1. 程式人生 > >3元一次方程(牛頓迭代法求方程的根)

3元一次方程(牛頓迭代法求方程的根)

牛頓迭代方求方程根的公式原理請自行谷歌或百度相關資料,具體程式碼如下:

// test1.cpp : 定義控制檯應用程式的入口點。
//

#include "stdafx.h"
#include<stdio.h>
#include<math.h>

#define t_3
//#define t_2

int _tmain(int argc, _TCHAR* argv[])
{
	float solution(float a, float b, float c, float d);
	float solution1(float a,float b, float c);
	float a,b,c,d;
#ifdef t_3
	printf("input a,b,c,d:");
	scanf("%f,%f,%f,%f", &a,&b,&c,&d);
	printf("The solution is: x=%10.7f\n", solution(a,b,c,d));
#else if t_2
	printf("input a,b,c:");
	scanf("%f,%f,%f", &a,&b,&c);
	printf("The solution is: x=%10.7f\n", solution1(a,b,c));
#endif
	return 0;
}

float solution(float a,float b, float c,float d)
{
	float x=1,x0,f,f1;
	do
	{
		x0=x;
		f=((a*x0+b)*x0+c)*x0+d;
		f1=(3*a*x0+2*b)*x0+c;
		x=x0-f/f1;
	}while(fabs(x-x0)>=1e-5);
	return x;
}

float solution1(float a,float b, float c)
{
	float x=1,x0,f,f1;
	do
	{
		x0=x;
		f=(a*x0+b)*x0+c;
		f1=(3*a)*x0+b;
		x=x0-f/f1;
	}while(fabs(x-x0)>=1e-5);
	return x;
}


1.求解精度可根據自身情況進行調節,目前精度為1e-5