简体   繁体   中英

passing a value calculated from one function to another

I have been doing python programming for my project and I have just started. This might be another trivial question. I have this code in which I need to use a value calculated in the function poly_root() which is x. That value should be used as u in the bezier() function. After poly_root() function it should go to bezier() function with its calculated value. I dont know if I am doing it in the correct way. There is no error but it doesnt print t from the bezier() function. Thank you very much.

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)

In this part of code:

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

bezier(x) is unreachable. You need to rewrite it.

It would be better for poly_root to return the same type of thing in both situations (ie a list with two elements) ...

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

Then at the bottom, you can have ...

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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