其他分享
首页 > 其他分享> > 使用牛顿迭代法求解n次方根

使用牛顿迭代法求解n次方根

作者:互联网

一、牛顿迭代法的原理

      1.问题描述: 令f(x)=x^{n},求f(x)=0的解

         牛顿迭代法:

         设r是f(x)=0的解,选取x0作为r的初始近似值,过点(x0,f(x0))做曲线 y = f(x) 的切线 ,则切线L与X轴的交点为

         过点(x1,f(x1))继续做曲线 y = f(x) 的切线L2:y=f(x1{_{}})+f^{^{'}}(x1)*(x-x1),则切线L2与X轴的交点为                        

         以此类推,可以得到r的近似值序列,其中x{_{n+1}}=x{_{n}}- \frac{f(x{_{n}})}{f{^{'}}(x{_{n}})}为r的近似值,称为牛顿迭代公式。

     2.java实现

import java.util.Scanner;

public class NewtonMethod {
	public static void main(String[] args){
	    double power=8;
            int exp=3;
	    double mis=0.01;
            Scanner scan=new Scanner(System.in);
	    power=Double.parseDouble(scan.next());
	    exp=Integer.parseInt(scan.next());
	    mis=Double.parseDouble(scan.next());
	    System.out.print(Newton(power,exp,mis));
	}
	
	/*
	 * @power表示幂
	 * @exp表示指数
	 * @mis表示容错范围
	 */
	public static double Newton(double power,int exp,double mis){
		double root=power;
		if((exp%2)==0&&mis<0){
			return Double.NaN;
		}
		
		while((root-power/Math.pow(root, exp-1))>mis*root){
			root=((exp-1)*root/exp+power)/Math.pow(root, exp-1);
		}
		return root;
	}
}

 

标签:power,求解,double,scan,方根,exp,迭代法,root,mis
来源: https://blog.csdn.net/keng1013750638/article/details/53160270