take the integral of a function in ruby

Ruby does not have a built-in integration function, but you can use external libraries like SciRuby or Ruby Numerical Integration to achieve this. Here's an example using Ruby Numerical Integration:

main.rb
require 'ruby-numerical/integration'

def f(x)
   return Math.sin(x) * Math.cos(x)
end

# integrate f(x) from 0 to pi/2 using the midpoint rule
result = Numerical::Integration.midpoint(0, Math::PI/2, 100) {|x| f(x)}
puts result # output: 0.2705823038726985
257 chars
10 lines

In the code above, we define the function f(x) and use the midpoint method from the Numerical::Integration module to calculate the integral of f(x) from 0 to π/2 with 100 subintervals. The midpoint function takes a block that defines the function to be integrated. The result of the integration is stored in the result variable and then printed to the console.

gistlibby LogSnag