python 中以 3 为底的对数

Logarithm to base 3 in python

提问人:Goku - stands with Palestine 提问时间:9/2/2023 更新时间:9/2/2023 访问量:162

问:

我正在尝试使用 python 找到一个以 3 为底的数字的对数。

这是问题:

https://leetcode.com/problems/power-of-three/description/

我正在使用以下代码:

import math
math.log(k,3)

但是,对于某些测试用例,它失败了,例如(还有一些测试用例):

math.log(243,3)

#output
4.999999999999999

math.log(59049,3)

#output
9.999999999999998

我不想使用,因为它会四舍五入其他不是 3 的幂的数字。round()

这是我使用的完整代码:

class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        import math
        k = abs(n)
        if n<=0:
            return False
        return math.log(k,3) == int(math.log(k,3))

注意:我正在寻找涉及对数的解决方案。请随时要求任何澄清。

python-3.x 数学 对数

评论

0赞 Michael Butscher 9/2/2023
代码应该检查是否可以重复将 n 除以 3(无余数),直到结果为 1。

答:

1赞 dan04 9/2/2023 #1

这只是典型的浮点误差。回想一下,当你编写时,Python 实际上是在计算类似的东西,(自然)对数计算和除法都必须四舍五入到最接近的。math.log(x, 3)math.log(x) / math.log(3)float

但是,如果您用 代替 进行数学运算,则会保留精确性。intfloat

def is_power_of_three(n):
    if n <= 0:
        return False
    while n > 1:
        n, r = divmod(n, 3)
        if r != 0:
            return False
    return n == 1

这将检查您是否可以除以 3(没有余数),直到结果为 1。n

评论

0赞 Goku - stands with Palestine 9/2/2023
谢谢@dan04...我理解。它是对数的浮点误差。
2赞 eNeM 9/2/2023 #2

如果您仍然想要使用对数的答案。您可以使用以下代码。

def isPowerOfThree(self, n: int) -> bool:
    return n > 0 and n == 3**round(math.log(n, 3))

LeetCode 解决方案