简体   繁体   中英

How to implement the Lagrange algorithm in a for loop to calculate coordinates using Python

I have written the following code to calculate a polynomial equation for a given set of X and Y coordinates using the Lagrange algorithm. The equation is implemented using a def and appears to be working correctly. However, I am attempting to use the resulting polynomial equation to obtain the y coordinates for a given range of X values so that I can plot a path for a robot. Eg if the range is 1 to 15 inclusively, the program ought to calculate the corresponding values of Y and plot each pair of coordinates on a graph. I am not sure how to pass a value of X into the def and obtain the correct Y value - I'm sure it's relatively simple however my mind is completely blank! Any help would be greatly appreciated!

import sympy

from functools import *
from sympy import *
X = Symbol('X')

def Lagrange(points):

    P=[reduce((lambda x,y: x*y),[(X-points[j][0])/(points[i][0] - points[j][0]) for j in range(len(points)) if i != j])*points[i][1] for i in range(len(points))]

    return sum(P)

points=[[0, 1], [1, 0], [3, 16], [-1, 16]]
print(points)
P=Lagrange(points)
print("\nLagrange equation :\n")
print(P)

You can use subs to compute your function for a range of x-values. One way is shown below. You can then visualize using matplotlib

import matplotlib.pyplot as plt

# Your code

output = [P.subs({X: i}) for i in range(1, 16)]
plt.plot(range(1, 16), output)
plt.show()

Alternative is to use evalf to evaluate your function at a given X value

output = [P.evalf(subs={X:i}) for i in range(1, 16)]

在此处输入图片说明

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