Skip to content

Instantly share code, notes, and snippets.

@denpatin
Last active March 8, 2017 14:12
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 denpatin/07dea4b32b8a619971b8b341bfaafa68 to your computer and use it in GitHub Desktop.
Save denpatin/07dea4b32b8a619971b8b341bfaafa68 to your computer and use it in GitHub Desktop.
Ruby class for solving integrals
class Integral
def initialize(a, b, n = 100_000)
@a, @b, @n = a, b, n
end
def definite
h = (@b - @a).fdiv @n
h * (0...@n).inject(0) { |f, i| f + yield(@a + i * h) }
end
end
Integral.new(0, 2, 1000).definite { |x| Math.sin(x) * Math.cos(x) } # => 0.41378875524886966
Integral.new(0.1, 1).definite { |x| Math.log(x) / x } # => -2.65105267379091
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment