Last active
April 19, 2018 04:52
-
-
Save komasaru/5003139 to your computer and use it in GitHub Desktop.
Ruby script to interpolate with Lagrange method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/local/bin/ruby | |
#********************************************* | |
# ラグランジュ補間 | |
#********************************************* | |
# | |
class InterpolateLagrange | |
# あらかじめ与える点 | |
X = [0.0, 2.0, 3.0, 5.0, 8.0] | |
Y = [0.8, 3.2, 2.8, 4.5, 1.9] | |
def initialize | |
@n = X.size # 点の数 | |
end | |
# 計算・結果出力 | |
def calc | |
puts " x y" | |
X[0].step(X[@n - 1], 0.5) do |t| | |
printf("%7.2f%7.2f\n", t, interpolate_lagrange(t)) | |
end | |
end | |
private | |
# ラグランジュ補間 | |
def interpolate_lagrange(t) | |
s = 0.0 # 総和初期化 | |
# 総和 | |
0.upto(@n - 1) do |i| | |
p = Y[i] | |
# 総積 | |
0.upto(@n - 1) do |j| | |
p *= (t - X[j]) / (X[i] - X[j]) unless i == j | |
end | |
s += p | |
end | |
return s | |
end | |
end | |
if __FILE__ == $0 | |
begin | |
# 計算クラスインスタンス化 | |
obj = InterpolateLagrange.new | |
# ラグランジュ補間計算 | |
obj.calc | |
rescue => e | |
$stderr.puts "[例外発生] #{e}" | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment