Winternet

e, the transcendental constant

Filed under: — jwinter on 10/8/2003 at 12:09 am

For my Programming Languages class, we had to calculate e using the Maclaurin series 1/0! + 1/1! + 1/2! .. 1/n! in Fortran IV, Fortran II, and C and print some info about it out to the screen. I wrote it in OCaml during one of his lectures. OCaml has two numeric types int and float (makes sense so far) but has different operators for integer and float operation (umm) and I couldn’t figure out a clean way to mix ints and floats. Look at the nasty casting I do here:

let rec factorial n =
    if (n < 2) then
       1
    else
	n * factorial(n-1)
;;
let rec calculate_e precision =
    if (precision<2.0) then
       2.0
    else
	1.0/.float_of_int(factorial(int_of_float(precision))) +.
calculate_e(precision-.1.0);;
let how_precise = read_float();;
print_string (string_of_float(calculate_e(how_precise)));;
print_newline();;

There’s gotta be a better way. By the way, I gotta admit writing it in Fortran was kinda fun too.

Comments »

No comments yet.

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>


0.049 || Powered by WordPress