为什么从最大浮点数到最小浮点数的加法比从最小浮点数到最大浮点数的加法不准确? [英] Why adding from biggest to smallest floating-point numbers is less accurate than adding from smallest to biggest?

查看:162
本文介绍了为什么从最大浮点数到最小浮点数的加法比从最小浮点数到最大浮点数的加法不准确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Java教科书指出,在处理浮点数时,从最大到最小的加法不如从最小到最大的加法精确.但是,他没有继续明确解释为什么会这样.

My Java textbook states that adding from biggest to smallest is less accurate than adding from smallest to biggest when dealing with floating-point numbers. However, he doesn't go on to clearly explain why this is the case.

推荐答案

浮点数的精度位数有限(float为6,double为15).计算

Floating point has a limited number of digits of precision (6 for float, 15 for double). The calculation

1.0e20d + 1 

给出结果1.0e20,因为没有足够的精度来表示数字

gives the result 1.0e20 because there is not enough precision to represent the number

100,000,000,000,000,000,001

如果您以最大的数字开头,那么任何比n数量级小的数字(其中n是6或15,具体取决于类型)都将完全不构成总和.从最小的数字开始,您可能会将几个较小的数字求和,这会影响最终的总数.

If you start with the largest number then any numbers more than n orders of magnitude smaller (where n is 6 or 15 depending on type) will not contribute to the sum at all. Start with the smallest and you might sum several smaller numbers into one that will affect the final total.

例如,会有所不同的地方

Where it would make a difference is, for example

1.0e20 + 1.0e4 + 6.0e4 + 3.0e4

假设精确度为15位小数位数(不是,请参见下面的链接文章,但示例中15位就足够了),如果您以较大的数字开头,那么其他任何一个都不会有所作为,因为太小.如果从较小的开始,则它们的总和为1.0e5,足以影响最终总数.

Assuming it's exactly 15 decimal digits precision (it's not, see the linked article below, but 15 is good enough for the example), if you start with the larger number, none of the others will make a difference because they're too small. If you start with the smaller ones, they add up to 1.0e5, which IS large enough to affect the final total.

请阅读每位计算机科学家应了解的有关浮动的知识-点算术

这篇关于为什么从最大浮点数到最小浮点数的加法比从最小浮点数到最大浮点数的加法不准确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆