简体   繁体   English

将float转换为int会导致错误的值

[英]Casting float to int results in incorrect value

The result variable will hold the value 9.0. 结果变量将保留值9.0。 Why then when I print using "%d" does print return 8? 为什么当我使用“%d”打印时,打印返回8?

result = (((1.7526 % 0.3048) / 0.3048) * 12)
print(result)        #prints 9.0
print("%f" % result) #prints 9.0
print("%d" % result) #prints 8

Floating point arithmetic is inherently imprecise. 浮点运算本质上是不精确的。 In Python calculations are typically performed to double precision. 在Python中,计算通常以双精度进行。 Your numbers are not exactly representable to double precision and so are subject to rounding errors. 您的数字不能精确表示为双精度,因此会产生舍入误差。 On my machine, result is 8.9999999999999929 . 在我的机器上, result8.9999999999999929

>>> result = (((1.7526 % 0.3048) / 0.3048) * 12)
>>> result
8.9999999999999929
>>> print result
9.0
>>> int(result)
8

When you print the value it gets rounded to 9.0 , but the actual value stored in result in less than 9.0 . 当您打印的价值它被四舍五入到9.0 ,而是存储在实际值result小于9.0 So, when you convert result to an integer, it is truncated to 8 . 因此,当您将result转换为整数时,它将被截断为8

The key issue is that of representability of values. 关键问题是价值的可表示性。 Neither 1.7526 nor 0.3048 are exactly representable in double precision as can easily be seen in the Python interpreter. 正如在Python解释器中可以轻易看到的那样,无论是1.7526还是0.3048都不能以双精度精确表示。

>>> 1.7526
1.7525999999999999
>>> 0.3048
0.30480000000000002

The moral of the story is that you should not expect exact arithmetic when using floating point values. 这个故事的寓意是,使用浮点值时,您不应期望精确的算术运算。 The seminal discussion of this topic is: What Every Computer Scientist Should Know About Floating-Point Arithmetic . 关于该主题的开创性讨论是: 每个计算机科学家都应该了解有关浮点算法的知识

The %d truncates your value which is why you get 8. %d截断您的值,这就是为什么得到8的原因。

Floating point representation in a binary system is an approximation meaning the value that displayed at 9.0 was internally less than 9 and therefore truncated down to 8. 二进制系统中的浮点表示形式是一个近似值,表示在9.0处显示的值内部小于9,因此被截断为8。

For example all of these yield 3. 例如,所有这些产生3。

In [19]: i = 3.1
In [20]: print '%d' %i
3

In [21]: i = 3.4
In [22]: print '%d' %i
3

In [23]: i = 3.7
In [24]: print '%d' %i
3

In [25]: i = 3.9999
In [26]: print '%d' %i
3

This Wikipeadia article provides some additional background on floating point representation. Wikipeadia的这篇文章提供了有关浮点表示的其他背景。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM