Sure! Below is an example code that generates a curve using Lagrange interpolation for a given set of points and plots it using PyQt:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QGraphicsScene, QGraphicsView
from PyQt5.QtCore import Qt, QPointF
from PyQt5.QtGui import QPen, QPainter
def lagrange_interpolation(points):
n = len(points)
def L(k, x):
result = 1
for i in range(n):
if i != k:
result *= (x - points[i][0]) / (points[k][0] - points[i][0])
return result
def f(x):
result = 0
for k in range(n):
result += points[k][1] * L(k, x)
return result
return f
class Window(QMainWindow):
def __init__(self, points):
super().__init__()
self.setWindowTitle("Lagrange Interpolation")
self.setGeometry(100, 100, 800, 600)
self.view = QGraphicsView(self)
self.view.setAlignment(Qt.AlignTop)
self.setCentralWidget(self.view)
self.scene = QGraphicsScene(self)
self.view.setScene(self.scene)
self.points = points
self.curve = self.generate_curve()
def generate_curve(self):
curve = []
f = lagrange_interpolation(self.points)
x_range = range(min(self.points, key=lambda p: p[0])[0], max(self.points, key=lambda p: p[0])[0])
for x in x_range:
y = f(x)
curve.append(QPointF(x, y))
return curve
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
pen = QPen(Qt.blue, 2)
painter.setPen(pen)
for i in range(len(self.curve) - 1):
painter.drawLine(self.curve[i], self.curve[i+1])
for point in self.points:
painter.drawPoint(*point)
if __name__ == '__main__':
points = [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)] # Modify the points as needed
app = QApplication(sys.argv)
window = Window(points)
window.show()
sys.exit(app.exec_())
In the above code, the lagrange_interpolation function takes a list of points and returns a function that calculates the y-coordinate for a given x-coordinate using Lagrange interpolation. The Window class creates a QMainWindow with a QGraphicsView that displays the generated curve and the given points. The paintEvent method is overridden to draw the curve and points using QPainter.
To test the code, make sure you have PyQt5 installed and run the script. It will open a window displaying the curve formed by the given points using Lagrange interpolation. You can modify the points list in the script to use different set of points.