第五章第二十三题(演示抵消错误)(Demonstrate cancellation errors)

第五章第二十三题(演示抵消错误)(Demonstrate cancellation errors)

  • *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;

public class Code_23 {
    public static void main(String[] args) {
        final int 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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值