K
K
KatrinP2020-05-22 10:57:31
Python
KatrinP, 2020-05-22 10:57:31

How can I make this program calculate the Langrange number and print it out?

import numpy as np
import matplotlib.pyplot as plt

x = np.array([-6, 7, 4, 3], dtype=float)
y = np.array([-297, 249, 33, 9], dtype=float)


def lagranz(x, y, t):
    z = 0
    for j in range(len(y)):
        p1 = 1;
        p2 = 1
        for i in range(len(x)):
            if i == j:
                p1 = p1 * 1;
                p2 = p2 * 1
            else:
                p1 = p1 * (t - x[i])
                p2 = p2 * (x[j] - x[i])
        z = z + y[j] * p1 / p2
    return z


xnew = np.linspace(np.min(x), np.max(x), 100)
ynew = [lagranz(x, y, i) for i in xnew]
plt.plot(x, y, 'o', xnew, ynew)
plt.grid(True)
plt.show()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alan Gibizov, 2020-05-23
@phaggi

Maybe something like this:

spoiler
import numpy as np
import matplotlib.pyplot as plt

x = np.array([-6, 7, 4, 3], dtype=float)
y = np.array([-297, 249, 33, 9], dtype=float)


def lagranz(x, y, t):
    z = 0
    for j in range(len(y)):
        p1 = 1;
        p2 = 1
        for i in range(len(x)):
            if i == j:
                p1 = p1 * 1;
                p2 = p2 * 1
            else:
                p1 = p1 * (t - x[i])
                p2 = p2 * (x[j] - x[i])
        z = z + y[j] * p1 / p2
    return z


xnew = np.linspace(np.min(x), np.max(x), 100)
ynew = [lagranz(x, y, i) for i in xnew]

counter = 0
step = 9
for xx, yy, tex in zip(xnew, ynew, xnew):
    if counter % step == 0:
        t = plt.text(xx, yy, round(tex, 2), horizontalalignment='right' if xx < 0 else 'left', 
                 verticalalignment='center', fontdict={'color':'red' if xx < 0 else 'green', 'size':14}) 
    counter += 1

plt.plot(x, y, 'o', xnew, ynew)
plt.grid(True)
plt.show()

(It was torn off in the infernet, it was crookedly finished in the part of the display step).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question