比较从float和string创建的Python小数 [英] Comparing Python Decimals created from float and string

查看:77
本文介绍了比较从float和string创建的Python小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能解释为什么以下三个示例不完全相同吗?

Can someone explain why the following three examples are not all equal?

ipdb> Decimal(71.60) == Decimal(71.60)
True
ipdb> Decimal('71.60') == Decimal('71.60')
True
ipdb> Decimal(71.60) == Decimal('71.60')
False

在Python中创建十进制对象的正确方法? (即,作为字符串还是作为浮点数)

Is there a general 'correct' way to create Decimal objects in Python? (ie, as strings or as floats)

推荐答案

浮点数(默认情况下使用的是基数2)。71.6不能准确地以2为底进行表示。(想想以10为底的1/3之类的数字)。

Floating point numbers, what are used by default, are in base 2. 71.6 can't be accurately represented in base 2. (Think of numbers like 1/3 in base 10).

因此,它们将被转换为小数位作为浮点数可以表示。因为基数2中的数字71.6会一直持续下去,并且您几乎肯定没有无限的记忆可玩,所以计算机决定用更少的位数来表示它。

Because of this, they will be converted to be as many decimal places as the floating point can represent. Because the number 71.6 in base 2 would go on forever and you almost certainly don't have infinate memory to play with, the computer decides to represent it (well, is told to) in a fewer number of bits.

如果要使用字符串代替,程序可以使用一种算法将其完全转换,而不是从模糊的四舍五入的浮点数开始。

If you were to use a string instead, the program can use an algorithm to convert it exactly instead of starting from the dodgy rounded floating point number.

>>> decimal.Decimal(71.6)
Decimal('71.599999999999994315658113919198513031005859375')

>>> decimal.Decimal("71.6")
Decimal('71.6')

但是,如果您的数字完全可以表示为浮点数,也可以像字符串一样精确

However, if your number is representable exactly as a float, it is just as accurate as a string

>>> decimal.Decimal(71.5)
Decimal('71.5')

这篇关于比较从float和string创建的Python小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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