1. 程式人生 > >牛頓迭代法(C++)

牛頓迭代法(C++)

牛頓迭代法(C++) 

摘自百度文庫

題目:給定方程        {{f}}(x) = \frac{{x^3 }}{3} - x = 0, 使用牛頓法解方程的根。

#include<iostream>
#include<string>
#include<cmath>
using namespace std;
double fd(double x)
{
	  double c = (x*x*x) / 3 - x;
	  double d = x*x - 1;
	  return (c / d);
}

void newton(double x0, double e)
{
	double a = x0;
	double x = x0 - fd(x0);
	int i=0;
	while (abs(x - a) > e)
	{   
		cout << a << endl;
		a = x;
		i++;   //迴圈次數
		x = x - fd(x);
			if (i > 50)
			{
				cout << "迭代失敗!" << endl;
				return ;
			}
	  }
	  cout << "迭代次數為:" << i << endl;
}

int main()
{
	double x0, e;
	cout << "請輸入x0的值:";
	cin >> x0;
	cout << "請輸入容許誤差:";
	cin >> e;
	newton(x0, e);
	return 0;
}