目前我正在为牛顿方法创建(尝试)一个程序,它假设允许你猜测初始根并给你根。但我无法弄清楚如何把它 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);
}
}
答案 0 :(得分:3)
你错误地说牛顿的方法是如何运作的:
正确的公式是:
x n + 1 < = x n -f(x n )/ 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");
}
}
}