Python中的不准确对数 [英] Inaccurate Logarithm in Python

查看:226
本文介绍了Python中的不准确对数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我每天在我公司的Python 2.4上工作。我使用了标准数学库中的多功能对数函数'log',当我输入log(2 ** 31,2)时,它返回31.000000000000004,这让我觉得有点奇怪。

我用2的其他权力做了同样的事情,它完美的工作。我跑了'log10(2 ** 31)/ log10(2)',我得到了一轮31.0我试着在Python 3.0.1中运行相同的原始函数,假设它是在一个更高级的版本中修复的。



为什么会发生这种情况?是否有可能在Python中的数学函数中有一些不准确的地方?

解决方案

这是计算机算术的期望。它遵循特定的规则,例如 IEEE 754 ,可能与您所学的数学不匹配在学校里。



如果实际上是 ,那么使用Python的
pre > 从十进制导入Decimal,Context
ctx = Context(prec = 20)
two = Decimal(2)
ctx.divide(ctx.power(two,Decimal (31))。ln(ctx),two.ln(ctx))


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:

from decimal import Decimal, Context
ctx = Context(prec=20)
two = Decimal(2)
ctx.divide(ctx.power(two, Decimal(31)).ln(ctx), two.ln(ctx))

这篇关于Python中的不准确对数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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