## 5.21. Numerical Computation of a Definite Integral
If you want to estimate the value of a definite integral, there is a time-tested technique for doing so. This is what the calculus student will remember as a Riemann sum. The def integrate(x0, x1, dx=(x1-x0)/1000.0) x = x0 sum = 0 loop do y = yield(x) sum += dx * y x += dx break if x > x1 end sum end def f(x) x**2 end z = integrate(0.0,5.0) {|x| f(x) } puts z, "\n" # 41.7291875 Note that in the preceding example, we are relying on the fact that a block returns a value that Drawing on our faded memories of calculus, we might compute the result here to be Finally, we will point out that a function like this is more useful when we have a variety of functions of arbitrary complexity, not just a simple function like |

The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)

ISBN: 0672328844

EAN: 2147483647

EAN: 2147483647

Year: 2004

Pages: 269

Pages: 269

Authors: Hal Fulton

Similar book on Amazon

flylib.com © 2008-2017.

If you may any questions please contact us: flylib@qtcs.net

If you may any questions please contact us: flylib@qtcs.net