自定义一个函数,实现用牛顿迭代法求方程的根。
方程为ax^3+bx^2+cx+d=0。系数a, b, c, d的值依次为1, 2, 3, 4,由主函数输入。求x在1附近的一个实根。求出根后由主函数输出。
牛顿迭代法的公式是x = x0 - f(x0) / f '(x),精度为10^-5。
#include
#include
#include
using namespace std;
float fun1(float x)
{
return x*x*x + 2*x*x + 3*x + 4;
}
float fun2(float x)
{
return 3*x*x + 4*x + 3;
}
int main()
{
float x , f1 ,f2 , d;
x = 1;
do
{
f1 = fun1( x);
f2 = fun2( x);
d = f1 / f2;
x -= d;
}
while(fabs(d) > 1e-5);//这一句fabs没学过不懂,能换别的方式表达吗
printf("%.5f\n\n",x);
return 0;
}
}