当我尝试使用函数替换功率功能时,即在提高到1/2时,请继续收回错误



对于分配,我必须使用一个函数创建一个程序,该函数替换了"功能函数",假设它出于任何原因而被损坏。当前的模型我的工作非常出色,但是当提高到1/2、1/4等时,我正在努力使它起作用。我知道这个问题在于浮子不与范围合作,但我个人不知道如何避免这种情况

def power (value, exp):
    num = 1.0 
    if exp>0:
        for function in range(exp):
            num = num * value 
    elif exp<0:
        for function in range(-exp):
            num = num / value
    else:
        num = 1
    return num
number = float(raw_input("Please enter a the base number you wish to raise to a power (no fractions, decimal allowed): "))
exponent = float(raw_input("Please enter the power you wish to raise the base number to (no fractions, decimal allowed): "))
print "Your base number was:", number
print "You rasied this number to the power of:", exponent
print "The ending product of this operation is:", power(number, exponent)

分数幂有点棘手,但是您可以使用b n/d/d =(b n ( 1/d = d √b n 。有关详细信息,请参见此处。因此,您可以编写递归算法

  • 降低指数,直到它是0到1
  • 之间的浮子
  • 近似于代表该浮点的分数n/d,例如使用fractions或此
  • 找到n功率的d根,例如使用简单的二进制搜索

代码:

def power(b, e):
    # the simple cases
    if e == 0: return 1
    if b in (0, 1): return b
    if e < 0: return 1 / power(b, -e)
    if e >= 1: return b * power(b, e - 1)
    # fractions: b^(n/d) == d-/ b^n
    n, d = float_to_fraction(e)  # see linked answer
    return root(power(b, n), d)
def root(x, r):
    if x < 0: raise ValueError("No roots of negative numbers!")
    low, high = 0, x
    cur = (low + high) / 2
    while high - low > 0.001:
        if power(cur, r) < x:
            low = cur
        else:
            high = cur
        cur = (low + high) / 2
    return cur

示例:

>>> b, e = 1.23, -4.56
>>> b**e
0.38907443175580797
>>> power(b, e))
0.38902984218983117

,或者您可以使用对数,尽管这可能被认为是作弊:

>>> math.exp(e * math.log(b))
0.38907443175580797

最新更新