如何在Python中正确添加浮点数? [英] How to correctly add floating numbers in Python?

查看:83
本文介绍了如何在Python中正确添加浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在运行到100的循环中将 0.2 值添加到常量 x,其中x = 8 .

I am trying to add 0.2 value to constant x where x = 8 in a loop that runs to 100. Following is the code

 x = 8
>>> for i in range(100):
...     x += 0.2
...
>>> x

但是每次我得到不同的答案时,计算总是不正确的.我了解了浮点算术问题和局限性,但是应该有一些解决方法.我可以使用 doubles (如果存在)吗?我正在使用Python 2.7

but everytime I get different answer and calculation always incorrect. I read about Floating Point Arithmetic Issue and Limitations but there should be some way around this. Can I use doubles (if they exists) ? I am using Python 2.7

更新:

  import time
x=1386919679

while(1):

        x+=0.02
        print "xx %0.9f"%x
        b= round (x,2)
        print "bb %0.9f"%b

        time.sleep(1)

输出

xx 1386933518.586801529
bb 1386933518.589999914
xx 1386933518.606801510
bb 1386933518.609999895
xx 1386933518.626801491
bb 1386933518.630000114

所需的输出我想要正确的输出,我知道如果只写 print x ,那将是准确的.但是我的应用程序要求我应以9精度打印结果.我是新手,所以请客气.

Desired output I want correct output, I know If just write print x it will be accurate. But my application require that I should print results with 9 precision. I am newbie so please be kind.

推荐答案

当然可以使用双精度浮点.默认情况下,您已经在使用它.

You can use double-precision floating point, sure. You're already using it by default.

关于它的解决方法: x + = 0.2 * 100

我知道这听起来很简单,但是解决浮点不精确度的方法不是设置 FLOATING_POINT_IMPRECISION = False .这是表示形式的基本限制,没有通用的解决方案,只有特定的解决方案(以及适用于特定情况组的模式).

I know that sounds facile, but the solution to floating point imprecision is not setting FLOATING_POINT_IMPRECISION = False. This is a fundamental limitation of the representation, and has no general solution, only specific ones (and patterns which apply to groups of specific situations).

还有一种可以完全存储 0.2 的有理数类型,但是对于大多数实际用例来说,这是不值得考虑的.

There's also a rational number type which can exactly store 0.2, but it's not worth considering for most real-world use cases.

这篇关于如何在Python中正确添加浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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