2011-07-26 90 views
1

我一直在爲我的項目做Python編程,並且我剛剛開始。這可能是另一個微不足道的問題。我有這個代碼,我需要使用在函數poly_root()中計算的值,它是x。該值應該用作bezier()函數中的u。在poly_root()函數之後,它應該使用它的計算值進入bezier()函數。我不知道我是否以正確的方式進行。沒有錯誤,但它不會從bezier()函數中打印出來。非常感謝你。將從一個函數計算出的值傳遞給另一個函數

import copy 

import math 

poly = [[-0.8,3], [0.75,2], [-0.75,1], [0.1,0]] 

def poly_diff(poly): 
    """ Differentiate a polynomial. """ 
    newlist = copy.deepcopy(poly) 

    for term in newlist: 
     term[0] *= term[1] 
     term[1] -= 1 

    return newlist 

def poly_apply(poly, x): 
    """ Apply values to the polynomial. """ 

    sum = 0.0 # force float 

    for term in poly: 
     sum += term[0] * (x ** term[1]) 

    return sum 

def poly_root(poly, start, n, r_i): 
    """ Returns a root of the polynomial, with a starting value.""" 

    poly_d = poly_diff(poly) 
    x = start # starting guess value 
    counter = 0 

    while True: 
     if (n >= 0) and (n < 1): 
      break 

     x_n = x - (float(poly_apply(poly, x))/poly_apply(poly_d, x)) 

     if x_n == x: 
      break 

     x = x_n # this is the u value corresponding to the given time which will be used in bezier equation 

     n -= 1 
     counter += 1 

    if r_i: 
     #print [x, counter]) 
     return [x, counter] 
    else: 
     #print x 
     return x 
    bezier(x) 

def bezier(value) : 
    """ Calculates control points using rational bezier curve equation""" 

    u = value 
    w = 5 

    t = math.pow(1-u,3) * points[0][0] + 3 * u * math.pow(1-u,2) * points[1][0] \ 
     + 3 * (1-u) * math.pow(u,2) * points[2][0] + math.pow(u,3) * points[3][0] 

    t = t * w 

    d = math.pow(1-u,3) * w + 3 * u * w * math.pow(1-u,2) + 3 * (1-u) * w \ 
     * math.pow(u,2) + math.pow(u,3) * w 


    t = t/d 
    print t 

if __name__ == "__main__" : 
    poly_root(poly, 0.42, 1, 0) 

回答

3

在這部分代碼:

if r_i: 
    #print [x, counter]) 
    return [x, counter] 
else: 
    #print x 
    return x 
bezier(x) 

bezier(x)不可達。你需要重寫它。

+0

我明白了。當然,我在想什麼。現在它正常運行。謝謝。 – zingy

1

這將是更好地爲poly_root返回在這兩種情況下同一類型的事情(即有兩個元素的列表)...

if r_i: 
    return [x, counter] 
else: 
    return [x, None] 

然後在底部,你可以有...

if __name__ == "__main__" : 
    x, counter = poly_root(poly, 0.42, 1, 0) 
    if counter is None: # I don't know if this is what you intended with your code. 
     bezier(x) 
相關問題