【发布时间】:2015-05-08 11:21:50
【问题描述】:
我正在编写一个程序以在 Java 中应用 Newton-Raphson 方法,其中包含一个方程:
f(x) = 3x - e^x + sin(x)
和
g(x) = f'(x) = 3- e^x + cos (x)
问题是当我试图解决论文中的方程以达到小于 (0.5%) 的误差
我得到了:
Xn |错误
Xo = 2 | ----------------------
X1 = 1.900158400 | 5.254%
X2 = 1.89012709 | 0.5307%
但是当我用 Java 编写程序时,它没有到达最后一行,这是必需的错误
(例如:X2 = 1.89012709)
它只显示第一行,即第一步
(X1 = 1.900158400)
我的 Java 代码是:
package newton.raphson.method;
public class NewtonRaphsonMethod {
// let f be a function defined as f(x) = 3x - e^x + sin(x)
public static double f (double x){
return (3*x-(Math.pow(Math.E, x))+Math.sin(x));
}
// let g be a function defined as g(x) = f'(x) = 3- e^x + cos (x)
public static double g (double x){
return (3-(Math.pow(Math.E, x))+Math.cos(x));
}
public static double NewtonRaphson (){
int iterations_number=0;
boolean cont = true;
double x0 , x1, Error=5000;
x0 =2;
x1=0;
while (cont){
x1 = x0 - (f(x0)/g(x0));
Error = (Math.abs(x1-x0)/x1)*100;
iterations_number++;
if (f(x1)<=0.05){
cont = false;
System.out.println("The Program did it in "+iterations_number+" Step(s)");
System.out.println("The root is: "+ x1);
System.out.println("The Error is: "+(Math.abs(x1-x0)/x1)*100+"%");
}
}
return x1;
}
public static void main(String[] args) {
NewtonRaphson();
}
}
输出是:
The Program did it in 1 Step(s)
The root is: 1.9001584993293807
The Error is: 5.254377500921955%
【问题讨论】:
-
我在您的代码中没有看到您计算或显示 x2 的任何地方
-
@azurefrog 我已经做了一个while循环,所以它应该自动计算它
-
您在问题中说您正在寻找“(例如:X2 = 1.89012709)”。您的代码中没有任何内容称为 x2。在“The Error is:
-
我希望while循环在误差小于0.5%时结束
-
那么你应该让你的while循环依赖于小于0.5%的错误。目前您在
f(x1) <= 0.05时终止,而不是在您的错误小于 0.05 时终止。
标签: java netbeans newtons-method