Skip to main content
 首页 » 编程设计

python之零除错误 : float division

2025年05月04日15dyllove98

我有这段代码可以解决牛顿法。但它给出了零除法错误。我不知道出了什么问题。谢谢。

import copy 
 
tlist = [0.0, 0.12, 0.16, 0.2, 0.31, 0.34] # list of start time for the phonemes 
 
w = w1 = w2 = w3 = w = 5 
 
def time() : 
    frame = 0.04 
    for i, start_time in enumerate(tlist) : 
        end_time = tlist[i] 
        frame = frame * (i + 1) 
        poly = poly_coeff(start_time, end_time, frame) 
        Newton(poly)  
 
def poly_coeff(stime, etime, f) : 
    """The equation is k6 * u^3 + k5 * u^2 + k4 * u + k0 = 0. Computing the coefficients for this polynomial.""" 
    """Substituting the required values we get the coefficients.""" 
    t_u = f 
    t0 = stime 
    t3 = etime 
    t1 = t2 = (stime + etime) / 2 
    w0 = w1 = w2 = w3 = w 
    k0 = w0 * (t_u - t0) 
    k1 = w1 * (t_u - t1) 
    k2 = w2 * (t_u - t2) 
    k3 = w3 * (t_u - t3) 
    k4 = 3 * (k1 - k0) 
    k5 = 3 * (k2 - 2 * k1 + k0) 
    k6 = k3 - 3 * k2 + 3 * k1 -k0  
 
    return [[k6,3], [k5,2], [k4,1], [k0,0]] 
 
def poly_differentiate(poly): 
    """ Differentiate polynomial. """ 
    newlist = copy.deepcopy(poly) 
 
    for term in newlist: 
        term[0] *= term[1] 
        term[1] -= 1 
 
    return newlist 
 
def poly_substitute(poly, x): 
    """ Apply value to polynomial. """ 
    sum = 0.0  
 
    for term in poly: 
        sum += term[0] * (x ** term[1]) 
    return sum 
 
def Newton(poly): 
    """ Returns a root of the polynomial""" 
    poly_diff = poly_differentiate(poly)  
    counter = 0 
    epsilon = 0.000000000001 
 
    x = float(raw_input("Enter initial guess:")) 
 
    while True: 
        x_n = x - (float(poly_substitute(poly, x)) / poly_substitute(poly_diff, x)) 
        counter += 1 
        if abs(x_n - x) < epsilon : 
            break 
        x = x_n 
    print "Number of iterations:", counter 
    print "The actual root is:", x_n 
    return x_n 
 
if __name__ == "__main__" : 
    time() 
Enter initial guess:0.5 
Traceback (most recent call last): 
  File "newton.py", line 79, in <module> 
    time() 
  File "newton.py", line 18, in time 
    Newton(poly)  
  File "newton.py", line 67, in Newton 
    x_n = x - (float(poly_substitute(poly, x)) / poly_substitute(poly_diff, x)) 
ZeroDivisionError: float division 

请您参考如下方法:

这里有一个基本的错误:

for i, start_time in enumerate(tlist): 
    end_time = tlist[i] 

由于 enumerate 的性质,start_time 和 end_time 具有相同的值。这意味着 poly_coeff 每次都会返回 [[0,3], [0,2], [0,1], [0,0]]。当此结果(通过 Newton)传递到 poly_differentiate 时,结果将是 [[0,2], [0,1], [0,0 ], [0,-1]].

传递到 poly_substitute 的结果将产生一个零的总和,因为在求和之前将所有列表条目乘以 term[0](恰好为零)他们。然后,将 - 除以零。

解决方案(根据您的评论编辑):

使用正确的 start_time 和 end_time 值。看起来你想要 end_time = tlist[i+1]。其边缘条件是在不评估最终列表条目的情况下突破。你真正想要的是:

for i, start_time in enumerate(tlist[:-1]): 
    end_time = tlist[i+1]