非线性方程二分法求解

  1. // binarySearch.cpp : Defines the entry point for the console application.  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5.   
  6. #include <CMATH>  
  7. #include <IOSTREAM>  
  8.   
  9. using namespace std;  
  10.   
  11. // 非线性方程  
  12. double func(double x)  
  13. {  
  14.     return 2*x*x*x-5*x-1;     
  15. }  
  16.   
  17. // 二分法  
  18. double BinarySearch(double a, double b, double err)  
  19. {  
  20.     err = fabs(err);  
  21.     double c = (a + b) / 2;             // 取中间值  
  22.   
  23.     while(fabs(func(c)) > err && func(a-b) > err)  
  24.     {  
  25.         if ((func(c) * func(b)) < 0)  
  26.         {  
  27.             a = c;  
  28.         }  
  29.         if((func(c) * func(a)) < 0)  
  30.         {  
  31.             b = c;  
  32.         }  
  33.         c = (a + b) / 2;                // 二分法确定新区间  
  34.     }  
  35.     return c;  
  36. }  
  37.   
  38. int main(int argc, char* argv[])  
  39. {  
  40.     double a = 1.0, b = 2.0;  
  41.     double err = 1e-10;  
  42.     double result;  
  43.   
  44.     result = BinarySearch(a ,b, err);  
  45.   
  46.     cout<<result<<endl;  
  47.   
  48.     return 0;  
  49. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值