为什么python十进制库不为某些输入返回指定数量的有效数字 [英] Why doesn't python decimal library return the specified number of signficant figures for some inputs
问题描述
注意事项:该问题与> 重要数字有关> 。 不是关于小数点后的位数或类似问题的问题。
NB: this question is about significant figures. It is not a question about "digits after the decimal point" or anything like that.
编辑:这问题不是 重复的十进制模块中的有效数字。这两个问题是关于完全不同的问题。我想知道为什么函数不返回特定输入的期望值。 十进制模块中的有效数字都没有答案。
EDIT: This question is not a duplicate of Significant figures in the decimal module. The two questions are asking about entirely different problems. I want to know why the function about does not return the desired value for a specific input. None of the answers to Significant figures in the decimal module address this question.
下面的函数应该返回具有指定有效位数的浮点数的字符串表示形式:
The following function is supposed to return a string representation of a float with the specified number of significant figures:
import decimal
def to_sigfigs(value, sigfigs):
return str(decimal.Context(prec=sigfigs).create_decimal(value))
乍看之下似乎可行:
print to_sigfigs(0.000003141592653589793, 5)
# 0.0000031416
print to_sigfigs(0.000001, 5)
# 0.0000010000
print to_sigfigs(3.141592653589793, 5)
# 3.1416
...但是
print to_sigfigs(1.0, 5)
# 1
最后一个表达式的期望输出(IOW,5个有效位数gure表示形式1.0)是字符串 1.0000。实际输出为字符串 1。
The desired output for the last expression (IOW, the 5-significant figure representation of 1.0) is the string '1.0000'. The actual output is the string '1'.
我误解了吗?这是十进制
中的错误吗?
Am I misunderstanding something or is this a bug in decimal
?
推荐答案
这是一个错误吗?我不知道,我认为文档不够紧,无法做出决定。肯定是令人惊讶的结果。
Is it a bug? I don't know, I don't think the documentation is tight enough to make that determination. It certainly is a surprising result.
可以用更多的逻辑来修复自己的函数。
It is possible to fix your own function with a little more logic.
def to_sigfigs(value, sigfigs):
sign, digits, exponent = decimal.Context(prec=sigfigs).create_decimal(value).as_tuple()
if len(digits) < sigfigs:
missing = sigfigs - len(digits)
digits = digits + (0,) * missing
exponent -= missing
return str(decimal.Decimal((sign, digits, exponent)))
这篇关于为什么python十进制库不为某些输入返回指定数量的有效数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!