ラグランジュ補間法

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

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

	y1 = 0.0

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

	return y1
end

x = Array.new(3)
y = Array.new(3)
				# 線形補間
n    = 1
x[0] = 0.0
x[1] = 2.0
y[0] = 0.0
y[1] = 4.0

printf("線形補間\n")
x1 = 0.0
for i1 in 0 ... 9
	y1 = Lagrange(n, x, y, x1)
	printf("   x %f y %f\n", x1, y1)
	x1 += 0.25
end

				# 2次補間
n    = 2
x[0] = 0.0
x[1] = 1.0
x[2] = 2.0
y[0] = 0.0
y[1] = 1.0
y[2] = 4.0

printf("2次補間\n")
x1 = 0.0
for i1 in 0 ... 9
	y1 = Lagrange(n, x, y, x1)
	printf("   x %f y %f\n", x1, y1)
	x1 += 0.25
end