[英]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. 我编写了以下代码,以使用Lagrange算法为给定的X和Y坐标集计算多项式方程。 The equation is implemented using a def and appears to be working correctly.
该方程是使用def实现的,并且似乎工作正常。 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.
但是,我试图使用所得的多项式方程式来获得给定范围的X值的y坐标,以便为机器人绘制路径。 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.
例如,如果范围为1到15(含1和15),则程序应计算相应的Y值,并在图形上绘制每对坐标。 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!
我不确定如何将X的值传递给def并获取正确的Y值-我确定它相对简单,但是我的想法完全空白! 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. 您可以使用
subs
来计算一系列x值的函数。 One way is shown below. 一种方法如下所示。 You can then visualize using
matplotlib
然后,您可以使用
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 另一种方法是使用
evalf
以给定的X
值评估函数
output = [P.evalf(subs={X:i}) for i in range(1, 16)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.