Computer Science Canada

[O'Caml] Riemann Sums

Author:  Cervantes [ Thu Dec 15, 2005 6:18 pm ]
Post subject:  [O'Caml] Riemann Sums

Click here if you don't know what a Riemann Sum is.

Here is the code:

OCaml:

let rec riemann_sum fcn width low high =
   if high -. low <= width then
      (high -. low) *. fcn ((high +. low) /. 2.0)
   else
      width *. fcn (low +. width /. 2.) +. riemann_sum fcn width (low +. width) high;;

print_float (riemann_sum (fun x -> -.(x ** 2.) +. 100.) 0.5 (-10.) 10.);;


The Parameters: fcn is the function. For example f(x) = x^2. Written in O'Caml, that would be:
code:
fun x -> x ** 2.

The second parameter represents the width of each rectangle.
The third and fourth parameters represent the domain to find the area of.

Basically, it starts from the left side (at low) and adds the area it of that rectangle to the riemann_sum function, called again. Except it moves the lower bounds of the function over by width. This recursion will end when low has been shifted over so far that the distance between low and high is less than width.

Author:  rizzix [ Mon Dec 26, 2005 1:59 am ]
Post subject: 

eh? can that be cleared up.. cuz it looks way too ugly..

Author:  wtd [ Mon Dec 26, 2005 3:22 pm ]
Post subject: 

I suppose some of the mathematical expressions could be factored out into local let bindings, but it isn't that bad.


: