python - 如何使用 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 中使用对数来实现这一点。
解决方案
不要使用对数;它们依靠真正的算术来正确工作,而 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
。
推荐阅读
- python - 如何查看安装另一个软件包需要哪些软件包?
- java - 初始化 JFrame 窗口时出现黑屏
- python - 迭代多个列表并从中得出重要的模式
- javascript - REACT 中的图像解析、格式化、渲染
- sql - 如何将特定行转置为列
- python-3.x - 基于多列值拆分数据框
- spring - 为什么在这种情况下 Mockito doThrow 不抛出异常?与 mock 的零交互
- android - 首选项设置 - 如何在启用点击侦听器时禁用更改侦听器?
- materialize - 如何在搜索输入中更改 Materialise 标签图标的活动颜色
- java - 如何修复java代码以将结果显示为名称和分数