*5.23(演示抵消错误)当处理一个很大的数字和一个很小的数字的时候,会产生一个抵消错误(cancellation error)。大的数字可能会略去很小的数。例如,100000000.0 + 0.000000001等于100000000.0。为了避免抵消错误,从而获得更加精确的结果,谨慎选择计算的次序。比如,在计算下面的数列时,从右到左计算要比从左到右计算得到的结果更精确: 编写程序对上面的数列从左到右和从右到左计算的结果进行比较,这里取n=50000。 *5.23(Demonstrate cancellation errors) A cancellation error occurs when you are manipulating a very large number with a very small number. The large number may cancel out the smaller number. For example, the result of 100000000.0 + 0.000000001 is equal to 100000000.0. To avoid cancellation errors and obtain more accurate results, carefully select the order of computation. For example, in computing the following summation, you will obtain more accurate results by computing from right to left rather than from left to right: Write a program that compares the results of the summation of the preceding series, computing from left to right and from right to left with n = 50000.
参考代码:
package chapter05;publicclassCode_23{publicstaticvoidmain(String[] args){finalint N =50000;double sumFromLeftToRight,sumFromRightToLeft;
sumFromLeftToRight = sumFromRightToLeft =0;for(int i =1;i <= N;i++)
sumFromLeftToRight +=1.0/ i;for(int i = N;i >=1;i--)
sumFromRightToLeft +=1.0/ i;
System.out.println("The result of summation from left to right is "+ sumFromLeftToRight);
System.out.println("The result of summation from right to left is "+ sumFromRightToLeft);}}
结果显示:
The result of summation from left to right is 11.397003949278504
The result of summation from right to left is 11.397003949278519
Process finished with exit code 0