亲宝软件园·资讯

展开

C++二分法求连续一元函数根 C++实现二分法求连续一元函数根

Alex山南水北 人气:0

设计一个用二分法求连续一元函数根的通用函数solve
此函数有三个参数:

函数的返回值为求得的解

要求编写main函数如下:

double fun(double x)
{
 double y;
 y=4*pow(x,3)-6*pow(x,2)+3*x-2;
 return y;
}

int main()
{
 cout<<"4*x^3-6*x^2+3*x-2=0在区间(1,2)的根为 x="<<solve(fun,1,2);
 return 0;
}

C++实现:

#include <iostream>
#include <cmath>

using namespace std;

double solve(double (*fun)(double x), double a, double b);

double fun(double x);

int main() {
 cout << "4*x^3-6*x^2+3*x-2=0在区间(1,2)的根为 x=" << solve(fun, 1, 2);
 return 0;
}

double solve(double (*fun)(double x), double a, double b) {
 double i = b - a;
 double c = (a + b) / 2;
 while (i > 0.0000001) {
 i = b - a;
 if (fun(c) == 0)return c;
 if (fun(c) * fun(a) < 0) {
  b = c;
  c = (a + b) / 2;
 } else {
  a = c;
  c = (a + b) / 2;
 }
 }
 return c;
}

double fun(double x) {
 double y;
 y = 4 * pow(x, 3) - 6 * pow(x, 2) + 3 * x - 2;
 return y;
}

总结:

加载全部内容

相关教程
猜你喜欢
用户评论