Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using two consecutive values from a list in each iteration

Tags:

python

I have posted a part of my code below. Newton() function calls Bezier() function. The Bezier() function has a list from where I get p0 and p3. What I am trying to do is, in 1st iteration the program should take the first and second items from the plist as p0 and p3. Then in 2nd iteration, p0 and p3 are the second and third items and so on. With each iteration, the p0 and p3 values should change. It's like the new p0 is the old p3. I could not put this in the code properly. Thank you.

import math

w = 1.0

def Newton(poly):
    """ Returns a root of the polynomial"""
    x = 0.5  # initial guess value
    counter = 0
    epsilon = 0.000000000001
    poly_diff = poly_differentiate(poly)

    while True:
        x_n = x - (float(poly_substitute(poly, x)) / float(poly_substitute(poly_diff, x)))
        counter += 1
        if abs(x_n - x) < epsilon :
            break
        x = x_n
        print "\tIteration " , counter , " : ", x_n

    print "u: ", x_n
    Bezier(x_n)

def Bezier(x_n) :
    """ Calculating sampling points using rational bezier curve equation"""
    u = x_n
    plist = [0.5, 0.1, 0.4, 0.35, 0.8, 0.6, 1.0, 0.2, 0.7, 0.9] # list of parameter values of the phonemes

    for i in range(len(plist) - 1) :
        p0 = plist[i]
        p3 = plist[i + 1] 
        p1 = p0
        p2 = p3
        print p0, p3   
        p_u = math.pow(1 - u, 3) * p0 + 3 * u * math.pow(1 - u, 2) * p1 \
            + 3 * (1 - u) * math.pow(u, 2) * p2 + math.pow(u, 3) * p3
        p_u = p_u * 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
        p_u = p_u / d

    print "p(u): ", p_u
    return plist

if __name__ == "__main__" :
like image 347
zingy Avatar asked Dec 03 '22 01:12

zingy


2 Answers

>>> p = [1, 2, 3, 4, 5]
>>> for p1, p2 in zip(p, p[1:]):
...     print p1, p2
... 
1 2
2 3
3 4
4 5

Does it help?

like image 165
Mariy Avatar answered Jan 07 '23 05:01

Mariy


Perhaps the pairwise iterator from itertools recipes will help?

from itertools import izip, tee
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)
like image 22
Lauritz V. Thaulow Avatar answered Jan 07 '23 06:01

Lauritz V. Thaulow