简体   繁体   English

Python3确定对数是否“完美”,即浮点数没有余数

[英]Python3 Determine if logarithm is “perfect,” i.e., no remainder on float

Problem statement:问题陈述:

I am trying to determine if a logarithm is "perfect," ie, there is no remainder.我试图确定一个对数是否“完美”,即没有余数。 The issue I am having is that math.log() always returns a float.我遇到的问题是math.log()总是返回一个浮点数。

I read this: https://docs.python.org/3/tutorial/floatingpoint.html我读到这个: https://docs.python.org/3/tutorial/floatingpoint.html

Here is my current solution:这是我目前的解决方案:

import sys
import math


def is_even_log(argument, base):
    x = math.log(argument, base)  # yields float

    numerator, denominator = x.as_integer_ratio()

    print(
        f"numeratorerator: {numerator}, "
        f"denominatorominator: {denominator}")

    if numerator % denominator == 0:
        print(f"Log base {base} of {argument} is even")
        return True
    else:
        print(f"Log base {base} of {argument} is not even")
        return False


is_even_log(int(sys.argv[1]), int(sys.argv[2]))

Question问题

Just curious if anyone has better way to do this?只是好奇是否有人有更好的方法来做到这一点? I would imagine that I could access some property of the PyObject which indicates if there is a remainder or not.我想我可以访问 PyObject 的某些属性,该属性指示是否存在余数。

You can round the logarithm to the nearest integer, and check if it's correct by exponentiating back up again:您可以将对数四舍五入到最接近的 integer,并通过再次取幂来检查它是否正确:

def is_even_log(argument, base):
    return argument == base**round(math.log(argument, base))

Log b in base i equals x is equivalent to b equals i to the power x.以 i 为底的 log b 等于 x 等价于 b 等于 i 的 x 次方。 So the code would be:所以代码是:

def is_even_log(arg, base):
    x = math.log(arg, base)
    return arg == base ** int(x+1/2) 

As the int function returns the truncation of a float, int(x+1/2) returns the rounded number.由于 int function 返回浮点数的截断,因此int(x+1/2)返回四舍五入的数字。 This solution works for integers (both arg and base) because in this case the if statement is a comparaison between integers此解决方案适用于整数(arg 和 base),因为在这种情况下,if 语句是整数之间的比较

Testing the equality of floats is not recommended anyways because of the approximations.由于近似值,无论如何都不建议测试浮点数的相等性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM