Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active April 19, 2018 04:52
Show Gist options
  • Save komasaru/5080004 to your computer and use it in GitHub Desktop.
Save komasaru/5080004 to your computer and use it in GitHub Desktop.
Ruby script to interpolate with Newton method.
#! /usr/local/bin/ruby
#*********************************************
# ニュートン補間
#*********************************************
#
class InterpolateNewton
# あらかじめ与える点
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_newton(t))
end
end
private
# ニュートン補間
def interpolate_newton(t)
c = Array.new # 係数配列
w = Array.new # 作業用配列
# 差分商
0.upto(@n - 1) do |i|
w[i] = Y[i]
(i - 1).downto(0) {|j| w[j] = (w[j + 1] - w[j]) / (X[i] - X[j])}
c[i] = w[0]
end
# 総和
s = c[@n - 1]
(@n - 2).downto(0) {|i| s = s * (t - X[i]) + c[i]}
return s
end
end
if __FILE__ == $0
begin
# 計算クラスインスタンス化
obj = InterpolateNewton.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