Calculate digits of e

From CodeCodex

Related content:

Implementations[edit]

C++[edit]

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[edit]

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[edit]

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[edit]

# 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[edit]

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

Python[edit]

Uses the formula in PHP

The code is implemented with Python 3.0

import math
def e(accuracy):
    return sum(1.0/math.factorial(i) for i in range(accuracy))

if __name__ == "__main__":
    print(e(10))


Ruby[edit]

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

Tcl[edit]

# 1000 digits of e with a spigot algorithm
 
proc e {} {
 set f {}
 set n 1000
 set b [expr {10 * $n / 4}]
 for {set i 0} {$i <= $b} {incr i} {lappend f 1}     
 incr n -1
 puts -nonewline "2."
 for {set j 1} {$j <= $n} {incr j} {
    set q 0
    for {set i $b} {$i >= 1} {incr i -1} {
       set k [expr {$i + 1}]
       set x [expr {[lindex $f $i]*10 + $q}]
       lset f $i [expr {$x % $k}]
       set q [expr {$x / $k}]
    }
    puts -nonewline $q
    flush stdout
 }
}