【问题标题】:Newton's Method Java牛顿法 Java
【发布时间】:2013-10-17 08:58:53
【问题描述】:

目前我正在为牛顿法创建(尝试)一个程序,它假设允许您猜测初始根并给您根。但我无法弄清楚如何放置 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);

    }
}

【问题讨论】:

  • 嗯,它需要一个函数来猜测根,你从哪里得到 f(x)?也许问用户?也许您已经拥有它并且只是希望用户猜测根目录?牛顿函数也是一种迭代方法,您的 x1(可能)越来越接近,但您什么时候知道您已经找到了根?
  • 是的,我只是想让用户猜测根目录。

标签: java loops newtons-method jcreator


【解决方案1】:

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

正确的公式是:

xn+1n-f(xn)/f '(xn )

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

如果你知道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");
        }
    }   
}

【讨论】:

    猜你喜欢
    • 2017-09-15
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    • 2022-01-16
    • 2012-02-16
    • 2015-07-28
    • 2019-06-27
    • 1970-01-01
    相关资源
    最近更新 更多