- // binarySearch.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include <CMATH>
- #include <IOSTREAM>
- using namespace std;
- // 非线性方程
- double func(double x)
- {
- return 2*x*x*x-5*x-1;
- }
- // 二分法
- double BinarySearch(double a, double b, double err)
- {
- err = fabs(err);
- double c = (a + b) / 2; // 取中间值
- while(fabs(func(c)) > err && func(a-b) > err)
- {
- if ((func(c) * func(b)) < 0)
- {
- a = c;
- }
- if((func(c) * func(a)) < 0)
- {
- b = c;
- }
- c = (a + b) / 2; // 二分法确定新区间
- }
- return c;
- }
- int main(int argc, char* argv[])
- {
- double a = 1.0, b = 2.0;
- double err = 1e-10;
- double result;
- result = BinarySearch(a ,b, err);
- cout<<result<<endl;
- return 0;
- }
非线性方程二分法求解
最新推荐文章于 2024-07-29 00:58:39 发布