Python中的不准确对数 [英] Inaccurate Logarithm in Python
问题描述
我用2的其他权力做了同样的事情,它完美的工作。我跑了'log10(2 ** 31)/ log10(2)',我得到了一轮31.0我试着在Python 3.0.1中运行相同的原始函数,假设它是在一个更高级的版本中修复的。
为什么会发生这种情况?是否有可能在Python中的数学函数中有一些不准确的地方?
这是计算机算术的期望。它遵循特定的规则,例如 IEEE 754 ,可能与您所学的数学不匹配在学校里。
如果实际上是 ,那么使用Python的 I work daily with Python 2.4 at my company. I used the versatile logarithm function 'log' from the standard math library, and when I entered log(2**31, 2) it returned 31.000000000000004, which struck me as a bit odd. I did the same thing with other powers of 2, and it worked perfectly. I ran 'log10(2**31) / log10(2)' and I got a round 31.0 I tried running the same original function in Python 3.0.1, assuming that it was fixed in a more advanced version. Why does this happen? Is it possible that there are some inaccuracies in mathematical functions in Python? This is to be expected with computer arithmetic. It is following particular rules, such as IEEE 754, that probably don't match the math you learned in school. If this actually matters, use Python's decimal type. Example:
这篇关于Python中的不准确对数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
pre > 从十进制导入Decimal,Context
ctx = Context(prec = 20)
two = Decimal(2)
ctx.divide(ctx.power(two,Decimal (31))。ln(ctx),two.ln(ctx))
from decimal import Decimal, Context
ctx = Context(prec=20)
two = Decimal(2)
ctx.divide(ctx.power(two, Decimal(31)).ln(ctx), two.ln(ctx))