Difference between revisions of "Calculate digits of e"

From CodeCodex

(OCaml)
Line 3: Line 3:
 
===OCaml===
 
===OCaml===
 
<pre>
 
<pre>
# let rec e ?(fact=1) ?(i=1) n =
+
# let rec e ?(fact=1) ?(i=1) = function
     if n=0 then 0. else
+
     | 0 -> 0.
      1. /. float fact +. e ~fact:(i*fact) ~i:(i+1) (n-1);;
+
    | n -> 1. /. float fact +. e ~fact:(i*fact) ~i:(i+1) (n-1);;
 
val e : ?fact:int -> ?i:int -> int -> float = <fun>
 
val e : ?fact:int -> ?i:int -> int -> float = <fun>
 
</pre>
 
</pre>
Line 13: Line 13:
 
- : float = 2.71828152557319225
 
- : float = 2.71828152557319225
 
</pre>
 
</pre>
 +
 
===PHP===
 
===PHP===
 
Uses the formula:  e = 1/0! + 1/1! + 1/2! + 1/3! + 1/4! + ... 1/N!
 
Uses the formula:  e = 1/0! + 1/1! + 1/2! + 1/3! + 1/4! + ... 1/N!

Revision as of 17:15, 4 August 2006

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;
}
?>