ラグランジュ補間法

# -*- coding: UTF-8 -*-
from math import *
import numpy as np

############################################
# ラグランジュ補間法
#      n : 次数(n=1は線形補間)
#      x, y : (n+1)個の点の座標
#      x1 : 補間したい点のx座標
#      return : 補間結果
#      coded by Y.Suganuma
############################################

def Lagrange(n, x, y, x1) :

	y1 = 0.0

	for i1 in range(0, n+1) :
		s1 = 1.0
		s2 = 1.0
		for i2 in range(0, n+1) :
			if i2 != i1 :
				s1 *= (x1 - x[i2])
				s2 *= (x[i1] - x[i2])
		y1 += y[i1] * s1 / s2

	return y1

----------------------------------

# -*- coding: UTF-8 -*-
import numpy as np
from math import *
from function import Lagrange

############################################
# 補間法(ラグランジュ)
#      coded by Y.Suganuma
############################################

x = np.array([0, 2, 2], np.float)
y = np.array([0, 4, 4], np.float)
			# 線形補間
n = 1
print("線形補間")
x1 = 0.0
for i1 in range(0, 9) :
	y1 = Lagrange(n, x, y, x1)
	print("   x " + str(x1) + " y " + str(y1))
	x1 += 0.25

			# 2次補間
n    = 2
x[1] = 1.0
y[1] = 1.0
print("2次補間")
x1 = 0.0
for i1 in range(0, 9) :
	y1 = Lagrange(n, x, y, x1)
	print("   x " + str(x1) + " y " + str(y1))
	x1 += 0.25