处理虚幻的数字,跳起来抓住
handle unreal numbers, jump to catch
我有这段代码应该使用正割法计算 f(x) = ln(x+1)+1
的根。
输入 xold1 = 0; xold2 = 1;
do {
try {
iteration++;
fxold1 = Math.log(xold1+1)+1;
fxold2 = Math.log(xold2+1)+1;
xnew = xold2 - (fxold2 * (xold2 - xold1))/(fxold2 - fxold1);
//Show iterations and results
System.out.println("Iteration: " + iteration + "; x = " + xnew);
diff = Math.abs(xnew-xold1);
//Replace old variables with new ones
xold2 = xold1;
xold1 = xnew;
} catch(Exception e) {
System.out.println("No solution for this starting point.");
}
} while(diff > 0.00001);
输出:
Iteration: 1; x = -1.4426950408889634
Iteration: 2; x = NaN
在纸上做数学运算,第二次迭代给出一个虚数:0.185125859 + 3.14159265 i。所以,这个想法是程序应该跳起来捕捉。为什么它没有这样做,我应该怎么做呢?谢谢!
通过查看 the docs
很容易回答这个问题
If the argument is NaN or less than zero, then the result is NaN.
如果您给它一个否定参数,Math.log
不会抛出异常。它returnsNaN
。您应该 check for that 而不是试图捕获异常。
xnew = xold2 - (fxold2 * (xold2 - xold1))/(fxold2 - fxold1);
if(Double.isNaN(xnew)){
System.out.println("No solution for this starting point.");
break;
}
我有这段代码应该使用正割法计算 f(x) = ln(x+1)+1
的根。
输入 xold1 = 0; xold2 = 1;
do {
try {
iteration++;
fxold1 = Math.log(xold1+1)+1;
fxold2 = Math.log(xold2+1)+1;
xnew = xold2 - (fxold2 * (xold2 - xold1))/(fxold2 - fxold1);
//Show iterations and results
System.out.println("Iteration: " + iteration + "; x = " + xnew);
diff = Math.abs(xnew-xold1);
//Replace old variables with new ones
xold2 = xold1;
xold1 = xnew;
} catch(Exception e) {
System.out.println("No solution for this starting point.");
}
} while(diff > 0.00001);
输出:
Iteration: 1; x = -1.4426950408889634
Iteration: 2; x = NaN
在纸上做数学运算,第二次迭代给出一个虚数:0.185125859 + 3.14159265 i。所以,这个想法是程序应该跳起来捕捉。为什么它没有这样做,我应该怎么做呢?谢谢!
通过查看 the docs
很容易回答这个问题如果您给它一个否定参数,If the argument is NaN or less than zero, then the result is NaN.
Math.log
不会抛出异常。它returnsNaN
。您应该 check for that 而不是试图捕获异常。
xnew = xold2 - (fxold2 * (xold2 - xold1))/(fxold2 - fxold1);
if(Double.isNaN(xnew)){
System.out.println("No solution for this starting point.");
break;
}