Advertisement
999ms

Untitled

Dec 7th, 2019
247
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.20 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3.  
  4. xs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
  5. fx = [5, 6, 8, 10, 12, 13, 12, 10, 8, 10, 8, 11, 7, 9, 11, 10, 9, 12, 11, 6]
  6.  
  7. degree = 7
  8.  
  9.  
  10. def interpolate(x):
  11.     index = 0
  12.     assert (xs[0] <= x <= xs[-1])
  13.     for i in range(len(xs)):
  14.         if xs[i] > x:
  15.             index = i
  16.             break
  17.     left = index - ((degree - 1) // 2)
  18.     right = index + ((degree - 1) // 2)
  19.     left = max(0, left)
  20.     right = min(right, len(xs) - 1)
  21.     result = 0
  22.     for i in range(left, right + 1):
  23.         cur = fx[i]
  24.         for j in range(left, right + 1):
  25.             if i == j:
  26.                 continue
  27.             cur *= (x - xs[j])
  28.             cur /= (xs[i] - xs[j])
  29.         result += cur
  30.     return result
  31.  
  32.  
  33. x = xs[0]
  34. dx = 0.01
  35.  
  36. gx = []
  37. gy = []
  38.  
  39. while x < xs[-1]:
  40.     gx.append(x)
  41.     gy.append(interpolate(x))
  42.     x += dx
  43.  
  44. gx = np.array(gx)
  45. gy = np.array(gy)
  46.  
  47. fig, ax = plt.subplots()
  48. ax.scatter(gx, gy)
  49. ax.plot(np.array(xs), np.array(fx), color='red')
  50. plt.show()
  51.  
  52. for i in range(len(gx)):
  53.     for j in range(len(xs)):
  54.         if abs(gx[i] - xs[j]) < 1e-5:
  55.             print(xs[j], gy[i], fx[j])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement