首页 > 解决方案 > 如何使用 Python3 中的对数属性确保一个数字是另一个数字的幂?

问题描述

我想检查一个数字 x 是否是另一个数字 y 的指数幂。我了解数学:使用对数。

但是,当我在 Python3 中使用 log() 函数执行此方法时,我得到了奇怪的结果。我想测试 243 是否是 3 的幂,它是,我的代码返回 False。我的代码如下:

power = log(n, 3)
if (int(power)) == power:
    return True

我得到 4.999999999999999 作为power. 我阅读了有关 Python3 中浮点和对数的精度和其他战术细节,并尝试了这些解决方案,但没有一个给出我知道就基本数学而言是正确的答案。

我试过这个:

from math import log
from decimal import Decimal, Context

class Power:
    def power_func(self, n: int) -> bool:
        if n == 0:
            return False
        ctx = Context(prec=20)
        power = log(n, Decimal(3))
        if (int(power)) == power:
            return True
        return False

我想我在这里缺少一些 Python 的基础知识,但不知道如何进一步进行。我知道完成这项任务的其他解决方案,但我想在 Python3 中使用对数来实现这一点。

标签: pythonpython-3.xmathlogarithm

解决方案


不要使用对数;它们依靠真正的算术来正确工作,而 Python 无法做到。

n相反,使用重复平方从底部接近。

def is_power_of(n, b):
    y = b
    # Compute y = b**2, b**4, ..., b**2**i until y reaches or exceeds n
    # i = 1
    while y < n:
        y = y * y
        # i *= 2

    # If we overshoot, divide by b until we either
    # reach n or get a non-zero remainder
    while y > n:
        y, r = divmod(y, b)
        # i -= 1
        if r:
            return False
    else:
        return y == n

请注意,如果函数返回 true,i将是这样的值b**i == n


推荐阅读