Last active
April 22, 2022 15:25
-
-
Save komasaru/ba5a0229bb3e23eae671355c225fc4b3 to your computer and use it in GitHub Desktop.
Ruby script to compute definite integral by Simpson rule.
This file contains hidden or 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 DefiniteIntegralSimpson | |
# 積分区間分割数 | |
M = 100 | |
def initialize | |
# 被積分関数 | |
@f = lambda { |x| 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, f_e = 0, 0 # 奇数項、偶数項の合計 | |
# 奇数項の合計、偶数項の合計計算 | |
1.upto(2 * M - 2) do |k| | |
x += h | |
if k % 2 == 1 | |
f_o += @f.call(x) | |
else | |
f_e += @f.call(x) | |
end | |
end | |
# 面積計算 | |
s = @f.call(a) + @f.call(b) | |
s += 4 * (f_o + @f.call(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 | |
if __FILE__ == $0 | |
begin | |
# データ入力 | |
print "積分区間 A :" | |
a = gets.chomp.to_f | |
print " B :" | |
b = gets.chomp.to_f | |
exit if a == 0 && b == 0 | |
# 計算クラスインスタンス化 | |
obj = DefiniteIntegralSimpson.new | |
# 定積分計算 | |
obj.generate_integral(a, b) | |
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