Skip to content

Instantly share code, notes, and snippets.

@mberlanda
Last active April 5, 2017 15:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mberlanda/b2c858fac0220861155757afe5880c18 to your computer and use it in GitHub Desktop.
Save mberlanda/b2c858fac0220861155757afe5880c18 to your computer and use it in GitHub Desktop.
Ruby Implementation of Riemann Sum (left and right solution)
# https://en.wikipedia.org/wiki/Riemann_sum
class RiemannSum
def initialize(f, v_start, v_end, n_step)
@f = f
@v_start = v_start
@v_end = v_end
@n_step = n_step
@step_size = (v_end - v_start) / (n_step * 1.0)
end
def solve_left
sum = 0
s, e = @v_start, @v_end
@n_step.times do
sum += @f.call(s) * @step_size
s = [s + @step_size, e].min
end
sum
end
def solve_right
sum = 0
s = @v_start + @step_size
e = @v_end
@n_step.times do
sum += @f.call(s) * @step_size
s = [s + @step_size, e].min
end
sum
end
end
# \displaystyle\int_{3}^{10} \left( -10x^{2}+3x+6\right) dx
f = ->(x) { -10*(x**2) + 3*x + 6 }
r = RiemannSum.new(f, 3, 10, 2)
=> #<RiemannSum:0x00000001f63e88 @f=#<Proc:0x00000001f75e58@(irb):2 (lambda)>, @v_start=3, @v_end=10, @n_step=2, @step_size=3.5>
r.solve_left
# => -1652.0
r.solve_right
# => -4763.5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment