import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
x1 = np.linspace(1, 7, 7)
x2 = np.linspace(1, 7, 8)
f, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
ax1.plot(x1, np.log(x1), 'bo')
#ax2.plot(x1, np.sin(x1), 'ro')
ax2.plot(x2, np.log(x2), 'ro')
ax1.grid(), ax2.grid()
f.subplots_adjust(hspace=0)
def func(x):
return np.log(x)
#Sum the two files myfile+myfile2 = myfilet
#np.savetxt('myfilet.txt', np.c_[ x1, 2*np.log(x1)])
def interp(x, a, b):
return func(a) + (func(b) - func(a))/(b-a)*(x-a)
c = 3.
plt.plot(x2, np.log(x2), 'ro-')
plt.plot(c, interp(c, x2[0], x2[-1]), 'go')
plt.plot([x2[0], x2[-1]], [np.log(x2[0]), np.log(x2[-1])], 'g-')
#plt.plot(c, interp(c, x2[2], x2[3]), 'bo')
#plt.plot([x2[2], x2[3]], [np.log(x2[2]), np.log(x2[3])], 'b-')
for i in range(2, 7):
plt.plot(i, interp(i, x2[i-1], x2[i]), 'go')
plt.grid()
Newton Forward And Backward Interpolation
https://www.geeksforgeeks.org/newton-forward-backward-interpolation/?ref=rp
def interp_quad(x, x0, x1, x2):
b0 = func(x0)
b1 = (func(x1) - b0)/(x1 - x0)
b2 = (func(x2) - func(x1) )/(x2-x1) - b1
b2/= x2-x0
return b0 + b1*(x-x0)+b2*(x-x0)*(x-x1)
plt.plot(x2, np.log(x2), 'ro-')
plt.plot([x2[1], x2[2], x2[3]], [func(x2[1]), func(x2[2]), func(x2[3])], 'go')
plt.plot(3, interp_quad(3, x2[1], x2[2], x2[3]), 'bo')
tmp= np.linspace(1, 5, 10)
plt.plot(tmp, interp_quad(tmp, x2[1], x2[2], x2[3]), 'bo-' )
plt.grid()
# Lagrange's Interpolation
# To represent a data point corresponding to x and y = f(x)
class Data:
def __init__(self, x, y):
self.x = x
self.y = y
# function to interpolate the given data points
# using Lagrange's formula
# xi -> corresponds to the new data point
# whose value is to be obtained
# n -> represents the number of known data points
def interpolate(f: list, xi: int, n: int) -> float:
# Initialize result
result = 0.0
for i in range(n):
# Compute individual terms of above formula
term = f[i].y
for j in range(n):
if j != i:
term = term * (xi - f[j].x) / (f[i].x - f[j].x)
print (term)
# Add current term to result
result += term
return result
# Driver Code
if __name__ == "__main__":
# creating an array of 4 known data points
f = [Data(-2, -8), Data(2, 8), Data(3, 27), Data(4, 64)]
# Using the interpolate function to obtain a data point
# corresponding to x=3
print("Value of f(3) is :", interpolate(f, 3.5, 4))
-0.024999999999999998 -1.375 22.275 22.0 Value of f(3) is : 42.875
plt.plot([-2,2,3,4], [-8,8,27,64], 'bo')
plt.plot(3.5, 42.875, 'ro')
#x=np.linspace(-2,4,30)
#plt.plot(x, x**3)
[<matplotlib.lines.Line2D at 0x11b7c9eb8>]
Splines, B-Splines, Bezier
https://www.geeksforgeeks.org/difference-between-spline-b-spline-and-bezier-curves/