Skip to content

Instantly share code, notes, and snippets.

@komasaru
Created February 21, 2013 08:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komasaru/5003276 to your computer and use it in GitHub Desktop.
Save komasaru/5003276 to your computer and use it in GitHub Desktop.
Ruby script to definite integral by simpson method.
# -*- coding: utf-8 -*-
#*********************************************
# シンプソン則による定積分
#*********************************************
class DefiniteIntegralSimpson
# 積分区間分割数
M = 100
# 計算クラス
class Calc
# 被積分関数
def f(x)
return Math.sqrt(4 - x * x)
end
# 定積分計算
def generate_integral(a, b)
# 1区間の幅
h = (b - a) / (2 * M).to_f
# 初期化
x = a # X 値を a で初期化
f_o = 0 # 奇数項の合計
f_e = 0 # 偶数項の合計
# 奇数項の合計、偶数項の合計計算
1.upto(2 * M - 2) do |k|
x += h
if k % 2 == 1
f_o += f(x)
else
f_e += f(x)
end
end
# 面積計算
s = f(a) + f(b)
s += 4 * (f_o + f(b-h)) + 2 * f_e
s *= h / 3.0
# 結果表示
printf(" /%f\n",b);
printf(" | f(x)dx = %f\n", s);
printf(" /%f\n",a);
end
end
# メイン処理
begin
# データ入力
print "積分区間 A :"
a = gets.chomp.to_f
print " B :"
b = gets.chomp.to_f
exit if a == 0 && b == 0
# 計算クラスインスタンス化
obj_calc = Calc.new
# 定積分計算
obj_calc.generate_integral(a, b)
rescue => e
# エラーメッセージ
puts "[例外発生] #{e}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment