黑马程序员___求解多项式

----------------------android培训java培训、期待与您交流! ----------------------

/**
 *  求多项式方程的一个近似解
 *	f(x) = 2x^3 -x^2 -25x-12;
 *  求解思路:
 *  设r是方程f(x)=0的根,选取x0作为r初始近似值,
 *  过点(x0,f(x0)做曲线y=f(x)的切线L,L的方程为y=f(x0)+df(x0)(x-x0),
 *  求出L与x轴交点的横坐标x1=x0-f(x0)/df(x0),称x1为r的一次近似值,
 *  过点(x1,f(x1))做曲线y=f(x)的切线,
 *  并求该切线与x轴的横坐标x2=x1-f(x1)/df(x1)称x2为r的二次近似值,
 *  重复上述过程,得r的近似值序列{Xn},其中Xn+1=Xn-f(Xn)/df(Xn),
 *  称为r的n+1次近似值
 */
public class NewtonIterationToSolveEquation {
	
	private double f(double x){
		return 2*Math.pow(x, 3) - Math.pow(x, 2) - 25*x - 12;
	}
	
	private double df(double x){
		return 6*Math.pow(x, 2) - 2*x -25;
	}
	
	private double answer(double t){
		double x , x0 , y , dy;		
		x = t;
		x0 = 0;
		
		while(Math.abs(x - x0) >= 1e-5){
			x0 = x;
			y = f(x);//原函数
			dy = df(x);//导函数
			
			x = x0 - y/dy;
		}
		
		return x0;
	}
	
	public static void main(String[] args) {
		NewtonIterationToSolveEquation nitse = new NewtonIterationToSolveEquation();
		//传入一个非零常数即可得到一个近似解。
		System.out.println(nitse.answer(1));//-0.49999999992372396 接近-1/2
		System.out.println(nitse.answer(2));//-3.0000010996411954 接近-3
		System.out.println(nitse.answer(3));//4.000000000430927	 接近4		
	}
	
}


---------------------- android培训java培训、期待与您交流! ----------------------

详细请查看:http://edu.csdn.net/heima


你可能感兴趣的:(程序设计)