1

目前我正在为牛顿法创建(尝试)一个程序,它假设允许你猜测初始根并给你根。但我不知道如何把 x1=x0-f(x0)/f(x0) 也需要一个循环这是我目前的代码:

import java.util.Scanner;

public class NewtonsMethod {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Please enter your guess for the root:");
        double x = keyboard.nextDouble();
        double guessRootAnswer =Math.pow(6*x,4)-Math.pow(13*x,3)-Math.pow(18*x,2)+7*x+6;
            for(x=x-f(x)/f(x));

        System.out.println("Your answer is:" + guessRootAnswer);

    }
}
4

1 回答 1

4

您错误地说明了牛顿法的工作原理:

正确的公式是:

x n+1 <= x n -f(x n )/f '(x n )

请注意,第二个函数是第一个函数的一阶导数。
一阶导数的外观取决于函数的确切性质。

如果你知道是什么f(x)样子的,那么在编写程序时,你也可以填写一阶导数的代码。如果您必须在运行时弄清楚它,它看起来更像是一项艰巨的任务。

以下代码来自:http
://www.ugrad.math.ubc.ca/Flat/newton-code.html 演示了这个概念:

class Newton  {

    //our functio f(x)
    static double f(double x) {
        return Math.sin(x);
    }

    //f'(x) /*first derivative*/
    static double fprime(double x) {
        return Math.cos(x);
    }

    public static void main(String argv[]) {

        double tolerance = .000000001; // Stop if you're close enough
        int max_count = 200; // Maximum number of Newton's method iterations

/* x is our current guess. If no command line guess is given, 
   we take 0 as our starting point. */

        double x = 0;

        if(argv.length==1) {
            x= Double.valueOf(argv[0]).doubleValue();
        }

        for( int count=1;
            //Carry on till we're close, or we've run it 200 times.
            (Math.abs(f(x)) > tolerance) && ( count < max_count); 
             count ++)  {

            x= x - f(x)/fprime(x);  //Newtons method.
            System.out.println("Step: "+count+" x:"+x+" Value:"+f(x));
        }     
        //OK, done let's report on the outcomes.       
        if( Math.abs(f(x)) <= tolerance) {
            System.out.println("Zero found at x="+x);
        } else {
            System.out.println("Failed to find a zero");
        }
    }   
}
于 2013-10-09T20:34:49.887 回答