Last active
March 8, 2017 14:12
-
-
Save denpatin/07dea4b32b8a619971b8b341bfaafa68 to your computer and use it in GitHub Desktop.
Ruby class for solving integrals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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