识别浮点数的实际精度
Identify actual precision of a float
我正在与 returns 漂浮的 API 互动。我正在尝试计算 API 创建这些浮点数的小数位数。
例如:
# API returns the following floats.
>> 0.0194360600000000015297185740.....
>> 0.0193793800000000016048318230.....
>> 0.0193793699999999999294963970.....
# Quite clearly these are supposed to represent:
>> 0.01943606
>> 0.01937938
>> 0.01937937
# And are therefore ACTUALLY accurate to only 8 decimal places.
如何确定浮点数实际上精确到小数点后 8 位?一旦这样做,我就可以使用 "true" 值而不是不准确的浮点数来初始化 decimal.Decimal
实例。
编辑:API 返回的准确小数位数各不相同,并不总是 8!
如果您使用的是 Python 2.7 或 Python 3.1+,请考虑使用 repr()
内置函数。
下面是它如何在 Python 3.6 解释器中与您的示例一起工作。
>>> repr(0.0194360600000000015297185740)
'0.01943606'
>>> repr(0.0193793800000000016048318230)
'0.01937938'
>>> repr(0.0193793699999999999294963970)
'0.01937937'
这是可行的,因为 repr()
显示数字 的最小 精度,n
,仍然满足 float(repr(n)) == n
.
给定repr()
返回的字符串表示,你可以计算小数点右边的位数。
我正在与 returns 漂浮的 API 互动。我正在尝试计算 API 创建这些浮点数的小数位数。
例如:
# API returns the following floats.
>> 0.0194360600000000015297185740.....
>> 0.0193793800000000016048318230.....
>> 0.0193793699999999999294963970.....
# Quite clearly these are supposed to represent:
>> 0.01943606
>> 0.01937938
>> 0.01937937
# And are therefore ACTUALLY accurate to only 8 decimal places.
如何确定浮点数实际上精确到小数点后 8 位?一旦这样做,我就可以使用 "true" 值而不是不准确的浮点数来初始化 decimal.Decimal
实例。
编辑:API 返回的准确小数位数各不相同,并不总是 8!
如果您使用的是 Python 2.7 或 Python 3.1+,请考虑使用 repr()
内置函数。
下面是它如何在 Python 3.6 解释器中与您的示例一起工作。
>>> repr(0.0194360600000000015297185740)
'0.01943606'
>>> repr(0.0193793800000000016048318230)
'0.01937938'
>>> repr(0.0193793699999999999294963970)
'0.01937937'
这是可行的,因为 repr()
显示数字 的最小 精度,n
,仍然满足 float(repr(n)) == n
.
给定repr()
返回的字符串表示,你可以计算小数点右边的位数。