Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby script to compute definite integral by trapizoidal rule.
#! /usr/local/bin/ruby
#*********************************************
# 台形則による定積分
#*********************************************
class DefiniteIntegralTrapzoid
# 積分区間分割数
M = 100
def initialize
# 被積分関数
@f = lambda { |x| 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 += + h
s += @f.call(x)
end
s = h * ((@f.call(a) + @f.call(b)) / 2 + s)
# 結果表示
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 = DefiniteIntegralTrapzoid.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
You can’t perform that action at this time.