問題描述
我每天都在公司使用 Python 2.4.我使用了標(biāo)準(zhǔn)數(shù)學(xué)庫中的通用對數(shù)函數(shù)log",當(dāng)我輸入 log(2**31, 2) 時(shí),它返回 31.000000000000004,這讓我覺得有點(diǎn)奇怪.
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.
我對 2 的其他冪也做了同樣的事情,而且效果很好.我跑了 'log10(2**31)/log10(2)' 得到了 31.0 輪
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
我嘗試在 Python 3.0.1 中運(yùn)行相同的原始函數(shù),假設(shè)它已在更高級的版本中得到修復(fù).
I tried running the same original function in Python 3.0.1, assuming that it was fixed in a more advanced version.
為什么會這樣?Python中的數(shù)學(xué)函數(shù)是否可能存在一些不準(zhǔn)確之處?
Why does this happen? Is it possible that there are some inaccuracies in mathematical functions in Python?
推薦答案
這對于計(jì)算機(jī)算術(shù)來說是意料之中的.它遵循特定規(guī)則,例如 IEEE 754,可能與您所學(xué)的數(shù)學(xué)不符在學(xué)校.
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.
如果這確實(shí)很重要,請使用 Python 的 十進(jìn)制類型.
If this actually matters, use Python's decimal type.
例子:
from decimal import Decimal, Context
ctx = Context(prec=20)
two = Decimal(2)
ctx.divide(ctx.power(two, Decimal(31)).ln(ctx), two.ln(ctx))
這篇關(guān)于Python中不準(zhǔn)確的對數(shù)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!