2013-10-09 63 views
0

目前我正在为牛顿方法创建(尝试)一个程序,并假设它允许您猜测初始根并给出根。但我无法弄清楚如何把 X1 = X-F(X0)/ F(X0)还需要一个循环 这里是我的代码目前:牛顿方法Java

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); 

    } 
} 
+0

那么它需要一个函数来猜测根,你在那里会得到F(X)?也许问用户?也许你已经拥有它,只是想让用户猜测根?另外牛顿函数是一种迭代方法,你的x1(might)可以靠近,但是你什么时候才能知道你已经找到根? – arynaq

+0

是的,我只是想让用户猜根。 – user2809115

回答

3

你说错了如何牛顿法作品:

正确公式为:

X n + 1个 < = X ñ -f(X ñ)/ F“(X ñ

请注意,第二个函数是第一个函数的一阶导数。
一阶导数看起来如何取决于函数的确切性质。

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