Calculate digits of e

From CodeCodex

Revision as of 19:06, 4 December 2010 by 211.2.129.92 (Talk)

Related content:

Implementations

C++

double e(int n)
{
    int fact = 1;
    double sum = 0;
    for (int i = 1; i <= n; i++) {
        sum += 1. / fact;
        fact *= i;
    }
    return sum;
}

Common Lisp

Implements the above algorithm (which is in PHP) in Common Lisp

;;; Note that we already have the very first iteration (n = 0 in PHP code)
;;; calculated (result = 1), so we'll return a more accurate result on a
;;; same accuracy request.
(defun e (accuracy)
  (let ((lastfactorial 1)
        (result 1))
    (dotimes (i accuracy)
      (progn
        (incf result (/ 1 lastfactorial))
        (setf lastfactorial (* lastfactorial (+ i 2)))))
    (return-from e result)))

;;; Usage:
* (e 10)
13563139/4989600
* (float * 1.0L0)  ;; Use Long float.
2.7182818261984928651L0

Erlang

e(N) -> e(N, 1, 1, 0.0).

e(0, _, _, Sum) -> Sum;
e(N, I, Fact, Sum) ->
    e(N - 1, I + 1, Fact * I, Sum + 1 / Fact).

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

Ruby

def e(n)
  sum  = 0.0
  fact = 1
  for i in 1..n
    sum  += 1.0 / fact
    fact *= i
  end
  sum
end