Skip to content

Instantly share code, notes, and snippets.

@fee1good
Last active March 11, 2017 15:16
Show Gist options
  • Save fee1good/e9789c525b1960b70fac301299b4716d to your computer and use it in GitHub Desktop.
Save fee1good/e9789c525b1960b70fac301299b4716d to your computer and use it in GitHub Desktop.
# Recang method calculation
class RectangleMethod
include Enumerable
def initialize(a, b, n = 1000)
@a, @b, @n = a, b, n
end
def calc_rectang
# @result = 0
interval = (@b - @a).fdiv @n
@n.times.inject(0) {|data, exp| data + yield(@a + interval * exp)} * interval
# @n.times do |i|
# @result += yield(@a + interval * i)
# end
# @result * interval
end
def calc_lambda(arg)
@result = 0
interval = (@b - @a).fdiv @n
@n.times do |i|
@result += arg.call (@a + interval * i)
end
@result * interval
end
def calc2_lambda
@result = 0
interval = (@b - @a).fdiv @n
l = lambda { |func| Math.sin(func) * Math.cos(func) }
@n.times do |i|
@result += l.call (@a + interval * i)
end
@result * interval
end
end
puts RectangleMethod.new(0, 2).calc_rectang { |func| Math.sin(func) * Math.cos(func) }
puts RectangleMethod.new(0, 2).calc_lambda -> func { Math.sin(func) * Math.cos(func) }
puts RectangleMethod.new(0, 2).calc2_lambda
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment