I started learning OCaml today. I already knew Scheme so I thought it would be good to try to translate some example Scheme programs to ML. I have some code below for calculating Euler's number which works, but it does not work in OCaml. I get this error: Exception: Division_by_zero.
I think that this might be a problem with mixing floats and ints somewhere. I have not been able to figure out how to set breakpoints for functions with ocamldebug
. Can anyone identify where my mistake is happening? Thank you.
(define (factorial n)
(if (zero? n) 1 (* n (factorial (sub1 n)))))
(define (find-e accuracy sum)
(if (zero? accuracy) (add1 sum)
(find-e (sub1 accuracy) (+ sum (/ 1 (factorial accuracy))))))
(display (format "~f" (find-e 100 0)))
let rec factorial n = if n == 0 then 1 else n * factorial (n - 1) ;;
let rec find_e accuracy sum =
if accuracy == 0
then (sum + 1)
else find_e (accuracy - 1) (sum + (1 / factorial accuracy)) ;;
let result = find_e 100 0 ;;