Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
数値積分(台形則,シンプソン則)
module DifiniteIntegral
# 積分区間分割数
M = 100
class Trapzoid
def initialize(func_str)
@f = lambda { |x| eval(func_str) }
end
def generate_integral(a, b)
# 1区間の幅
h = (b - a) / M.to_f
# 初期化
x = a # X値をaで初期化
s = a # 面積初期化
1.upto(M - 1) do |k|
x += h
s += @f.call(x)
end
s = h * ((@f.call(a) + @f.call(b)) / 2 + s)
#puts "I = %f" % s
return s
end
end
class Simpson
def initialize(func_str)
@f = lambda { |x| eval(func_str) }
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.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
# 結果表示
# puts "I = %f" % s
return s
end
end
end
trapzoid = DifiniteIntegral::Trapzoid.new("Math.sqrt(4 - x * x)") # √4-x^2
simpson = DifiniteIntegral::Simpson.new("Math.sqrt(4 - x * x)")
puts "I = %f" % trapzoid.generate_integral(0, 2)
puts "I = %f" % simpson.generate_integral(0, 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment