C++实现牛顿迭代法求解非线性方程

#include
#define e 2.718281828489
#define eps 0.5*1e-5
#define eps2 1e-12
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
const ll N = 1e5;

double f1(double x)
{
	return x*x*x - 3.0*x -1.0;
}
double f1_dc(double x)
{
	return 3.0*x*x -3.0;
}


double NewtonRaphson(double x, double (*f)(double), double (*f_dc)(double),int n)
{
	double next_x = x;
	next_x = x - f(x) / f_dc(x);
	int count = 1;
	while( fabs(x-next_x)/(1.0+fabs(x)) > eps )
	{
		x = next_x;
		next_x = x - f(x) / f_dc(x);
		count++;
		if(count>=n)
		{
			cout<<"超过最大迭代步数"< eps)
	{
		double temp = x1;
		double k = (x-x1) / (f(x) - f(x1));
		x1 = x - k * f(x);
		count++;
		if(count>=n)
		{
			cout<<"迭代次数超过限制"< eps )
	{
		x = next_x;
		k = ( f(x+eps2) - f(x) ) / eps2;
		next_x = x - f(x) / k;
		count++;
		if(count>=n)
		{
			cout<<"超过最大迭代步数"<>x;
	double ans = NewtonRaphson(x,f1, f1_dc, 30);
	double ans2 = NewtonRaphson3(x,f1, 30);
	printf("%.9f\n", ans);
	printf("%.9f\n", ans2);
	cout<<"Enter two initial values:"<>a>>b;
	double ans3 = NewtonRaphson2(a, b, f1, 30);
	printf("%.9f\n", ans3);
	
	return 0;
}

 

你可能感兴趣的:(数值计算方法,C++)