将从一个函数计算的值传递给另一个函数

时间:2011-07-26 14:31:55

标签: python

我一直在为我的项目做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)

2 个答案:

答案 0 :(得分:3)

在这部分代码中:

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

bezier(x)无法访问。你需要重写它。

答案 1 :(得分: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)