Created
February 21, 2013 08:43
-
-
Save komasaru/5003286 to your computer and use it in GitHub Desktop.
Ruby script to definite integral by trapzoid 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
# -*- coding: utf-8 -*- | |
#********************************************* | |
# 台形則による定積分 | |
#********************************************* | |
class DefiniteIntegralTrapzoid | |
# 積分区間分割数 | |
M = 100 | |
# 計算クラス | |
class Calc | |
# 被積分関数 | |
def f(x) | |
return Math.sqrt(4 - x * x) | |
end | |
# 定積分計算 | |
def generate_integral(a, b) | |
# 1区間の幅 | |
h = (b - a) / M | |
# 初期化 | |
x = a # X 値を a で初期化 | |
s = 0 # 面積初期化 | |
# 計算 | |
1.upto(M - 1) do |k| | |
x = x + h | |
s = s + f(x) | |
end | |
s = h * ((f(a) + f(b)) / 2 + s) | |
# 結果表示 | |
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