在运用牛顿迭代法的过程中出现了一些问题
题目:用牛顿迭代法求方程2x³-4x²+3x-6=0在1.5附近的结果。
以下几种方法希望可以帮我看看错在哪里呀www
虽然差别都很小,但是我很多细节不太理解
方法一:
do while结果为2.3333333
#include<iostream>
using namespace std;
#include<math.h>
double fun(double x,double a,double b,double c,double d);
double dfun(double x,double a,double b,double c,double d);
int main()
{double a,b,c,d;
double fun(double x,double a,double b,double c,double d);
double dfun(double x,double a,double b,double c,double d);
cin>>a>>b>>c>>d;
double f,df;
double x=1.5,x2,h;
do
{
x2=x;
f= fun(x,a,b,c,d);
df= dfun(x,a,b,c,d);
h=double(f/df);
x2=x-h;
x=x2;
}while(fabs(x2-x)>=1e-5);
cout<<"方程在1.5附近的结果为:" <<x<<endl;
}
double fun(double x,double a,double b,double c,double d){
double f;
f=a*x*x*x+b*x*x+c*x+d;
return f;
}
double dfun(double x,double a,double b,double c,double d){
double df;
df=3*a*x*x+2*b*x+c;
return df;
}
方法二:
while结果是2
#include<iostream>
using namespace std;
#include<math.h>
double fun(double x,double a,double b,double c,double d);
double dfun(double x,double a,double b,double c,double d);
int main(){
double a,b,c,d;
cin>>a>>b>>c>>d;
double x1=1.5,x2;
x2=x1-fun(x1,a,b,c,d)/dfun(x1,a,b,c,d);
while(fabs(x1-x2)>=1e-6)
//while是当条件不满足时才进行循环,所以这里应该是题目中要求的范围的补集
{
x1=x2;
x2=x1-fun(x1,a,b,c,d)/dfun(x1,a,b,c,d);
}
cout<<"方程在1.5附近的结果为" <<x1<<endl;
return 0;
}
double fun(double x,double a,double b,double c,double d){
double f=a*x*x*x+b*x*x+c*x+d;
return f;
}
double dfun(double x,double a,double b,double c,double d){
double df=3*a*x*x+2*b*x+c;
return df;
}
方法三:dowhile结果也是2
#include<iostream>
using namespace std;
#include<math.h>
double fun(double x, double a, double b, double c, double d)
{
double f;
f = double(a * x * x * x + b * x * x + c * x + d);
return f;
}
double dfun(double x, double a, double b, double c, double d)
{
double df;
df = double(3 * a * x * x + 2 * b * x + c);
return df;
}
int main()
{
double a, b, c, d;
cin >> a >> b >> c >> d;
double f, df, h;
double x = 1.5, x0;
do
{
x0 = x;
f = fun(x0,a,b,c,d);
df = dfun(x0,a,b,c,d);
h = double(f / df);
x = x0 - h;
} while (fabs(x-x0) >= 1e-5);
cout << "方程在1.5附近的结果为:" << x << endl;
}
方法四:while结果也是2
#include<iostream>
using namespace std;
#include<math.h>
double fun(double x, double a, double b, double c, double d)
{
double f;
f = double(a * x * x * x + b * x * x + c * x + d);
return f;
}
double dfun(double x, double a, double b, double c, double d)
{
double df;
df = double(3 * a * x * x + 2 * b * x + c);
return df;
}
int main()
{
double a, b, c, d;
cin >> a >> b >> c >> d;
double f, df, h;
double x = 1.5, x0;
x0 = x;
f = fun(x0, a, b, c, d);
df = dfun(x0, a, b, c, d);
h = double(f / df);
x = x0 - h;
while (fabs(x - x0) >= 1e-5)
{
x0 = x;
f = fun(x0,a,b,c,d);
df = dfun(x0,a,b,c,d);
h = double(f / df);
x = x0 - h;
}
cout << "方程在1.5附近的结果为:" << x << endl;
}