1. 程式人生 > >程式基本演算法習題解析 採用迭代法使用牛頓切線法求解方程

程式基本演算法習題解析 採用迭代法使用牛頓切線法求解方程

求近似值的公式為:

x{_{n+1}}=x{_{n}}-f(x{_{n}})/f^{'}(x{_{n}}))

附上程式碼:

// Chapter6_3.cpp : Defines the entry point for the application.
// 採用迭代法使用牛頓切線法求解方程

#include "stdafx.h"
#include<iostream>
#include<math.h>
using namespace std;
//求函式值
float fun(float x,float a,float b,float c,float d)
{
	return a*x*x*x+b*x*x+c*x+d;
}
//求導數值
float funDiff(float x,float a,float b,float c)
{
	return 3*a*x*x+2*b*x+c;
}
//按照公式求近似值
float funResolve(float x,float a,float b,float c,float d)
{
	//滿足一定精度時輸出近似值
	if(abs(fun(x,a,b,c,d))<1e-6)
		return x;
	//不滿足精度時繼續迭代
	else
	{
		return funResolve(x-fun(x,a,b,c,d)/funDiff(x,a,b,c),a,b,c,d);
	}
}
int main()
{
	float a,b,c,d,resolve;
	cout << "input a,b,c,d: ";
	cin >> a >> b >> c >> d;
	resolve = funResolve(0,a,b,c,d);
	cout << "the resolve is: " << resolve << endl;
	system("pause");
	return 0;
}

執行結果如下: