Inaccurate Logarithm in Python

前端 未结 9 1949
甜味超标
甜味超标 2020-12-04 01:37

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.0

9条回答
  •  伪装坚强ぢ
    2020-12-04 02:00

    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))
    

提交回复
热议问题