Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 [O'Caml] Riemann Sums
Index -> Programming, General Programming -> Functional Programming
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Cervantes




PostPosted: 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.
Sponsor
Sponsor
Sponsor
sponsor
rizzix




PostPosted: Mon Dec 26, 2005 1:59 am   Post subject: (No subject)

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




PostPosted: Mon Dec 26, 2005 3:22 pm   Post subject: (No subject)

I suppose some of the mathematical expressions could be factored out into local let bindings, but it isn't that bad.
Display posts from previous:   
   Index -> Programming, General Programming -> Functional Programming
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 3 Posts ]
Jump to:   


Style:  
Search: