Skip to content Skip to sidebar Skip to footer

Generating A String With Python Using Loops With Logic Conditions Issues Against Join Function Alternative?

I coded a function in order to generate Lagrange interpolation expressions. So I got: def polinomioLagrange(Xs, Ys, t): for k in range(len(Xs)): if k >0:

Solution 1:

I think you're making this a lot harder than it needs to be. Rather than building strings, simply build symbolic expressions. We can implement l and L directly:

from sympy import Symbol, prod

def lag_l(xx, j):
    x = Symbol("x")
    parts = ((x - x_i) / (xx[j] - x_i) for i, x_i in enumerate(xx) if i != j)
    return prod(parts)

def lag_L(xx, yy):
    return sum(y*lag_l(xx, j) for j, y in enumerate(yy))

def lag_fn(xx, yy, x):
    return lag_L(xx, yy).subs({'x': x})

after which we can get the basis functions:

>>> lag_l([1,2,3], 0)
(-x + 2)*(-x/2 + 3/2)
>>> lag_l([1,2,3], 1)
(-x + 3)*(x - 1)
>>> lag_l([1,2,3], 2)
(x/2 - 1/2)*(x - 2)

the full interpolating polynomial:

>>> lag_L([1,2,3],[1,4,9])
(-x + 2)*(-x/2 + 3/2) + 4*(-x + 3)*(x - 1) + 9*(x/2 - 1/2)*(x - 2)

and we can call the function (here wrapped as lag_fn):

>>> lag_fn([1,2,3],[1,4,9], 3)
9

.. of course the interpolating polynomial can be simplified a lot:

>>> from sympy import simplify
>>> simplify(lag_L([1,2,3],[1,4,9]))
x**2

Post a Comment for "Generating A String With Python Using Loops With Logic Conditions Issues Against Join Function Alternative?"