Calculate digits of e

From CodeCodex

Revision as of 17:15, 4 August 2006 by Jdh30 (Talk | contribs)

Related content:

Implementations

OCaml

# let rec e ?(fact=1) ?(i=1) = function
    | 0 -> 0.
    | n -> 1. /. float fact +. e ~fact:(i*fact) ~i:(i+1) (n-1);;
val e : ?fact:int -> ?i:int -> int -> float = <fun>

For example:

# e 10;;
- : float = 2.71828152557319225

PHP

Uses the formula: e = 1/0! + 1/1! + 1/2! + 1/3! + 1/4! + ... 1/N!

<?PHP
/* 
Example usage: 
echo number_format(e(15),20,'.','')
*/

function factorial($num) {
 if ($num >= 0) {
  $factorial = 1;
  for($i=0;$i<$num;$i++) {
   $factorial *= $num - $i;
  }
  return $factorial;
 }
}

function e($accuracy) {
 for($n=0;$n<$accuracy;$n++) {
  $total += 1 / factorial($n);
 }
 return $total;
}
?>