4.5.1-polynomial-interpolation.py 586 B

123456789101112131415161718192021222324252627282930
  1. import numpy as np
  2. def lagrange(points):
  3. result = np.poly1d([0])
  4. for i, (x_i, y_i) in enumerate(points):
  5. poly = np.poly1d([y_i])
  6. for j, (x_j, y_j) in enumerate(points):
  7. if i == j:
  8. continue
  9. poly *= np.poly1d([1, -x_j]) / (x_i - x_j)
  10. #print(poly)
  11. #print(poly(1), poly(2), poly(3))
  12. result += poly
  13. return result
  14. left = lagrange([
  15. (1, 2), (2, 2), (3, 6)
  16. ])
  17. print(left)
  18. right = lagrange([
  19. (1, 1), (2, 3), (3, 2)
  20. ])
  21. print(right)
  22. out = lagrange([
  23. (1, 2), (2, 6), (3, 12)
  24. ])
  25. print(out)