Python 3中math.log的错误答案

6

今天我使用了math.log() 函数来获取以给定底数17为底数的4913的对数。答案是3,但当我运行下面的代码时,结果是2.9999999999999996。

1)这是因为math.log(x, b)的计算是 log(x) / log(b) 吗?

2)有没有办法得到正确的答案3?

import math
print(math.log(4913,17))

你的猜测(#1)很有可能是正确的。至于#2,有许多方法。你是否事先知道答案将是一个整数? - President James K. Polk
2
更好的重复问题:Python中的对数精度 - nwellnhof
@nwellnhof,我重新打开了这个问题,因为原帖作者也想知道如何获得一个整数解。 - hiro protagonist
可能是浮点数计算有问题吗?的重复。 - Peter O.
2个回答

3

非常感谢您的回答! - Saisiot

2
  1. Yes, the documentation says so explicitly.
  2. Another solution is to use the Decimal class, from the "decimal" library:

    import math
    from decimal import Decimal, getcontext
    getcontext().prec = 6
    Decimal(math.log(4913))/Decimal(math.log(17))
    

2
Decimal(4913).ln() / Decimal(17).ln() - Gabriel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接