为什么十进制乘法有些不准确? [英] Why is decimal multiplication slightly inaccurate?

查看:79
本文介绍了为什么十进制乘法有些不准确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
为什么要对浮点数进行简单的数学运算在VB.Net和Python中返回意外(不准确的)结果?

Possible Duplicate:
Why do simple math operations on floating point return unexpected (inacurate) results in VB.Net and Python?

为什么在Python中会发生这种情况?

Why does this happen in Python:

>>> 
>>> 483.6 * 3
1450.8000000000002
>>> 

我知道其他语言也会发生这种情况,因此我没有问如何解决此问题.我知道你可以做到:

I know this happens in other languages, and I'm not asking how to fix this. I know you can do:

>>> 
>>> from decimal import Decimal
>>> Decimal('483.6') * 3
Decimal('1450.8')
>>> 

那么究竟是什么导致这种情况发生呢?为什么在进行这样的数学运算时小数会变得有点不准确?

So what exactly causes this to happen? Why do decimals get slightly inaccurate when doing math like this?

计算机是否有任何特定原因无法解决此问题?

Is there any specific reason the computer doesn't get this right?

推荐答案

请参见 Python文档在浮点数上.本质上,当您创建浮点数时,您使用的是基数2算法.就像1/3是.333 ....到无穷大一样,因此大多数浮点数不能精确地以2为底表示.因此,您的结果.

See the Python documentation on floating point numbers. Essentially when you create a floating point number you are using base 2 arithmetic. Just as 1/3 is .333.... on into infinity, so most floating point numbers cannot be exactly expressed in base 2. Hence your result.

Python解释器和某些其他语言之间的区别是其他语言可能不会显示这些多余的数字.这不是Python中的错误,而是硬件如何使用浮点算法进行计算.

The difference between the Python interpreter and some other languages is that others may not display these extra digits. It's not a bug in Python, just how the hardware computes using floating-point arithmetic.

这篇关于为什么十进制乘法有些不准确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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