我有这段代码,应该使用割线法计算 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
不会引发异常。它返回NaN
。你应该check for that而不是 try catch 异常。
xnew = xold2 - (fxold2 * (xold2 - xold1))/(fxold2 - fxold1);
if(Double.isNaN(xnew)){
System.out.println("No solution for this starting point.");
break;
}
关于java - 处理虚数,跳跃捕捉,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33878463/