今天我使用了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))
今天我使用了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))
gmpy2
库:import gmpy2
print(gmpy2.iroot(4913, 3))
# (mpz(17), True)
print(gmpy2.iroot(4913 + 1, 3))
# (mpz(17), False)
该函数会告诉您计算结果的精确性。
还可以查看Python中的对数精度和浮点数运算是否有误?相关问题。
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))
Decimal(4913).ln() / Decimal(17).ln()
- Gabriel