Calculating the value of e

You are encouraged to solve this task according to the task description, using any language you may know.
- Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
11l
V e0 = 0.0
V e = 2.0
V n = 0
V fact = 1
L (e - e0 > 1e-15)
e0 = e
n++
fact *= 2 * n * (2 * n + 1)
e += (2.0 * n + 2) / fact
print(‘Computed e = ’e)
print(‘Real e = ’math:e)
print(‘Error = ’(math:e - e))
print(‘Number of iterations = ’n)
- Output:
Computed e = 2.718281779 Real e = 2.718281828 Error = 4.941845111e-8 Number of iterations = 8
360 Assembly
The 'include' file FORMAT, to format a floating point number, can be found in: Include files 360 Assembly.
* Calculating the value of e - 21/07/2018
CALCE PROLOG
LE F0,=E'0'
STE F0,EOLD eold=0
LE F2,=E'1' e=1
LER F4,F2 xi=1
LER F6,F2 facti=1
BWHILE CE F2,EOLD while e<>eold
BE EWHILE ~
STE F2,EOLD eold=e
LE F0,=E'1' 1
DER F0,F6 1/facti
AER F2,F0 e=e+1/facti
AE F4,=E'1' xi=xi+1
MER F6,F4 facti=facti*xi
LER F0,F4 xi
B BWHILE end while
EWHILE LER F0,F2 e
LA R0,5 number of decimals
BAL R14,FORMATF format a float number
MVC PG(13),0(R1) output e
XPRNT PG,L'PG print e
EPILOG
COPY FORMATF format a float number
EOLD DS E eold
PG DC CL80' ' buffer
REGEQU
END CALCE
- Output:
2.71828
Action!
INCLUDE "H6:REALMATH.ACT"
PROC Euler(REAL POINTER e)
REAL e0,fact,tmp,tmp2,one
INT n
IntToReal(1,one)
IntToReal(2,e)
IntToReal(1,fact)
n=2
DO
RealAssign(e,e0)
IntToReal(n,tmp)
RealMult(fact,tmp,tmp2)
RealAssign(tmp2,fact)
n==+1
RealDiv(one,fact,tmp)
RealAdd(e,tmp,tmp2)
RealAssign(tmp2,e)
UNTIL RealGreaterOrEqual(e0,e)
OD
RETURN
PROC Main()
REAL e,calc,diff
Put(125) PutE() ;clear screen
ValR("2.71828183",e)
Euler(calc)
RealSub(calc,e,diff)
Print(" real e=") PrintRE(e)
Print("calculated e=") PrintRE(calc)
Print(" error=") PrintRE(diff)
RETURN
- Output:
Screenshot from Atari 8-bit computer
real e=2.71828183 calculated e=2.71828178 error=-5E-08
Ada
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Long_Float_Text_IO; use Ada.Long_Float_Text_IO;
procedure Euler is
Epsilon : constant := 1.0E-15;
Fact : Long_Integer := 1;
E : Long_Float := 2.0;
E0 : Long_Float := 0.0;
N : Long_Integer := 2;
begin
loop
E0 := E;
Fact := Fact * N;
N := N + 1;
E := E + (1.0 / Long_Float (Fact));
exit when abs (E - E0) < Epsilon;
end loop;
Put ("e = ");
Put (E, 0, 15, 0);
New_Line;
end Euler;
- Output:
e = 2.718281828459046
ALGOL 68
BEGIN
# calculate an approximation to e #
LONG REAL epsilon = 1.0e-15;
LONG INT fact := 1;
LONG REAL e := 2;
LONG INT n := 2;
WHILE
LONG REAL e0 = e;
fact *:= n;
n +:= 1;
e +:= 1.0 / fact;
ABS ( e - e0 ) >= epsilon
DO SKIP OD;
print( ( "e = ", fixed( e, -17, 15 ), newline ) )
END
- Output:
e = 2.718281828459045
AppleScript
For the purposes of 32 bit floating point, the value seems to stabilise after summing c. 16 terms.
--------------- CALCULATING THE VALUE OF E ----------------
on run
sum(map(inverse, ¬
scanl(product, 1, enumFromTo(1, 16))))
--> 2.718281828459
end run
-- inverse :: Float -> Float
on inverse(x)
1 / x
end inverse
-- product :: Float -> Float -> Float
on product(a, b)
a * b
end product
--------------------- GENERIC FUNCTIONS ---------------------
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m ≤ n then
set lst to {}
repeat with i from m to n
set end of lst to i
end repeat
lst
else
{}
end if
end enumFromTo
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
-- The list obtained by applying f
-- to each element of xs.
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- scanl :: (b -> a -> b) -> b -> [a] -> [b]
on scanl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
set lst to {startValue}
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
set end of lst to v
end repeat
return lst
end tell
end scanl
-- sum :: [Num] -> Num
on sum(xs)
script add
on |λ|(a, b)
a + b
end |λ|
end script
foldl(add, 0, xs)
end sum
- Output:
2.718281828459
Or, as a single fold:
------------- APPROXIMATION OF THE VALUE OF E ------------
-- eApprox :: Int -> Float
on eApprox(n)
-- The approximation of E obtained after N iterations.
script go
on |λ|(efl, x)
set {e, fl} to efl
set flx to fl * x
{e + (1 / flx), flx}
end |λ|
end script
item 1 of foldl(go, {1, 1}, enumFromTo(1, n))
end eApprox
--------------------------- TEST -------------------------
on run
-- The approximation of E obtained after 20 iterations.
eApprox(20)
end run
------------------------- GENERIC ------------------------
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m ≤ n then
set xs to {}
repeat with i from m to n
set end of xs to i
end repeat
xs
else
{}
end if
end enumFromTo
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper.
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn
- Output:
2.718281828459
Applesoft BASIC
?"E = "EXP(1)
- Output:
E = 2.71828183
Arturo
fact: 1
e: 2.0
e0: 0.0
n: 2
lim: 0.0000000000000010
while [lim =< abs e-e0][
e0: e
fact: fact * n
n: n + 1
e: e + 1.0 / fact
]
print e
- Output:
2.718281828459046
Asymptote
real n, n1;
real e1, e;
n = 1.0;
n1 = 1.0;
e1 = 0.0;
e = 1.0;
while (e != e1){
e1 = e;
e += (1.0 / n);
n1 += 1;
n *= n1;
}
write("The value of e = ", e);
- Output:
The value of e = 2.71828182845905
AWK
# syntax: GAWK -f CALCULATING_THE_VALUE_OF_E.AWK
BEGIN {
epsilon = 1.0e-15
fact = 1
e = 2.0
n = 2
do {
e0 = e
fact *= n++
e += 1.0 / fact
} while (abs(e-e0) >= epsilon)
printf("e=%.15f\n",e)
exit(0)
}
function abs(x) { if (x >= 0) { return x } else { return -x } }
- Output:
e=2.718281828459046
BASIC
BASIC256
n = 1 : n1 = 1
e1 = 0 : e = 1 / 1
while e <> e1
e1 = e
e += 1 / n
n1 += 1
n *= n1
end while
print "The value of e = "; e
end
- Output:
The value of e = 2.71828182829
QBasic
n = 1: n1 = 1
e! = 1 / 1
DO WHILE e <> e1
e1 = e
e = e + 1 / n
n1 = n1 + 1
n = n * n1
LOOP
PRINT "The value of e ="; e
- Output:
The value of e = 2.718282
True BASIC
LET n = 1
LET n1 = 1
LET e = 1 / 1
DO WHILE e <> e1
LET e1 = e
LET e = e + 1 / n
LET n1 = n1 + 1
LET n = n * n1
LOOP
PRINT "The value of e ="; e
END
- Output:
The value of e = 2.7182818
Yabasic
n = 1 : n1 = 1
e1 = 0 : e = 1 / 1
while e <> e1
e1 = e
e = e + 1 / n
n1 = n1 + 1
n = n * n1
wend
print "The value of e = ", e
- Output:
The value of e = 2.71828
Befunge
Befunge has no decimal capabilities, evaluates as fractions of 10^17
52*92*1->01p:01g1-:v v *_$101p011p54*21p>:11g1+:01g*01p:11p/21g1-:v v <
^ _$$>\:^ ^ p12_$>+\:#^_$554**/@
- Output:
2718281828459045
Burlesque
blsq ) 70rz?!{10 100**\/./}ms36.+Sh'.1iash
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274
C
solution 1
#include <stdio.h>
#include <math.h>
int main(int argc, char* argv[])
{
double e;
puts("The double precision in C give about 15 significant digits.\n"
"Values below are presented with 16 digits after the decimal point.\n");
// The most direct way to compute Euler constant.
//
e = exp(1);
printf("Euler constant e = %.16lf\n", e);
// The fast and independed method: e = lim (1 + 1/n)**n
//
int n = 8192;
e = 1.0 + 1.0 / n;
for (int i = 0; i < 13; i++)
e *= e;
printf("Euler constant e = %.16lf\n", e);
// Taylor expansion e = 1 + 1/1 + 1/2 + 1/2/3 + 1/2/3/4 + 1/2/3/4/5 + ...
// Actually Kahan summation may improve the accuracy, but is not necessary.
//
const int N = 1000;
double a[1000];
a[0] = 1.0;
for (int i = 1; i < N; i++)
{
a[i] = a[i-1] / i;
}
e = 1.;
for (int i = N - 1; i > 0; i--)
e += a[i];
printf("Euler constant e = %.16lf\n", e);
return 0;
}
- Output:
The double precision in C give about 15 significant digits. Values below are presented with 16 digits after the decimal point. Euler constant e = 2.7182818284590451 Euler constant e = 2.7181159362660465 Euler constant e = 2.7182818284590455
solution 2
#include <stdio.h>
#include <math.h>
#define EPSILON 1.0e-15
int main() {
unsigned long long fact = 1;
double e = 2.0, e0;
int n = 2;
do {
e0 = e;
fact *= n++;
e += 1.0 / fact;
}
while (fabs(e - e0) >= EPSILON);
printf("e = %.15f\n", e);
return 0;
}
- Output:
e = 2.718281828459046
C#
using System;
namespace CalculateE {
class Program {
public const double EPSILON = 1.0e-15;
static void Main(string[] args) {
ulong fact = 1;
double e = 2.0;
double e0;
uint n = 2;
do {
e0 = e;
fact *= n++;
e += 1.0 / fact;
} while (Math.Abs(e - e0) >= EPSILON);
Console.WriteLine("e = {0:F15}", e);
}
}
}
- Output:
e = 2.718281828459050
Using Decimal type
using System;
class Calc_E
{
static Decimal CalcE()
{
Decimal f = 1, e = 2; int n = 1;
do e += (f = f / ++n); while (f > 1e-27M);
return e;
}
static void Main()
{
Console.WriteLine(Math.Exp(1)); // double precision built-in result
Console.WriteLine(CalcE()); // Decimal precision result
}
}
- Output:
2.71828182845905 2.7182818284590452353602874713
Arbitrary Precision
Automatically determines number of padding digits required for the arbitrary precision output. Can calculate a quarter million digits of e in under half a minute.
using System; using System.Numerics;
using static System.Math; using static System.Console;
static class Program
{
static string CalcE(int nDigs)
{
int pad = (int)Round(Log10(nDigs)), n = 1;
BigInteger f = BigInteger.Pow(10, nDigs + pad), e = f + f;
do e += (f /= ++n); while (f > n);
return (e / BigInteger.Pow(10, pad + 1)).ToString().Insert(1, ".");
}
static void Main()
{
WriteLine(Exp(1)); // double precision built-in function
WriteLine(CalcE(100)); // arbitrary precision result
DateTime st = DateTime.Now; int qmil = 250_000;
string es = CalcE(qmil); // large arbitrary precision result string
WriteLine("{0:n0} digits in {1:n3} seconds.", qmil, (DateTime.Now - st).TotalSeconds);
WriteLine("partial: {0}...{1}", es.Substring(0, 46), es.Substring(es.Length - 45));
}
}
- Output:
2.71828182845905 2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427 250,000 digits in 22.833 seconds. partial: 2.71828182845904523536028747135266249775724709...026587951482508371108187783411598287506586313
C++
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
const double EPSILON = 1.0e-15;
unsigned long long fact = 1;
double e = 2.0, e0;
int n = 2;
do {
e0 = e;
fact *= n++;
e += 1.0 / fact;
}
while (fabs(e - e0) >= EPSILON);
cout << "e = " << setprecision(16) << e << endl;
return 0;
}
- Output:
e = 2.718281828459046
Clojure
;; Calculating the number e, euler-napier number.
;; We will use two methods
;; First method: the forumula (1 + 1/n)^n
;; Second method: the series partial sum 1/(p!)
;;first method
(defn inverse-plus-1 [n]
(+ 1 (/ 1 n)))
(defn e-return [n]
(Math/pow (inverse-plus-1 n) n))
(time (e-return 100000.))
;;"Elapsed time: 0.165629 msecs"
;;2.7182682371922975
;;SECOND METHOD
(defn method-e [n]
(loop [e-aprx 0M
value-add 1M
p 1M]
(if (> p n)
e-aprx
(recur (+ e-aprx value-add) (/ value-add p) (inc p)))))
(time (with-precision 110 (method-e 200M)))
"Elapsed time: 11.310568 msecs" 2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274274663923M
COBOL
>>SOURCE FORMAT IS FIXED
IDENTIFICATION DIVISION.
PROGRAM-ID. EULER.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 EPSILON USAGE COMPUTATIONAL-2 VALUE 1.0E-15.
01 FACT USAGE BINARY-DOUBLE UNSIGNED VALUE 1.
01 N USAGE BINARY-INT UNSIGNED.
01 E USAGE COMPUTATIONAL-2 VALUE 2.0.
01 E0 USAGE COMPUTATIONAL-2 value 0.0.
01 RESULT-MESSAGE.
03 FILLER PIC X(4) VALUE 'e = '.
03 RESULT-VALUE PIC 9.9(18) USAGE DISPLAY.
PROCEDURE DIVISION.
MAIN SECTION.
PERFORM
VARYING N FROM 2 BY 1
UNTIL FUNCTION ABS(E - E0) < EPSILON
MOVE E TO E0
COMPUTE FACT = FACT * N
COMPUTE E = E + 1.0 / FACT
END-PERFORM.
MOVE E TO RESULT-VALUE.
DISPLAY RESULT-MESSAGE.
STOP RUN.
- Output:
e = 2.718281828459041093
Commodore BASIC
Commodore BASIC floats have a 40-bit mantissa, so we get max precision after just 11 iterations:
100 REM COMPUTE E VIA INVERSE FACTORIAL SUM
110 N = 11:REM NUMBER OF ITERATIONS
120 E = 1:REM APPROXIMATE E HERE
130 F = 1:REM BUILD FACTORIAL HERE
140 FOR I = 1 TO N
150 : F = F*I
160 : E = E + 1/F
170 NEXT I
180 PRINT "AFTER" N "ITERATIONS, E =" E
- Output:
AFTER 11 ITERATIONS, E = 2.71828183 READY.
Common Lisp
Common Lisp performs exact rational arithmetic, but printing those results out in decimal form is challenging; the built-in options require conversion to floating point values of relatively low precision. The QuickLisp module computable-reals makes printing out precise decimal representations easy, though:
(ql:quickload :computable-reals :silent t)
(use-package :computable-reals)
(defparameter *iterations* 1000)
(let ((e 1) (f 1))
(loop for i from 1 to *iterations* doing
(setq f (* f i))
(setq e (+ e (/ 1 f))))
(format t "After ~a iterations, e = " *iterations*)
(print-r e 2570))
- Output:
After 1000 iterations, e = +2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746639193200305992181741359662904357290033429526059563073813232862794349076323382988075319525101901157383418793070215408914993488416750924476146066808226480016847741185374234544243710753907774499206955170276183860626133138458300075204493382656029760673711320070932870912744374704723069697720931014169283681902551510865746377211125238978442505695369677078544996996794686445490598793163688923009879312773617821542499922957635148220826989519366803318252886939849646510582093923982948879332036250944311730123819706841614039701983767932068328237646480429531180232878250981945581530175671736133206981125099618188159304169035159888851934580727386673858942287922849989208680582574927961048419844436346324496848756023362482704197862320900216099023530436994184914631409343173814364054625315209618369088870701676839642437814059271456354906130310720851038375051011574770417189861068739696552126715468895703503540212340784981933432106817012100562788023519303322474501585390473041995777709350366041699732972508868769664035557071622684471625607988265178713419512466520103059212366771943252786753985589448969709640975459185695638023637016211204774272283648961342251644507818244235294863637214174023889344124796357437026375529444833799801612549227850925778256209262264832627793338656648162772516401910590049164499828931505660472580277863186415519565324425869829469593080191529872117255634754639644791014590409058629849679128740687050489585867174798546677575732056812884592054133405392200011378630094556068816674001698420558040336379537645203040243225661352783695117788386387443966253224985065499588623428189970773327617178392803494650143455889707194258639877275471096295374152111513683506275260232648472870392076431005958411661205452970302364725492966693811513732275364509888903136020572481765851180630364428123149655070475102544650117272115551948668508003685322818315219600373562527944951582841882947876108526398139559900673764829224437528718462457803619298197139914756448826260390338144182326251509748279877799643730899703888677822713836057729788241256119071766394650706330452795466185509666618566470971134447401607046262156807174818778443714369882185596709591025968620023537185887485696522000503117343920732113908032936344797273559552773490717837934216370120500545132638354400018632399149070547977805669785335804896690629511943247309958765523681285904138324116072260299833053537087613893963917795745401613722361878936526053815584158718692553860616477983402543512843961294603529133259...
D
import std.math;
import std.stdio;
enum EPSILON = 1.0e-15;
void main() {
ulong fact = 1;
double e = 2.0;
double e0;
int n = 2;
do {
e0 = e;
fact *= n++;
e += 1.0 / fact;
} while (abs(e - e0) >= EPSILON);
writefln("e = %.15f", e);
}
- Output:
e = 2.718281828459046
dc
After 51 iterations the result is correct to 67 digits after the decimal, which gets as many digits as dc will display on a single line. After 1000 iterations the approximation is correct to 2,570 digits after the decimal. In each case you need to tell dc to (k)eep several digits past the target or else it will hit a plateau and stop improving before it reaches the desired precision.
Here's the 1000-iteration code, which keeps 2574 digits of precision to ensure that it gets the answer right to 2570 (and then only prints it out to 2570):
1000 sn [ n = number of iterations ]sx
2574k [ precision to use during computation ]sx
1 d se sf [ set e and f to 1 ]sx
0 si [ set i to 0 ]sx
[ [ p = begin ]sx
lf li 1 + d si * sf [ f = f*(++i) ]sx
le 1 lf / + se [ e = e + 1/f ]sx
ln li <p [ if i<n recur ]sx
]sp [ end ]sx
lpx [ call p ]sx
[After ]n lnn [ output header. uses n + 10P for newline ]sx
[ iterations, e =]n [ instead of p, so nothing is left hanging ]sx
10P [ around on the stack.]sx
2570k [ now reset precision to match correct digits ]sx
le 1 / [ get result truncated to that precision ]sx
n 10P [ and print it out, again with n + 10P ]sx
- Output:
After 1000 iterations, e = 2.7182818284590452353602874713526624977572470936999595749669676277240\ 766303535475945713821785251664274274663919320030599218174135966290435\ 729003342952605956307381323286279434907632338298807531952510190115738\ 341879307021540891499348841675092447614606680822648001684774118537423\ 454424371075390777449920695517027618386062613313845830007520449338265\ 602976067371132007093287091274437470472306969772093101416928368190255\ 151086574637721112523897844250569536967707854499699679468644549059879\ 316368892300987931277361782154249992295763514822082698951936680331825\ 288693984964651058209392398294887933203625094431173012381970684161403\ 970198376793206832823764648042953118023287825098194558153017567173613\ 320698112509961818815930416903515988885193458072738667385894228792284\ 998920868058257492796104841984443634632449684875602336248270419786232\ 090021609902353043699418491463140934317381436405462531520961836908887\ 070167683964243781405927145635490613031072085103837505101157477041718\ 986106873969655212671546889570350354021234078498193343210681701210056\ 278802351930332247450158539047304199577770935036604169973297250886876\ 966403555707162268447162560798826517871341951246652010305921236677194\ 325278675398558944896970964097545918569563802363701621120477427228364\ 896134225164450781824423529486363721417402388934412479635743702637552\ 944483379980161254922785092577825620926226483262779333865664816277251\ 640191059004916449982893150566047258027786318641551956532442586982946\ 959308019152987211725563475463964479101459040905862984967912874068705\ 048958586717479854667757573205681288459205413340539220001137863009455\ 606881667400169842055804033637953764520304024322566135278369511778838\ 638744396625322498506549958862342818997077332761717839280349465014345\ 588970719425863987727547109629537415211151368350627526023264847287039\ 207643100595841166120545297030236472549296669381151373227536450988890\ 313602057248176585118063036442812314965507047510254465011727211555194\ 866850800368532281831521960037356252794495158284188294787610852639813\ 955990067376482922443752871846245780361929819713991475644882626039033\ 814418232625150974827987779964373089970388867782271383605772978824125\ 611907176639465070633045279546618550966661856647097113444740160704626\ 215680717481877844371436988218559670959102596862002353718588748569652\ 200050311734392073211390803293634479727355955277349071783793421637012\ 050054513263835440001863239914907054797780566978533580489669062951194\ 324730995876552368128590413832411607226029983305353708761389396391779\ 574540161372236187893652605381558415871869255386061647798340254351284\ 3961294603529133259
Delphi
See Pascal
Hand-coded version:
program Calculating_the_value_of_e;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
const
EPSILON = 1.0e-15;
function fAbs(value: Extended): Extended;
begin
Result := value;
if value < 0 then
Result := -Result;
end;
function e: Extended;
var
fact: UInt64;
e, e0: Extended;
n: Integer;
begin
fact := 1;
Result := 2.0;
n := 2;
repeat
e0 := Result;
fact := fact * n;
inc(n);
Result := Result + (1.0 / fact);
until (fAbs(Result - e0) < EPSILON);
end;
begin
writeln(format('e = %.15f', [e]));
readln;
end.
- Output:
e = 2,718281828459045
Dyalect
func calculateE(epsilon = 1.0e-15) {
func abs(n) {
if n < 0 {
-n
} else {
n
}
}
var fact = 1
var e = 2.0
var e0 = 0.0
var n = 2
while true {
e0 = e
fact *= n
n += 1
e += 1.0 / Float(fact)
if abs(e - e0) < epsilon {
break
}
}
return e
}
print(calculateE())
- Output:
2.71828182845905
EasyLang
numfmt 0 5
fact = 1
n = 2
e = 2
while abs (e - e0) > 0.0001
e0 = e
fact = fact * n
n += 1
e += 1 / fact
.
print e
EDSAC order code
Simple arithmetic
The difficulty here is that the EDSAC was designed to hold real numbers in the range -1 <= x < 1 only. Subroutines were devised for floating-point arithmetic, but rather than get involved with those we'll cheat slightly by calculating e - 2 and printing the result with '2' in front. It will be seen that the answer is 3 out in the 10th decimal place.
[Calculate e]
[EDSAC program, Initial Orders 2]
[Library subroutine M3. Prints header and is then overwritten]
[Here, last character sets teleprinter to figures]
PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF
@&*CALCULATION!OF!E@&#
..PZ [blank tape, needed to mark end of header text]
[Library subroutine D6. Division, accurate, fast.
Closed, 36 locations, working positions 6D and 8D.
C(0D) := C(0D)/C(4D), where C(4D) <> 0, -1.]
T56K [define load address for subroutine]
GKA3FT34@S4DE13@T4DSDTDE2@T4DADLDTDA4DLDE8@RDU4DLDA35@
T6DE25@U8DN8DA6DT6DH6DS6DN4DA4DYFG21@SDVDTDEFW1526D
[Library subroutine P1.
Prints a single positive number (without layout or round-off).
Prints number in 0D to n places of decimals, where
n is specified by 'P n F' pseudo-order after subroutine call.
Closed, 21 locations.]
T92K [define load address for subroutine]
GKA18@U17@S20@T5@H19@PFT5@VDUFOFFFSFL4FTDA5@A2FG6@EFU3FJFM1F
..PZ
[Main routine]
T120K [Define load address for main program.
Must be even, because of double values at start.]
GK [set @ (theta) for relative addresses]
[0] PF PF [build sum 4*(1/3! + 1/4! + 1/5! + ...)]
[2] PF PF [term in sum]
[4] PD PF [2^-34, stop when term < this]
[6] PF [divisor]
[7] IF [1/2]
[8] QF [1/16]
[9] @F [carriage return]
[10] &F [line feed]
[11] WF [digit '2']
[12] MF [full stop / decimal point]
[13] K4096F [teleprinter null]
[14] A8@ [load 1/16]
LD [shift, makes 1/8]
UD [to 0D for subroutine D6]
T6@ [divisor := 1/8]
T#@ [sum := 0]
[loop, acc assumed to be 0 here]
[19] A6@ [load divisor]
A8@ [add 1/16]
U6@ [update divisor]
T4D [to 4D for subroutine D6]
[23] A23@ [for subroutine return]
G56F [call D6]
AD [load quotient]
U2#@ [store as term]
A#@ [add term into sum]
T#@ [update sum]
A2#@ [load term]
S4#@ [test for convergence]
G36@ [jump out if so]
A4#@ [restore term after test]
R4F [divide by 16]
TD [to 0D for subroutine D6]
E19@ [loop back]
[here when converged]
[36] TF [clear acc]
A#@ [load sum]
R1F [shift to divide by 4]
A7@ [add 1/2, now have (e - 2)]
YF [round]
TD [to 0D for subroutine P1]
O11@ [print '2.']
O12@
[44] A44@ [for subroutine return]
G92F [call P1 to print (e - 2)]
P10F [10 decimals]
O9@ [print CR]
O10@ [print LF]
O13@ [null to flush print buffer]
ZF [stop]
E14Z [relative address of entry]
PF [enter with accumulator = 0]
- Output:
CALCULATION OF E 2.7182818282
Multiword arithmetic
This version uses multiword arithmetic to output a lot more decimal places than the simple version.
The program calculates e as 1/0! + 1/1! + 1/2! + ..., stopping when 1/n! is too small to be distinguished from zero. There are two multiword variables, for 1/n! and the result respectively. The code leaves enough room for each variable to have 332 words.
For simplicity in printing the result, arithmetic is done in base 10^4. A larger base, e.g. 2^15, would give more decimals, but not as many as one might think. Moreover, the extra code required for printing would leave less room for the variables.
The program executes about 38 million orders (16 hours on the original EDSAC) and prints e to 1324 decimal places. Because of rounding errors, the last two places are wrong (should be 61, not 44).
[Calculate e by multilength variables.
EDSAC program, Initial Orders 2.
Subroutine to print 4-digit number in 0F.
6F >= 0 to print leading zeros, 6F < 0 to suppress them.
42 locations.]
T 56 K
GKA3FT36@T40@A6FE8@T1FA13@T40@T1FS2FL1FT39@H37@VFL2FA2FTFA40@E23@AFG27@
T1FT40@OFH38@CFTFT1FA39@A2FE36@T39@H26@VFL8FE16@EFI393FP2047DPFPF
[Division subroutine for positive 35-bit integers.
Input: dividend at 4D, divisor at 6D
Output: remainder at 4D, quotient at 6D.
37 locations; working locations 0D, 8D.]
T 98 K
GKA3FT35@A6DU8DTDA4DRDSDG13@T36@ADLDE4@T36@T6DA4DSDG23@
T4DA6DYFYFT6DT36@A8DSDE35@T36@ADRDTDA6DLDT6DE15@EFPF
[Define multilength variables, to base 10^4 for simplicity in printing out.
Low address = low order digit.
Variable starting at 360 is result = 1/0! + 1/1! + 1/2! + 1/3! + ...
Variable starting at 692 is the term 1/n!]
T 54 K [instruction to loader: store at 54, 55, ...]
P 360 F [address of result in 54; referred to by code letter C]
P 692 F [address of term in 55; referred to by code letter V]
T 135 K [instruction to loader: store at 135, 136, ...]
G K [instruction to loader: store 135 at address 42]
[Constants]
[0] # F [figure shift]
[1] M F [(1) decimal point for printing
(2) subtracted from A order to make T order]
[2] @ F [carriage return]
[3] & F [line feed]
[4] K 4096 F [null character]
[5] P 12 F [groups of 4 digits per line, as an address]
[6] P 332 F [length of variable, as an address
(max is 332 at present, 2020-07-04)]
[7] P D [1]
[8] W 904 F [10000 = base for multibyte variables]
[9] A C [used to manufacture orders]
[10] A V [used to manufacture orders
Variables]
[11] P F [(address of term) - (address of result)]
[12] A C ['A m C' order where m = length of result]
[13] A V ['A m V' order where m = length of term 1/n!]
[14] A V [divisor := 2, 3, 4, ... to get term 1/n!]
[Subroutine to set top word of multilength value and clear rest.
Input: 4F = A order for lowest value of multibyte
5F = value, assumed < base]
[15] A 3 F [make and plant link for return]
T 32 @
A 4 F [load A order]
S 1 @ [convert to T order]
U 24 @ [plant in code]
A 6 @ [make T order for top word]
S 2 F
T 31 @ [plant in code]
[23] T F [clear acc]
[24] T F [clear word in variable]
A 24 @ [load T order]
A 2 F [inc address]
U 24 @ [store back]
S 31 @ [reached top word?]
G 23 @ [no, loop back]
A 5 F [yes, load passed-in value]
[31] T F [store it]
[32] E F [return]
[Subroutine to set result := result + term, where term = 1/n!]
[33] A 3 F [make and plant link for return]
T 66 @
T 1 F [carry in 1F, initially := 0]
A 9 @ [load A order for start of result]
[37] U 44 @ [plant A order for result]
A 11 @ [make A order for term]
T 45 @ [plant A order for term]
A 44 @ [load A order for result]
S 1 @ [make T order for result]
U 50 @ [plant in code, 2 places]
T 56 @
[44] A C [load word from result]
[45] A V [add word from term]
A 1 F [add carry from last time]
S 8 @ [is sum >= base?]
E 56 @ [yes, jump]
A 8 @ [no, restore sum after test]
[50] T C [store in result]
[No carry. If rest of term is all 0's we can finish.]
A 45 @ [load A order for term]
S 13 @ [beyond end of non-zero part?]
E 65 @ [yes, jump to finish]
T F [no, clear acc]
E 58 @ [jump to set carry := 0]
[Here if there's a carry]
[56] T C [save word of result]
A 7 @ [load 1 for carry]
[58] T 1 F [update carry for next time]
A 44 @ [load A order for result]
A 2 F [inc address]
S 12 @ [reached end?]
E 65 @ [yes, jump to finish]
A 12 @ [no, restore A order after test]
G 37 @ [loop back]
[65] T F [clear acc]
[66] E F [return]
[Subroutine to round term 1/n!
Increments low word of term by 1. Assume this doesn't increase the length.]
[67] A 3 F [make and plant return link]
T 84 @
A 10 @ [load A order for start of term]
[70] U 74 @ [plant A order in code]
S 1 @ [convert to T order]
U 78 @ [plant T order, 2 places]
T 83 @
[74] A V [load word from term]
A 7 @ [add 1]
S 8 @ [carry needed?]
G 82 @ [no, store and exit]
[78] T V [yes, store dec'd word (must be 0)]
A 74 @ [load A order]
A 2 F [inc address]
G 70 @ [loop back]
[82] A 8 @ [no carry, restore sum after test]
[83] T V [store in word of term]
[84] E F [exit]
[Subroutine to divide term 1/n! by the 17-bit positive number in location 0.
Called when n is incremented; location 0 contains new value of n.
Adjusts the value of endAV if necessary.]
[85] A 3 F [make and plant return link]
T 130 @
A F [load divisor]
T 131 @ [store locally]
A 13 @ [load A order for end of term]
T 102 @ [plant in code]
T 1 F [carry in 1F, initially := 0]
[Start of loop]
[92] T F [clear acc]
A 102 @ [load A order for word in term]
S 2 F [dec address]
S 10 @ [now beyond start?]
G 119 @ [yes, jump to finish off]
A 10 @ [no, restore order after test]
U 102 @ [plant in code]
S 1 @ [convert to T order]
T 115 @ [plant in code]
T 4 D [clear 5F and sandwich bit]
[102] A V [load word from term]
T 4 F [store as double in 4D]
T 6 D [clear 7F and sandwich bit]
A 131 @ [load divisor]
T 6 F [store as double in 6D]
H 8 @ [multiplier register := base]
V 1 F [acc := base*carry]
R 1 F [shift 2 right]
A 4 D [add word from term]
T 4 D [to $D as dividend]
A 112 @ [call division routine]
G 98 F
A 6 F [load quotient]
[115] T V [to word in term]
A 4 F [load remainder]
T 1 F [to carry]
E 92 @ [loop for next]
[Done division, round quotient if necessary]
[119] T F [clear acc]
A 1 F [load carry out of last digit]
L D [carry*2]
S 131 @ [subtract divisor]
G 127 @ [if carry < divisor/2, skip rounding]
T F [clear acc]
A 125 @ [call routine to inc low word of term by 1]
G 67 @
[127] T F [clear acc]
A 128 @ [call routine to adjust endAV]
G 132 @
[130] E F [exit with acc = 0]
[131] P F [divisor]
[Subroutine to update endAV, i.e. the A order for start of zero words in the term 1/n!
The address *before* endAV must be either (1) less than ordAV or (2) contain non-zero.]
[132] A 3 F [make and plant return link]
T 148 @
[Start of loop. here acc = 0.]
[134] A 13 @ [load current endAV]
S 2 F [tentative new value]
U 140 @ [plant in code]
S 10 @ [less than ordAV?]
G 147 @ [yes, done]
T F [no, clear acc]
[140] A V [load word in term]
S 7 @ [greater than 0?]
E 147 @ [yes, done]
T F [no, clear acc]
A 140 @ [update endAV to tentative value]
T 13 @
E 134 @ [loop back to test new value]
[147] T F
[148] E F
[Subroutine to print multibyte result with formatting.
Assumes top word (integer part) is <= 9; OK since integer part = 2 here.
Uses 5F for countdown of words on current line.]
[149] A 3 F [make and plant return link]
T 183 @
A 12 @ [start at top end]
S 2 F [point to top word]
U 156 @ [plant A order, 2 places]
T 176 @
T 5 F [countdown := 0 to force newline]
[156] A F [load top word]
T F [to 0F for printing]
S 7 @ [acc := -1]
T 6 F [make 6F < 0 to suppress leading 0's]
A 160 @
G 56 F
O 1 @ [print decimal point]
[Start of loop to print fractional part of result. Assumes acc = 0.]
[163] A 176 @ [load A order for result]
S 2 F [dec address]
S 9 @ [now beyond start?]
G 182 @ [yes, exit]
A 9 @ [no, restore order after test]
T 176 @ [plant in code]
A 5 F [load printing countdown]
S 2 F [decrement]
E 175 @ [skip if not gone negative]
A 5 @ [reset print countdown]
O 2 @ [start new line]
O 3 @
[175] T 5 F
[176] A C [load word]
T F [to 0F for printing]
T 6 F [print leading 0's]
A 179 @ [call subroutine to print 0F]
G 56 F [(clears acc)]
E 163 @ [loop back]
[182] T F [exit with acc = 0]
[183] E F
[Enter with acc = 0]
[184] O @
A 10 @ [acc := A order for start of term 1/n!]
S 9 @ [subtract A order for start of result]
T 11 @ [store difference of addresses]
A 9 @ [A order for start of result]
A 6 @ [add length of result]
T 12 @ [store result]
A 10 @ [similarly for term]
A 6 @
T 13 @
A 9 @ [load A order for start of result]
T 4 F [to 4F for subroutine]
A 7 @ [load 1]
T 5 F [to 5F for subroutine]
A 198 @ [call subroutine to set result := 1]
G 15 @
A 10 @ [similarly term := 1]
T 4 F
A 7 @
U 14 @
T 5 F
A 205 @
G 15 @
[207] T F
A 208 @ [result := result + term]
G 33 @
T F
A 14 @ [inc n]
A 7 @
U 14 @
T F [also in 0F]
A 215 @ [divide term by n]
G 85 @
A 10 @
S 13 @
G 207 @
[Here 1/n! has been reduced to 0; time to stop]
T F [clear acc]
A 221 @ [call subroutine to print result]
G 149 @
O 4 @ [null to flush printer buffer]
Z F [stop]
E 184 Z [define entry point]
P F [acc = 0 on entry]
- Output:
2. 718281828459045235360287471352662497757247093699 959574966967627724076630353547594571382178525166 427427466391932003059921817413596629043572900334 295260595630738132328627943490763233829880753195 251019011573834187930702154089149934884167509244 761460668082264800168477411853742345442437107539 077744992069551702761838606261331384583000752044 933826560297606737113200709328709127443747047230 696977209310141692836819025515108657463772111252 389784425056953696770785449969967946864454905987 931636889230098793127736178215424999229576351482 208269895193668033182528869398496465105820939239 829488793320362509443117301238197068416140397019 837679320683282376464804295311802328782509819455 815301756717361332069811250996181881593041690351 598888519345807273866738589422879228499892086805 825749279610484198444363463244968487560233624827 041978623209002160990235304369941849146314093431 738143640546253152096183690888707016768396424378 140592714563549061303107208510383750510115747704 171898610687396965521267154688957035035402123407 849819334321068170121005627880235193033224745015 853904730419957777093503660416997329725088687696 640355570716226844716256079882651787134195124665 201030592123667719432527867539855894489697096409 754591856956380236370162112047742722836489613422 516445078182442352948636372141740238893441247963 5743702637552944483379980144
Spigot algorithm
The EDSAC program to calculate pi by means of a spigot algorithm is easily modified to calculate e. It will then output 2070 correct digits of e (though it outputs only 252 correct digits of pi). Details will be found under the task "Pi".
[Code not given, as it is almost the same as the EDSAC spigot algorithm for pi.
See the task "Pi" for the EDSAC program and the changes needed to calculate e.]
- Output:
2718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427 4274663919320030599218174135966290435729003342952605956307381323286279434907632338298807531952510190 1157383418793070215408914993488416750924476146066808226480016847741185374234544243710753907774499206 9551702761838606261331384583000752044933826560297606737113200709328709127443747047230696977209310141 6928368190255151086574637721112523897844250569536967707854499699679468644549059879316368892300987931 2773617821542499922957635148220826989519366803318252886939849646510582093923982948879332036250944311 7301238197068416140397019837679320683282376464804295311802328782509819455815301756717361332069811250 9961818815930416903515988885193458072738667385894228792284998920868058257492796104841984443634632449 6848756023362482704197862320900216099023530436994184914631409343173814364054625315209618369088870701 6768396424378140592714563549061303107208510383750510115747704171898610687396965521267154688957035035 4021234078498193343210681701210056278802351930332247450158539047304199577770935036604169973297250886 8769664035557071622684471625607988265178713419512466520103059212366771943252786753985589448969709640 9754591856956380236370162112047742722836489613422516445078182442352948636372141740238893441247963574 3702637552944483379980161254922785092577825620926226483262779333865664816277251640191059004916449982 8931505660472580277863186415519565324425869829469593080191529872117255634754639644791014590409058629 8496791287406870504895858671747985466775757320568128845920541334053922000113786300945560688166740016 9842055804033637953764520304024322566135278369511778838638744396625322498506549958862342818997077332 7617178392803494650143455889707194258639877275471096295374152111513683506275260232648472870392076431 0059584116612054529703023647254929666938115137322753645098889031360205724817658511806303644281231496 5507047510254465011727211555194866850800368532281831521960037356252794495158284188294787610852639813 9559900673764829224437528718462457803619298197139914756448826260390338
Emacs Lisp
(defun factorial (i)
"Compute factorial of i."
(apply #'* (number-sequence 1 i)))
(defun compute-e (iter)
"Compute e."
(apply #'+ 1 (mapcar (lambda (x) (/ 1.0 x))
(mapcar #'factorial (number-sequence 1 iter)))))
(compute-e 20)
- Output:
2.7182818284590455
Epoxy
fn CalculateE(P)
var E:1,F:1
loop I:1;I<=P;I+:1 do
F*:I
E+:1/F
cls
return E
cls
log(CalculateE(100))
log(math.e)
- Output:
2.7182818284590455 2.718281828459045
Excel
LAMBDA
Binding the name eApprox to the following lambda expression in the Name Manager of the Excel WorkBook:
(See LAMBDA: The ultimate Excel worksheet function)
eApprox
=LAMBDA(n,
INDEX(
FOLDROW(
LAMBDA(efl,
LAMBDA(x,
LET(
flx, INDEX(efl, 2) * x,
e, INDEX(efl, 1),
CHOOSE(
{1;2},
e + (1 / flx),
flx
)
)
)
)
)({1;1})(
SEQUENCE(1, n)
),
1
)
)
and also assuming the following generic bindings in the Name Manager for the WorkBook:
FOLDROW
=LAMBDA(op,
LAMBDA(a,
LAMBDA(xs,
LET(
b, op(a)(HEADROW(xs)),
IF(1 < COLUMNS(xs),
FOLDROW(op)(b)(
TAILROW(xs)
),
b
)
)
)
)
)
HEADROW
=LAMBDA(xs,
LET(REM, "The first item of each row in xs",
INDEX(
xs,
SEQUENCE(ROWS(xs)),
SEQUENCE(1, 1)
)
)
)
TAILROW
=LAMBDA(xs,
LET(REM,"The tail of each row in the grid",
n, COLUMNS(xs) - 1,
IF(0 < n,
INDEX(
xs,
SEQUENCE(ROWS(xs), 1, 1, 1),
SEQUENCE(1, n, 2, 1)
),
NA()
)
)
)
- Output:
Within the finite precision of Excel floating point numbers (IEEE 754 doubles) the approximation converges with the built-in EXP(n) function at around the 16th iteration.
fx | =eApprox(A2) | |||
---|---|---|---|---|
A | B | C | ||
1 | Iterations | Approximation | IEEE 754 difference | |
2 | 1 | 2 | 0.71828182845905 | |
3 | 2 | 2.5 | 0.21828182845905 | |
4 | 3 | 2.66666666666667 | 0.05161516179238 | |
5 | 4 | 2.70833333333333 | 0.00994849512571 | |
6 | 5 | 2.71666666666667 | 0.00161516179238 | |
7 | 6 | 2.71805555555556 | 0.00022627290349 | |
8 | 7 | 2.71825396825397 | 0.00002786020508 | |
9 | 8 | 2.71827876984127 | 0.00000305861778 | |
10 | 9 | 2.71828152557319 | 0.00000030288585 | |
11 | 10 | 2.71828180114638 | 0.00000002731266 | |
12 | 11 | 2.71828182619849 | 0.00000000226055 | |
13 | 12 | 2.71828182828617 | 0.00000000017288 | |
14 | 13 | 2.71828182844676 | 0.00000000001229 | |
15 | 14 | 2.71828182845823 | 0.00000000000081 | |
16 | 15 | 2.71828182845899 | 0.00000000000005 | |
17 | 16 | 2.71828182845904 | 0 |
F#
// A function to generate the sequence 1/n!). Nigel Galloway: May 9th., 2018
let e = Seq.unfold(fun (n,g)->Some(n,(n/g,g+1N))) (1N,1N)
Which may be used:
printfn "%.14f" (float (e |> Seq.take 20 |> Seq.sum))
- Output:
2.71828182845905
Factor
USING: math math.factorials prettyprint sequences ;
IN: rosetta-code.calculate-e
CONSTANT: terms 20
terms <iota> [ n! recip ] map-sum >float .
- Output:
2.718281828459045
FOCAL
1.1 S K=1; S E=0
1.2 F X=1,10; D 2
1.3 Q
2.1 S E=E+1/K
2.2 S K=K*X
2.3 T %2,X,%6.5,E,!
- Output:
*G = 1= 1.00000 = 2= 2.00000 = 3= 2.50000 = 4= 2.66667 = 5= 2.70833 = 6= 2.71667 = 7= 2.71806 = 8= 2.71825 = 9= 2.71828 = 10= 2.71828
FOCAL always computes six significant digits at most, so it only takes a few iterations until e = 2.71828, the same value as the built-in exponential function:
*T FEXP(1),! = 2.71828
Forth
Algorithm e-spigot: compute the first n decimal digits of e (due to Stanley Rabinowitz and Stan Wagon):
1. Initialize: Let the first digit be 2 and initialize an array A of length n + 1 to (1, 1, 1, . . . , 1).
2. Repeat n − 1 times:
- Multiply by 10: Multiply each entry of A by 10.
- Take the fractional part: Starting from the right, reduce the ith entry of A modulo i + 1, carrying the quotient one place left.
- Output the next digit: The final quotient is the next digit of e.
100 constant #digits
: int-array create cells allot does> swap cells + ;
#digits 1+ int-array e-digits[]
: init-e ( -- )
[ #digits 1+ ] literal 0 DO
1 i e-digits[] !
LOOP
." = 2." ;
: .e ( -- )
init-e
[ #digits 1- ] literal 0 DO
0 \ carry
0 #digits DO
i e-digits[] dup @ 10 * rot + i 2 + /mod -rot swap !
-1 +LOOP
0 .r
LOOP ;
- Output:
Gforth 0.7.3, Copyright (C) 1995-2008 Free Software Foundation, Inc. Gforth comes with ABSOLUTELY NO WARRANTY; for details type `license' Type `bye' to exit .e = 2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427 ok
Fortran
Program eee
implicit none
integer, parameter :: QP = selected_real_kind(16)
real(QP), parameter :: one = 1.0
real(QP) :: ee
write(*,*) ' exp(1.) ', exp(1._QP)
ee = 1. +(one +(one +(one +(one +(one+ (one +(one +(one +(one +(one +(one &
+(one +(one +(one +(one +(one +(one +(one +(one +(one +(one) &
/21.)/20.)/19.)/18.)/17.)/16.)/15.)/14.)/13.)/12.)/11.)/10.)/9.) &
/8.)/7.)/6.)/5.)/4.)/3.)/2.)
write(*,*) ' polynomial ', ee
end Program eee
- Output:
exp(1.) 2.71828182845904523543 polynomial 2.71828182845904523543
Free Pascal
See Pascal
FreeBASIC
Normal basic
' version 02-07-2018
' compile with: fbc -s console
Dim As Double e , e1
Dim As ULongInt n = 1, n1 = 1
e = 1 / 1
While e <> e1
e1 = e
e += 1 / n
n1 += 1
n *= n1
Wend
Print "The value of e ="; e
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End
- Output:
The value of e = 2.718281828459046
GMP version
' version 02-07-2018
' compile with: fbc -s console
#Include "gmp.bi"
Sub value_of_e(e As Mpf_ptr)
Dim As ULong n = 1
Dim As Mpf_ptr e1, temp
e1 = Allocate(Len(__mpf_struct)) : Mpf_init(e1)
temp = Allocate(Len(__mpf_struct)) : Mpf_init(temp)
Dim As Mpz_ptr fac
fac = Allocate(Len(__mpz_struct)) : Mpz_init_set_ui(fac, 1)
Mpf_set_ui(e, 1) ' 1 / 0! = 1 / 1
While Mpf_cmp(e1, e) <> 0
Mpf_set(e1, e)
Mpf_set_z(temp, fac)
n+= 1
Mpz_mul_ui(fac, fac, n)
Mpf_ui_div(temp, 1, temp)
Mpf_add(e, e, temp)
Wend
End Sub
' ------=< MAIN >=------
Dim As UInteger prec = 50 ' precision = 50 digits
Dim As ZString Ptr outtext = Callocate (prec + 10)
Mpf_set_default_prec(prec * 3.5)
Dim As Mpf_ptr e
e = Allocate(Len(__mpf_struct)) : Mpf_init(e)
value_of_e(e)
Gmp_sprintf(outtext,"%.*Ff", prec, e)
Print "The value of e = "; *outtext
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End
- Output:
The value of e = 2.71828182845904523536028747135266249775724709369996
Fōrmulæ
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.
Programs in Fōrmulæ are created/edited online in its website, However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
In this page you can see the program(s) related to this task and their results.
Furor
###sysinclude math.uh
1.0e-15 sto EPSILON
one fact
2. sto e
2 sto n
((
@e sto e0
#g @n++ prd fact
1.0 @fact !(#d) / sum e
( @e @e0 - abs @EPSILON < )))
."e = " @e printnl
end
{ „EPSILON” }
{ „fact” }
{ „e” }
{ „e0” }
{ „n” }
- Output:
e = +2.71828182845905
Go
package main
import (
"fmt"
"math"
)
const epsilon = 1.0e-15
func main() {
fact := uint64(1)
e := 2.0
n := uint64(2)
for {
e0 := e
fact *= n
n++
e += 1.0 / float64(fact)
if math.Abs(e - e0) < epsilon {
break
}
}
fmt.Printf("e = %.15f\n", e)
}
- Output:
e = 2.718281828459046
Groovy
Solution:
If the difference between previous and next iteration is less than the tolerance (ε) we judge that the sequence of partial sums has converged "enough".
Since the difference between partial sums is always the "last" term, it suffices to ensure that the "last" term is less than the tolerance.
def ε = 1.0e-15
def φ = 1/ε
def generateAddends = {
def addends = []
def n = 0.0
def fact = 1.0
while (true) {
fact *= (n < 2 ? 1.0 : n) as double
addends << 1.0/fact
if (fact > φ) break // any further addends would not pass the tolerance test
n++
}
addends.sort(false) // smallest addends first for better response to rounding error
}
def e = generateAddends().sum()
Test:
printf "%17.15f\n%17.15f\n", e, Math.E
Output:
2.718281828459045 2.718281828459045
Haskell
For the purposes of 64 bit floating point precision, the value seems to stabilise after summing c. 17-20 terms.
------ APPROXIMATION OF E OBTAINED AFTER N ITERATIONS ----
eApprox :: Int -> Double
eApprox n =
(sum . take n) $ (1 /) <$> scanl (*) 1 [1 ..]
--------------------------- TEST -------------------------
main :: IO ()
main = print $ eApprox 20
- Output:
2.7182818284590455
Or equivalently, in a single fold:
------ APPROXIMATION OF E OBTAINED AFTER N ITERATIONS ----
eApprox n =
snd $
foldr
( \x (fl, e) ->
(,) <*> (e +) . (1 /) $ fl * x
)
(1, 1)
[n, pred n .. 1]
--------------------------- TEST -------------------------
main :: IO ()
main = print $ eApprox 20
- Output:
2.7182818284590455
Or in terms of iterate:
{-# LANGUAGE TupleSections #-}
------------------- APPROXIMATIONS TO E ------------------
approximatEs :: [Double]
approximatEs =
fst
<$> iterate
( \(e, (i, n)) ->
(,) . (e +) . (1 /) <*> (succ i,) $ i * n
)
(1, (1, 1))
--------------------------- TEST -------------------------
main :: IO ()
main = print $ approximatEs !! 17
- Output:
2.7182818284590455
Icon and Unicon
For Icon, the EPSILON preprocessor constant would need to be an inline constant where tested, or set in a variable.
$define EPSILON 1.0e-15
procedure main()
local e0
local e := 2.0
local fact := 1
local n := 2
repeat {
e0 := e
fact *:= n
n +:= 1
e +:= (1.0 / fact)
if abs(e - e0) < EPSILON then break
}
write("computed e ", e)
write("keyword &e ", &e)
end
- Output:
prompt$ unicon -s euler.icn -x computed e 2.718281828459046 keyword &e 2.718281828459045
IS-BASIC
100 PROGRAM "e.bas"
110 LET E1=0:LET E,N,N1=1
120 DO WHILE E<>E1
130 LET E1=E:LET E=E+1/N
140 LET N1=N1+1:LET N=N*N1
150 LOOP
160 PRINT "The value of e =";E
- Output:
The value of e = 2.71828183
J
The j language has expressive notations for numbers. Examples:
NB. rational one half times pi to the first power NB. pi to the power of negative two NB. two oh in base 111 NB. complex number length 1, angle in degrees 180 1r2p1 1p_2 111b20 1ad270 1.5708 0.101321 222 0j_1
It won't surprise you that in j we can write
1x1 NB. 1 times e^1 2.71828
The unary power verb ^ uses Euler's number as the base, hence
^ 1 2.71828
Finally, to compute e find the sum as insert plus +/ of the reciprocals % of factorials ! of integers i. . Using x to denote extended precision integers j will give long precision decimal expansions of rational numbers. Format ": several expansions to verify the number of valid digits to the expansion. Let's try for arbitrary digits.
NB. approximation to e as a rational number NB. note the "r" separating numerator from denominator +/ % ! i. x: 20 82666416490601r30411275102208 NB. 31 places shown with 20 terms 32j30 ": +/ % ! i. x: 20 2.718281828459045234928752728335 NB. 40 terms 32j30 ": +/ % ! i. x: 40 2.718281828459045235360287471353 NB. 50 terms, 32j30 ": +/ % ! i. x: 50 2.718281828459045235360287471353 NB. verb to compute e as a rational number e =: [: +/ [: % [: ! [: i. x: NB. format for e to so many places places =: >: j. <: NB. verb f computes e for y terms and formats it in x decimal places f =: (":~ places)~ e While =: conjunction def 'u^:(0~:v)^:_' NB. return number of terms and the corresponding decimal representation e_places =: ({: , {.)@:(((f n) ; {.@:] , <@:(>:@:n@:]))While([: ~:/ 2 {. ]) '0' ; '1'&;)&1 e_places 1 ┌─┬──┐ │5│ 3│ └─┴──┘ e_places 4 ┌─┬─────┐ │9│2.718│ └─┴─────┘ e_places 40 ┌──┬─────────────────────────────────────────┐ │37│2.718281828459045235360287471352662497757│ └──┴─────────────────────────────────────────┘
Java
public class CalculateE {
public static final double EPSILON = 1.0e-15;
public static void main(String[] args) {
long fact = 1;
double e = 2.0;
int n = 2;
double e0;
do {
e0 = e;
fact *= n++;
e += 1.0 / fact;
} while (Math.abs(e - e0) >= EPSILON);
System.out.printf("e = %.15f\n", e);
}
}
- Output:
e = 2.718281828459046
JavaScript
Summing over a scan
(() => {
"use strict";
// - APPROXIMATION OF E OBTAINED AFTER N ITERATIONS --
// eApprox : Int -> Float
const eApprox = n =>
sum(
scanl(mul)(1)(
enumFromTo(1)(n)
)
.map(x => 1 / x)
);
// ---------------------- TEST -----------------------
const main = () =>
eApprox(20);
// ---------------- GENERIC FUNCTIONS ----------------
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = m =>
n => Array.from({
length: 1 + n - m
}, (_, i) => m + i);
// mul (*) :: Num a => a -> a -> a
const mul = a =>
// The arithmetic product of a and b.
b => a * b;
// scanl :: (b -> a -> b) -> b -> [a] -> [b]
const scanl = f => startValue => xs =>
// The series of interim values arising
// from a catamorphism. Parallel to foldl.
xs.reduce((a, x) => {
const v = f(a[0])(x);
return [v, a[1].concat(v)];
}, [startValue, [startValue]])[1];
// sum :: [Num] -> Num
const sum = xs =>
// The numeric sum of all values in xs.
xs.reduce((a, x) => a + x, 0);
// MAIN ---
return main();
})();
2.7182818284590455
Or as a single fold/reduce:
(() => {
"use strict";
// --------------- APPROXIMATION OF E ----------------
const eApprox = n =>
// Approximation of E obtained after Nth iteration.
enumFromTo(1)(n).reduce(
([fl, e], x) => (
flx => [flx, e + (1 / flx)]
)(
fl * x
),
[1, 1]
)[1];
// ---------------------- TEST -----------------------
// main :: IO ()
const main = () =>
eApprox(20);
// --------------------- GENERIC ---------------------
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = m =>
n => Array.from({
length: 1 + n - m
}, (_, i) => m + i);
// MAIN ---
return main();
})();
- Output:
2.7182818284590455
jq
1|exp #=> 2.718281828459045
def e:
[null,0,1,1]
| until(.[0] == .[1]; .[0]=.[1] | .[1]+=1/.[2] | .[2] *= .[3] | .[3]+=1)
| .[0];
e #=> 2.7182818284590455
Julia
Module:
module NeperConstant
export NeperConst
struct NeperConst{T}
val::T
end
Base.show(io::IO, nc::NeperConst{T}) where T = print(io, "ℯ (", T, ") = ", nc.val)
function NeperConst{T}() where T
local e::T = 2.0
local e2::T = 1.0
local den::(T ≡ BigFloat ? BigInt : Int128) = 1
local n::typeof(den) = 2
while e ≠ e2
e2 = e
den *= n
n += one(n)
e += 1.0 / den
end
return NeperConst{T}(e)
end
end # module NeperConstant
Main:
for F in (Float16, Float32, Float64, BigFloat)
println(NeperConst{F}())
end
- Output:
(Float16) 2.717 (Float32) 2.718282 (Float64) 2.7182818284590455 (BigFloat) 2.718281828459045235360287471352662497757247093699959574966967627724076630353416
K
/ Computing value of e
/ ecomp.k
\p 17
fact: {*/1+!:x}
evalue:{1 +/(1.0%)'fact' 1+!20}
evalue[]
- Output:
\l ecomp 2.7182818284590455
Klingphix
%e0 %e %n %fact %v
0 !e0 2 !e 0 !n 1 !fact
1e-15 !v
:printOp swap print print nl ;
:test $e $e0 - abs $v >= ;
[$e !e0
$n 1 + !n
2 $n * 2 $n * 1 + * $fact * !fact
2 $n * 2 + $fact / $e + !e]
[test]
while
%rE
2.718281828459045 !rE
"Computed e = " $e tostr printOp
"Real e = " $rE tostr printOp
"Error = " $rE $e sub printOp
"Number of iterations = " $n printOp
" " input
Kotlin
// Version 1.2.40
import kotlin.math.abs
const val EPSILON = 1.0e-15
fun main(args: Array<String>) {
var fact = 1L
var e = 2.0
var n = 2
do {
val e0 = e
fact *= n++
e += 1.0 / fact
}
while (abs(e - e0) >= EPSILON)
println("e = %.15f".format(e))
}
- Output:
e = 2.718281828459046
Lambdatalk
1) straightforward
{+ 1 {S.map {lambda {:n} {/ 1 {* {S.serie 1 :n}}}} {S.serie 1 17}}}
-> 2.7182818284590455
which is the value given by javascript : 2.718281828459045.
2) using recursion
{def fac
{lambda {:a :b}
{if {< :b 1}
then :a
else {fac {* :a :b} {- :b 1}}}}}
-> fac
{def euler
{lambda {:a :b}
{if {< :b 1}
then :a
else {euler {+ :a {/ 1 {fac 1 :b}}} {- :b 1}}}}}
-> euler
{euler 1 17}
-> 2.7182818284590455
langur
mode divMaxScale = 104
val .epsilon = 1.0e-104
var .e = 2
for .fact, .n = 1, 2 ; ; .n += 1 {
val .e0 = .e
.fact x= .n
.e += 1 / .fact
if abs(.e - .e0) < .epsilon: break
}
writeln ".e = ", .e
# compare to built-in constant e
writeln " e = ", e
- Output:
The result depends on the .epsilon value and the divMaxScale mode. Set to 15, this would give the same result as the Go example.
.e = 2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742747 e = 2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746
Lua
EPSILON = 1.0e-15;
fact = 1
e = 2.0
e0 = 0.0
n = 2
repeat
e0 = e
fact = fact * n
n = n + 1
e = e + 1.0 / fact
until (math.abs(e - e0) < EPSILON)
io.write(string.format("e = %.15f\n", e))
- Output:
e = 2.718281828459046
M2000 Interpreter
Using @ for Decimal, and ~ for Float, # for Currency (Double is the default type for M2000)
Module FindE {
Function comp_e (n){
\\ max 28 for decimal (in one line with less spaces)
n/=28:For i=27to 1:n=1+n/i:Next i:=n
}
Clipboard Str$(comp_e(1@),"")+" Decimal"+{
}+Str$(comp_e(1),"")+" Double"+{
}+Str$(comp_e(1~),"")+" Float"+{
}+Str$(comp_e(1#),"")+" Currency"+{
}
Report Str$(comp_e(1@),"")+" Decimal"+{
}+Str$(comp_e(1),"")+" Double"+{
}+Str$(comp_e(1~),"")+" Float"+{
}+Str$(comp_e(1#),"")+" Currency"+{
}
}
FindE
- Output:
2.7182818284590452353602874712 Decimal 2.71828182845905 Double 2.718282 Float 2.7183 Currency
As a lambda function (also we use a faster For, using block {})
comp_e=lambda (n)->{n/=28:For i=27to 1 {n=1+n/i}:=n}
Maple
evalf[50](add(1/n!,n=0..100));
# 2.7182818284590452353602874713526624977572470937000
evalf[50](exp(1));
# 2.7182818284590452353602874713526624977572470937000
With continued fractions:
with(NumberTheory):
e:=ContinuedFraction(exp(1)):
Convergent(e,100);
evalf[50](%);
# 13823891428306770374331665289458907890372191037173036666131/5085525453460186301777867529962655859538011626631066055111
# 2.7182818284590452353602874713526624977572470937000
Mathematica /Wolfram Language
1+Fold[1.+#1/#2&,1,Range[10,2,-1]]
- Output:
2.7182818261984928652
Sum[1/x!, {x, 0, ∞}]
Limit[(1+1/x)^x,x->∞]
Exp[1]
or even just
𝕖
input as
≡ee≡
- Output:
𝕖
min
(:n (n 0 ==) ((0)) (-1 () ((succ dup) dip append) n times) if) :iota
(iota 'succ '* map-reduce) :factorial
20 iota (factorial 1 swap /) '+ map-reduce print
- Output:
2.718281828459046
МК-61/52
П0 П1 0 П2 1 П2 1 П3
ИП3 ИП2 ИП1 ИП0 - 1 + * П2 1/x + П3
ИП0 x#0 25 L0 08 ИП3 С/П
At n = 10, the value is 2.7182819.
Modula-2
MODULE CalculateE;
FROM RealStr IMPORT RealToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
CONST EPSILON = 1.0E-15;
PROCEDURE abs(n : REAL) : REAL;
BEGIN
IF n < 0.0 THEN
RETURN -n
END;
RETURN n
END abs;
VAR
buf : ARRAY[0..31] OF CHAR;
fact,n : LONGCARD;
e,e0 : LONGREAL;
BEGIN
fact := 1;
e := 2.0;
n := 2;
REPEAT
e0 := e;
fact := fact * n;
INC(n);
e := e + 1.0 / LFLOAT(fact)
UNTIL abs(e - e0) < EPSILON;
WriteString("e = ");
RealToStr(e, buf);
WriteString(buf);
WriteLn;
ReadChar
END CalculateE.
Myrddin
use std
const main = {
var f: uint64 = 1
var e: flt64 = 2.0
var e0: flt64 = 0.0
var n = 2
while e > e0
e0 = e
f *= n
e += 1.0 / (f : flt64)
n++
;;
std.put("e: {}\n", e)
}
Nanoquery
e0 = 0
e = 2
n = 0
fact = 1
while (e - e0) > 10^-15
e0 = e
n += 1
fact *= 2*n*((2*n)+1)
e += ((2.0*n)+2)/fact
end
println "Computed e = " + e
println "Number of iterations = " + n
- Output:
Computed e = 2.7182818284590452349287527283351994002986043726966476833155148405875077310383076614195442493493357765 Number of iterations = 9
Nim
const epsilon : float64 = 1.0e-15
var fact : int64 = 1
var e : float64 = 2.0
var e0 : float64 = 0.0
var n : int64 = 2
while abs(e - e0) >= epsilon:
e0 = e
fact = fact * n
inc(n)
e = e + 1.0 / fact.float64
echo e
Pascal
Like delphi and many other.Slightly modified to calculate (1/n!) not n! and then divide to (1/n!)
program Calculating_the_value_of_e;
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
{$IFDEF WINDOWS}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
SysUtils;
const
EPSILON = 1.0e-14;
function Get_E: Extended;
var
recfact: Extended;
n: Integer;
begin
recfact := 1.0;
Result := 2.0;
n := 2;
repeat
recfact /= n;
inc(n);
Result := Result + recfact;
until (recfact < EPSILON);
end;
begin
writeln(format('calc e = %.15f intern e= %.15f', [Get_E,exp(1.0)]));
{$IFDEF WINDOWS}readln;{$ENDIF}
end.
- Output:
calc e = 2.718281828459045 intern e= 2.718281828459045
Perl
With the bignum
core module in force, Brother's algorithm requires only 18 iterations to match the precision of the built-in value, e
.
use bignum qw(e);
$e = 2;
$f = 1;
do {
$e0 = $e;
$n++;
$f *= 2*$n * (1 + 2*$n);
$e += (2*$n + 2) / $f;
} until ($e-$e0) < 1.0e-39;
print "Computed " . substr($e, 0, 41), "\n";
print "Built-in " . e, "\n";
- Output:
Computed 2.718281828459045235360287471352662497757 Built-in 2.718281828459045235360287471352662497757
To calculate 𝑒 to an arbitrary precision, enable the bigrat
core module evaluate the Taylor series as a rational number,
then use Math::Decimal
do to the 'long division' with the large integers.
Here, 71 terms of the Taylor series yield 𝑒 to 101 digits.
use bigrat;
use Math::Decimal qw(dec_canonise dec_mul dec_rndiv_and_rem);
sub factorial { my $n = 1; $n *= $_ for 1..shift; $n }
for $n (0..70) {
$sum += 1/factorial($n);
}
($num,$den) = $sum =~ m#(\d+)/(\d+)#;
print "numerator: $num\n";
print "denominator: $den\n";
$num_dec = dec_canonise($num);
$den_dec = dec_canonise($den);
$ten = dec_canonise("10");
($q, $r) = dec_rndiv_and_rem("FLR", $num_dec, $den_dec);
$e = "$q.";
for (1..100) {
$num_dec = dec_mul($r, $ten);
($q, $r) = dec_rndiv_and_rem("FLR", $num_dec, $den_dec);
$e .= $q;
}
printf "\n%s\n", subset $e, 0,102;
- Output:
numerator: 32561133701373476427912330475884581607687531065877567210421813247164172713574202714721554378508046501 denominator: 11978571669969891796072783721689098736458938142546425857555362864628009582789845319680000000000000000 2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274
Phix
with javascript_semantics requires("1.0.2") -- (builtin constant E renamed as EULER) atom e0 = 0, e = 2, n = 0, fact = 1 while abs(e-e0)>=1e-15 do e0 = e n += 1 fact *= 2*n*(2*n+1) e += (2*n+2)/fact end while printf(1,"Computed e = %.15f\n",e) printf(1," Real e = %.15f\n",EULER) printf(1," Error = %g\n",EULER-e) printf(1,"Number of iterations = %d\n",n)
- Output:
Computed e = 2.718281828459045 Real e = 2.718281828459045 Error = 4.4409e-16 Number of iterations = 9
Phixmonti
0 var e0 2 var e 0 var n 1 var fact
1e-15 var v
def printOp
swap print print nl
enddef
def test e e0 - abs v >= enddef
test
while
e var e0
n 1 + var n
2 n * 2 n * 1 + * fact * var fact
2 n * 2 + fact / e + var e
test
endwhile
2.718281828459045 var rE
"Computed e = " e tostr printOp
"Real e = " rE tostr printOp
"Error = " rE e - printOp
"Number of iterations = " n printOp
- Output:
Computed e = 2.718281828459045 Real e = 2.718281828459045 Error = 4.4409e-16 Number of iterations = 9
PicoLisp
(scl 15)
(let (F 1 E 2.0 E0 0 N 2)
(while (> E E0)
(setq E0 E F (* F N))
(inc 'E (*/ 1.0 F))
(inc 'N) )
(prinl "e = " (format E *Scl)) )
- Output:
e = 2.718281828459046
PowerShell
$e0 = 0
$e = 2
$n = 0
$fact = 1
while([Math]::abs($e-$e0) -gt 1E-15){
$e0 = $e
$n += 1
$fact *= 2*$n*(2*$n+1)
$e += (2*$n+2)/$fact
}
Write-Host "Computed e = $e"
Write-Host " Real e = $([Math]::Exp(1))"
Write-Host " Error = $([Math]::Exp(1) - $e)"
Write-Host "Number of iterations = $n"
- Output:
Computed e = 2.71828182845904 Real e = 2.71828182845905 Error = 4.44089209850063E-16 Number of iterations = 9
Processing
Updated to show that computed value matches library value after 21 iterations.
void setup() {
double e = 0;
long factorial = 1;
int iterations = 11;
for (int i = 0; i < iterations; i++) {
e += (double) (2 * i + 1) / factorial;
factorial *= (2 * i + 1) * (2 * i + 2);
}
println("After " + iterations + " iterations");
println("Computed value: " + e);
println("Real value: " + Math.E);
println("Error: " + (e - Math.E));
iterations = 21;
for (int i = 11; i < iterations; i++) {
e += (double) (2 * i + 1) / factorial;
factorial *= (2 * i + 1) * (2 * i + 2);
}
println("After " + iterations + " iterations");
println("Computed value: " + e);
println("Real value: " + Math.E);
println("Error: " + (e - Math.E));
}
- Output:
After 11 iterations Computed value: 2.7182818284590455 Real value: 2.718281828459045 Error: 4.440892098500626E-16 After 21 iterations Computed value: 2.718281828459045 Real value: 2.718281828459045 Error: 0.0
Prolog
Floating-point solution
Uses Newton's method to solve ln x = 1
% Calculate the value e = exp 1
% Use Newton's method: x0 = 2; y = x(2 - ln x)
tolerance(1e-15).
exp1_iter(L) :-
lazy_list(newton, 2, L).
newton(X0, X1, X1) :-
X1 is X0*(2 - log(X0)).
e([X1, X2|_], X1) :- tolerance(Eps), abs(X2 - X1) < Eps.
e([_|Xs], E) :- e(Xs, E).
main :-
exp1_iter(Iter),
e(Iter, E),
format("e = ~w~n", [E]),
halt.
?- main.
- Output:
$ swipl e.pl e = 2.7182818284590455
Arbitrary-precision solution
% John Devou: 26-Nov-2021
% Simple program to calculate e up to n decimal digits.
% Works fast for n ≤ 1 000 000.
l(M,F,L,S):- F > L -> S is M-1; M_ is M+1, F_ is F*M_, l(M_,F_,L,S).
e(S,X,Y,N,E):- S < 2 -> E is div(X*10**N,Y);
S_ is S-1, X_ is X+Y, Y_ is S*Y, e(S_,X_,Y_,N,E).
main:-
get_time(Start), % start computation
current_prolog_flag(argv,[X|_]), % read arguments
atom_number(X,N), % convert first argument to number
L is 3*10**(N+1), l(1,1,L,S), % find the smallest S, such that (S+1)! > 3*10^(N+1)
e(S,0,1,N,E), % compute decimal part of series 1/2! + 1/3! + ... + 1/S!
get_time(End), % finish computation
format("e = 2.~d\n",E), % show number
format("Computed in ~f sec",End- Start), % show computation time
halt.
?- main.
- Output:
$ swipl e.pl 1000 e = 2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427427466391932003059921817413596629 043572900334295260595630738132328627943490763233829880753195251019011573834187930702154089149934884167509244761460668082264800168477411853 742345442437107539077744992069551702761838606261331384583000752044933826560297606737113200709328709127443747047230696977209310141692836819 025515108657463772111252389784425056953696770785449969967946864454905987931636889230098793127736178215424999229576351482208269895193668033 182528869398496465105820939239829488793320362509443117301238197068416140397019837679320683282376464804295311802328782509819455815301756717 361332069811250996181881593041690351598888519345807273866738589422879228499892086805825749279610484198444363463244968487560233624827041978 623209002160990235304369941849146314093431738143640546253152096183690888707016768396424378140592714563549061303107208510383750510115747704 1718986106873969655212671546889570350354 Computed in 0.000998 sec
PureBasic
Define f.d=1.0, e.d=1.0, e0.d=e, n.i=1
LOOP:
f*n : e+1.0/f
If e-e0>=1.0e-15 : e0=e : n+1 : Goto LOOP : EndIf
Debug "e="+StrD(e,15)
- Output:
e=2.718281828459046
Python
Imperative
import math
#Implementation of Brother's formula
e0 = 0
e = 2
n = 0
fact = 1
while(e-e0 > 1e-15):
e0 = e
n += 1
fact *= 2*n*(2*n+1)
e += (2.*n+2)/fact
print "Computed e = "+str(e)
print "Real e = "+str(math.e)
print "Error = "+str(math.e-e)
print "Number of iterations = "+str(n)
- Output:
Computed e = 2.71828182846 Real e = 2.71828182846 Error = 4.4408920985e-16 Number of iterations = 9
Functional
This approximation stabilises (within the constraints of available floating point precision) after about the 17th term of the series.
'''Calculating an approximate value for e'''
from itertools import (accumulate, chain)
from functools import (reduce)
from operator import (mul)
# eApprox :: () -> Float
def eApprox():
'''Approximation to the value of e.'''
return reduce(
lambda a, x: a + 1 / x,
scanl(mul)(1)(
range(1, 18)
),
0
)
# TEST ----------------------------------------------------
# main :: IO ()
def main():
'''Test'''
print(
eApprox()
)
# GENERIC ABSTRACTIONS ------------------------------------
# scanl is like reduce, but returns a succession of
# intermediate values, building from the left.
# See, for example, under `scan` in the Lists chapter of
# the language-independent Bird & Wadler 1988.
# scanl :: (b -> a -> b) -> b -> [a] -> [b]
def scanl(f):
'''scanl is like reduce, but returns a succession of
intermediate values, building from the left.'''
return lambda a: lambda xs: (
accumulate(chain([a], xs), f)
)
# MAIN ---
if __name__ == '__main__':
main()
- Output:
2.7182818284590455
Or in terms of a single fold/reduce:
'''Approximation of E'''
from functools import reduce
# eApprox :: Int -> Float
def eApprox(n):
'''Approximation of E obtained after N iterations.
'''
def go(efl, x):
e, fl = efl
flx = fl * x
return e + 1 / flx, flx
return reduce(
go,
range(1, 1 + n),
(1, 1)
)[0]
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''Approximation of E obtained after 20 iterations.'''
print(eApprox(20))
# MAIN ---
if __name__ == '__main__':
main()
- Output:
2.7182818284590455
R
options(digits=22)
cat("e =",sum(rep(1,20)/factorial(0:19)))
- Output:
e = 2.718281828459046
Quackery
Using the Quackery bignum rational arithmetic library.
$ "bigrat.qky" loadfile
[ swap number$
tuck size -
times sp echo$ ] is echo-rj ( n n --> )
[ 2dup swap
say " First " echo
say " approximations of e by sum of 1/n! displayed to "
echo say " decimal places." cr
cr
temp put
1 n->v rot
1 swap times
[ i^ 1+ *
dup n->v 1/v
rot dip
[ v+ 2dup
i^ 1+ 5 echo-rj
say " : "
temp share point$ echo$
cr ] ]
3 times drop temp release ] is approximate-e ( n n --> )
55 70 approximate-e
- Output:
First 55 approximations of e by sum of 1/n! displayed to 70 decimal places. 1 : 2 2 : 2.5 3 : 2.6666666666666666666666666666666666666666666666666666666666666666666667 4 : 2.7083333333333333333333333333333333333333333333333333333333333333333333 5 : 2.7166666666666666666666666666666666666666666666666666666666666666666667 6 : 2.7180555555555555555555555555555555555555555555555555555555555555555556 7 : 2.7182539682539682539682539682539682539682539682539682539682539682539683 8 : 2.7182787698412698412698412698412698412698412698412698412698412698412698 9 : 2.7182815255731922398589065255731922398589065255731922398589065255731922 10 : 2.7182818011463844797178130511463844797178130511463844797178130511463845 11 : 2.7182818261984928651595318261984928651595318261984928651595318261984929 12 : 2.7182818282861685639463417241195018972796750574528352306130083907861686 13 : 2.718281828446759002314557870113425668981224536780092335647891203446759 14 : 2.7182818284582297479122875948272773669599066424463249860075256900653726 15 : 2.7182818284589944642854695764748674801584854494907404960315013225066135 16 : 2.7182818284590422590587934503278418622333966249310164654079997995341911 17 : 2.718281828459045070516047795848605061178979635251032698900735004065225 18 : 2.7182818284590452267081174817108696833426231358243669340947758487613936 19 : 2.7182818284590452349287527283351994002986043726966476833155148405875077 20 : 2.7182818284590452353397844906664158861464034345402617207765517901788134 21 : 2.7182818284590452353593574317298071473772510089137671511318392639688756 22 : 2.7182818284590452353602471108690522047059258986580173979661705127775148 23 : 2.7182818284590452353602857925707585115463030677773326260894023062039774 24 : 2.71828182845904523536028740430832960766465211649063742726120363093008 25 : 2.7182818284590452353602874687778324515093860784391696193080756839191241 26 : 2.7182818284590452353602874712574287147341835385141131651560323013417796 27 : 2.7182818284590452353602874713492656133721389999983703335207714353203965 28 : 2.7182818284590452353602874713525455026092088379085223752480835472482042 29 : 2.7182818284590452353602874713526586022380733150778379628938529304181287 30 : 2.7182818284590452353602874713526623722257021309834818158153785765237928 31 : 2.7182818284590452353602874713526624938382062863352767788128471457530078 32 : 2.7182818284590452353602874713526624976385970411900203714065180385414207 33 : 2.718281828459045235360287471352662497753760397397739874212386853474403 34 : 2.718281828459045235360287471352662497757147554933261036059618289207726 35 : 2.7182818284590452353602874713526624977572443308628473549695391873715352 36 : 2.7182818284590452353602874713526624977572470190831136416059258789871966 37 : 2.7182818284590452353602874713526624977572470917377154331366390328146469 38 : 2.7182818284590452353602874713526624977572470936496786381769209579153692 39 : 2.7182818284590452353602874713526624977572470936987033357420563918923108 40 : 2.7182818284590452353602874713526624977572470936999289531811847777417344 41 : 2.7182818284590452353602874713526624977572470936999588462894562017868423 42 : 2.7182818284590452353602874713526624977572470936999595580301293309307734 43 : 2.7182818284590452353602874713526624977572470936999595745822380083527253 44 : 2.7182818284590452353602874713526624977572470936999595749584222964759515 45 : 2.7182818284590452353602874713526624977572470936999595749667819473231343 46 : 2.7182818284590452353602874713526624977572470936999595749669636788632904 47 : 2.7182818284590452353602874713526624977572470936999595749669675454918044 48 : 2.7182818284590452353602874713526624977572470936999595749669676260465651 49 : 2.7182818284590452353602874713526624977572470936999595749669676276905398 50 : 2.7182818284590452353602874713526624977572470936999595749669676277234193 51 : 2.718281828459045235360287471352662497757247093699959574966967627724064 52 : 2.7182818284590452353602874713526624977572470936999595749669676277240764 53 : 2.7182818284590452353602874713526624977572470936999595749669676277240766 54 : 2.7182818284590452353602874713526624977572470936999595749669676277240766 55 : 2.7182818284590452353602874713526624977572470936999595749669676277240766
Racket
#lang racket
(require math/number-theory)
(define (calculate-e (terms 20))
(apply + (map (compose / factorial) (range terms))))
(module+ main
(let ((e (calculate-e)))
(displayln e)
(displayln (real->decimal-string e 20))
(displayln (real->decimal-string (- (exp 1) e) 20))))
- Output:
82666416490601/30411275102208 2.71828182845904523493 0.00000000000000000000
Raku
(formerly Perl 6)
# If you need high precision: Sum of a Taylor series method.
# Adjust the terms parameter to suit. Theoretically the
# terms could be ∞. Practically, calculating an infinite
# series takes an awfully long time so limit to 500.
sub postfix:<!> (Int $n) { (constant f = 1, |[\*] 1..*)[$n] }
sub 𝑒 (Int $terms) { sum map { FatRat.new(1,.!) }, ^$terms }
say 𝑒(500).comb(80).join: "\n";
say '';
# Or, if you don't need high precision, it's a built-in.
say e;
- Output:
2.718281828459045235360287471352662497757247093699959574966967627724076630353547 59457138217852516642742746639193200305992181741359662904357290033429526059563073 81323286279434907632338298807531952510190115738341879307021540891499348841675092 44761460668082264800168477411853742345442437107539077744992069551702761838606261 33138458300075204493382656029760673711320070932870912744374704723069697720931014 16928368190255151086574637721112523897844250569536967707854499699679468644549059 87931636889230098793127736178215424999229576351482208269895193668033182528869398 49646510582093923982948879332036250944311730123819706841614039701983767932068328 23764648042953118023287825098194558153017567173613320698112509961818815930416903 51598888519345807273866738589422879228499892086805825749279610484198444363463244 96848756023362482704197862320900216099023530436994184914631409343173814364054625 31520961836908887070167683964243781405927145635490613031072085103837505101157477 04171898610687396965521267154688957035035402123407849819334321068170121005627880 23519303322474501585390473041995777709350366041699732972508868769664035557071622 684471625608 2.71828182845905
REXX
version 1
This REXX version uses the following formula to calculate Napier's constant e:
╔═══════════════════════════════════════════════════════════════════════════════════════╗ ║ ║ ║ 1 1 1 1 1 1 1 ║ ║ e = ─── + ─── + ─── + ─── + ─── + ─── + ─── + ∙∙∙ ║ ║ 0! 1! 2! 3! 4! 5! 6! ║ ║ ║ ╚═══════════════════════════════════════════════════════════════════════════════════════╝
If the argument (digs) is negative, a running number of decimal digits of e is shown.
/*REXX pgm calculates e to a # of decimal digits. If digs<0, a running value is shown.*/
parse arg digs . /*get optional number of decimal digits*/
if digs=='' | digs=="," then digs= 101 /*Not specified? Then use the default.*/
numeric digits abs(digs); w=length(digits()) /*use the absolute value of digs. */
e= 1; q= 1 /*1st value of e and q. */
do #=1 until e==old; old= e /*start calculations at the second term*/
q= q / # /*calculate the divisor for this term. */
e= e + q /*add quotient to running e value. */
if digs>0 then iterate /*DIGS>0? Then don't show running digs*/
$= compare(e, old) /*$ is first digit not compared equal.*/
if $>0 then say right('with', 10) right(#+1, w) "terms," right($-1, w),
"decimal digits were calculated for e (Napier's constant)" /* ↑ */
end /*#*/ /* -1 is for the decimal point────┘ */
say /*stick a fork in it, we're all done. */
say '(with' abs(digs) "decimal digits) the value of e is:"; say e
Programming note: the factorial of the do loop index is calculated by division, not by the usual multiplication (for optimization).
- output when using the default input:
(with 101 decimal digits) the value of e is: 2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274
- output when using the input of: -101
(Shown at three-quarter size.)
with 2 terms, 0 decimal digits were calculated for e (Napier's constant) with 3 terms, 1 decimal digits were calculated for e (Napier's constant) with 4 terms, 2 decimal digits were calculated for e (Napier's constant) with 5 terms, 2 decimal digits were calculated for e (Napier's constant) with 6 terms, 3 decimal digits were calculated for e (Napier's constant) with 7 terms, 4 decimal digits were calculated for e (Napier's constant) with 8 terms, 5 decimal digits were calculated for e (Napier's constant) with 9 terms, 6 decimal digits were calculated for e (Napier's constant) with 10 terms, 6 decimal digits were calculated for e (Napier's constant) with 11 terms, 8 decimal digits were calculated for e (Napier's constant) with 12 terms, 9 decimal digits were calculated for e (Napier's constant) with 13 terms, 10 decimal digits were calculated for e (Napier's constant) with 14 terms, 11 decimal digits were calculated for e (Napier's constant) with 15 terms, 12 decimal digits were calculated for e (Napier's constant) with 16 terms, 14 decimal digits were calculated for e (Napier's constant) with 17 terms, 13 decimal digits were calculated for e (Napier's constant) with 18 terms, 16 decimal digits were calculated for e (Napier's constant) with 19 terms, 17 decimal digits were calculated for e (Napier's constant) with 20 terms, 18 decimal digits were calculated for e (Napier's constant) with 21 terms, 19 decimal digits were calculated for e (Napier's constant) with 22 terms, 21 decimal digits were calculated for e (Napier's constant) with 23 terms, 21 decimal digits were calculated for e (Napier's constant) with 24 terms, 24 decimal digits were calculated for e (Napier's constant) with 25 terms, 25 decimal digits were calculated for e (Napier's constant) with 26 terms, 27 decimal digits were calculated for e (Napier's constant) with 27 terms, 27 decimal digits were calculated for e (Napier's constant) with 28 terms, 29 decimal digits were calculated for e (Napier's constant) with 29 terms, 30 decimal digits were calculated for e (Napier's constant) with 30 terms, 32 decimal digits were calculated for e (Napier's constant) with 31 terms, 33 decimal digits were calculated for e (Napier's constant) with 32 terms, 35 decimal digits were calculated for e (Napier's constant) with 33 terms, 37 decimal digits were calculated for e (Napier's constant) with 34 terms, 38 decimal digits were calculated for e (Napier's constant) with 35 terms, 40 decimal digits were calculated for e (Napier's constant) with 36 terms, 41 decimal digits were calculated for e (Napier's constant) with 37 terms, 43 decimal digits were calculated for e (Napier's constant) with 38 terms, 45 decimal digits were calculated for e (Napier's constant) with 39 terms, 46 decimal digits were calculated for e (Napier's constant) with 40 terms, 48 decimal digits were calculated for e (Napier's constant) with 41 terms, 49 decimal digits were calculated for e (Napier's constant) with 42 terms, 51 decimal digits were calculated for e (Napier's constant) with 43 terms, 52 decimal digits were calculated for e (Napier's constant) with 44 terms, 54 decimal digits were calculated for e (Napier's constant) with 45 terms, 56 decimal digits were calculated for e (Napier's constant) with 46 terms, 57 decimal digits were calculated for e (Napier's constant) with 47 terms, 59 decimal digits were calculated for e (Napier's constant) with 48 terms, 61 decimal digits were calculated for e (Napier's constant) with 49 terms, 62 decimal digits were calculated for e (Napier's constant) with 50 terms, 64 decimal digits were calculated for e (Napier's constant) with 51 terms, 65 decimal digits were calculated for e (Napier's constant) with 52 terms, 67 decimal digits were calculated for e (Napier's constant) with 53 terms, 69 decimal digits were calculated for e (Napier's constant) with 54 terms, 71 decimal digits were calculated for e (Napier's constant) with 55 terms, 72 decimal digits were calculated for e (Napier's constant) with 56 terms, 74 decimal digits were calculated for e (Napier's constant) with 57 terms, 76 decimal digits were calculated for e (Napier's constant) with 58 terms, 78 decimal digits were calculated for e (Napier's constant) with 59 terms, 80 decimal digits were calculated for e (Napier's constant) with 60 terms, 81 decimal digits were calculated for e (Napier's constant) with 61 terms, 83 decimal digits were calculated for e (Napier's constant) with 62 terms, 84 decimal digits were calculated for e (Napier's constant) with 63 terms, 87 decimal digits were calculated for e (Napier's constant) with 64 terms, 88 decimal digits were calculated for e (Napier's constant) with 65 terms, 91 decimal digits were calculated for e (Napier's constant) with 66 terms, 92 decimal digits were calculated for e (Napier's constant) with 67 terms, 94 decimal digits were calculated for e (Napier's constant) with 68 terms, 96 decimal digits were calculated for e (Napier's constant) with 69 terms, 98 decimal digits were calculated for e (Napier's constant) with 70 terms, 100 decimal digits were calculated for e (Napier's constant) with 71 terms, 101 decimal digits were calculated for e (Napier's constant) (with 101 decimal digits) the value of e is: 2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274
version 2
Using the series shown in version 1 compute e to the specified precision.
/*REXX pgm calculates e to nn of decimal digits */
Parse Arg dig /* the desired precision */
Numeric Digits (dig+3) /* increase precision */
dig2=dig+2 /* limit the loop */
e=1 /* first element of the series */
q=1 /* next element of the series */
Do n=1 By 1 /* start adding the elements */
old=e /* current sum */
q=q/n /* new element */
e=e+q /* add the new element to the sum */
If left(e,dig2)=left(old,dig2) Then /* no change */
Leave /* we are done */
End
Numeric Digits dig /* the desired precision */
e=e/1 /* the desired approximation */
Return left(e,dig+1) '('n 'iterations required)'
- Output:
J:\>rexx eval compey(66) compey(66)=2.71828182845904523536028747135266249775724709369995957496696762772 (52 iterations required)
Check the function's correctness
/*REXX check the correctness of compey */
e_='2.7182818284590452353602874713526624977572470936999595749669676277240'||,
'766303535475945713821785251664274274663919320030599218174135966290435'||,
'729003342952605956307380251882050351967424723324653614466387706813388353430034'
ok=0
Do d=3 To 100
Parse Value compey(d) with e .
Numeric digits d
If e<>e_/1 Then Do
say d e
Say e
Say e_/1
End
Else ok=ok+1
End
Say ok 'comparisons are ok'
- Output:
J:\>rexx compez 98 comparisons are ok
Ring
# Project : Calculating the value of e
decimals(14)
for n = 1 to 100000
e = pow((1 + 1/n),n)
next
see "Calculating the value of e with method #1:" + nl
see "e = " + e + nl
e = 0
for n = 0 to 12
e = e + (1 / factorial(n))
next
see "Calculating the value of e with method #2:" + nl
see "e = " + e + nl
func factorial(n)
if n = 0 or n = 1
return 1
else
return n * factorial(n-1)
ok
Output:
Calculating the value of e with method #1: e = 2.71826823719230 Calculating the value of e with method #2: e = 2.71828182828617
Ruby
fact = 1
e = 2
e0 = 0
n = 2
until (e - e0).abs < Float::EPSILON do
e0 = e
fact *= n
n += 1
e += 1.0 / fact
end
puts e
Built in:
require "bigdecimal/math"
puts BigMath.E(50).to_s # 50 decimals
- Output:
0.27182818284590452353602874713526624977572470937e1
Rust
const EPSILON: f64 = 1e-15;
fn main() {
let mut fact: u64 = 1;
let mut e: f64 = 2.0;
let mut n: u64 = 2;
loop {
let e0 = e;
fact *= n;
n += 1;
e += 1.0 / fact as f64;
if (e - e0).abs() < EPSILON {
break;
}
}
println!("e = {:.15}", e);
}
- Output:
e = 2.718281828459046
Scala
- Output:
Best seen running in your browser either by ScalaFiddle (ES aka JavaScript, non JVM) or Scastie (remote JVM).
import scala.annotation.tailrec
object CalculateE extends App {
private val ε = 1.0e-15
@tailrec
def iter(fact: Long, ℯ: Double, n: Int, e0: Double): Double = {
val newFact = fact * n
val newE = ℯ + 1.0 / newFact
if (math.abs(newE - ℯ) < ε) ℯ
else iter(newFact, newE, n + 1, ℯ)
}
println(f"ℯ = ${iter(1L, 2.0, 2, 0)}%.15f")
}
Scheme
(import (rnrs))
(define (e)
(sum
(map
(lambda (x) (/ 1.0 x))
(scanl
(lambda (a x) (* a x))
1
(enum-from-to 1 20)))))
(define (enum-from-to m n)
(if (>= n m)
(iterate-until (lambda (x) (>= x n)) (lambda (x) (+ 1 x)) m)
'()))
(define (iterate-until p f x)
(let loop ((vs (list x)) (h x))
(if (p h)
(reverse vs)
(loop (cons (f h) vs) (f h)))))
(define (sum xs)
(fold-left + 0 xs))
(define-record-type scan (fields acc scan))
(define (scanl f start-value xs)
(scan-scan
(fold-left
(lambda (a x)
(let ((v (f (scan-acc a) x)))
(make-scan v (cons v (scan-scan a)))))
(make-scan start-value (cons start-value '()))
xs)))
(display (e))
(newline)
High Precision
Series Implementation
Scheme will in general, when passed an exact value (integer or rational), try to preserve the
exactness of the calculation. So, calling exp with the integer 1 will return an exact rational
value, allowing for higher precision than floating point would.
; Use series to compute approximation to exp(z) (using N terms of series).
; n-1
; exp(z) ~ SUM ( z^k / k! )
; k=0
(define exp
(lambda (z n)
(do ((k 0 (1+ k))
(sum 0 (+ sum (/ (expt z k) (fact k)))))
((>= k n) sum))))
; Procedure to compute factorial.
(define fact
(lambda (n)
(if (<= n 0)
1
(* n (fact (1- n))))))
Convert for Display
; Convert the given Rational number to a Decimal string.
; If opt contains an integer, show to that many places past the decimal regardless of repeating.
; If opt contains 'nopar, do not insert the parentheses indicating the repeating places.
; If opt contains 'plus, prefix positive numbers with plus ('+') sign.
; N.B.: When number of decimals specified, this truncates instead of rounds.
(define rat->dec-str
(lambda (rat . opt)
(let* ((num (abs (numerator rat)))
(den (abs (denominator rat)))
(no-par (find (lambda (a) (eq? a 'nopar)) opt))
(plus (find (lambda (a) (eq? a 'plus)) opt))
(dec-lim (find integer? opt))
(rep-inx #f)
(rems-seen '())
(int-part (format (cond ((< rat 0) "-~d") (plus "+~d") (else "~d")) (quotient num den)))
(frc-list
(cond
((zero? num)
'())
(else
(let loop ((rem (modulo num den)) (decs 0))
(cond
((or (<= rem 0) (and dec-lim (>= decs dec-lim)))
'())
((and (not dec-lim) (assq rem rems-seen))
(set! rep-inx (cdr (assq rem rems-seen)))
'())
(else
(set! rems-seen (cons (cons rem decs) rems-seen))
(cons
(integer->char (+ (quotient (* 10 rem) den) (char->integer #\0)))
(loop (modulo (* 10 rem) den) (1+ decs))))))))))
(when (and rep-inx (not no-par))
(set! frc-list (append
(list-head frc-list rep-inx)
(list #\()
(list-tail frc-list rep-inx)
(list #\)))))
(if (null? frc-list)
int-part
(format "~a.~a" int-part (list->string frc-list))))))
The Task
; Use the series approximation to exp(z) to compute e (= exp(1)) to 100 places.
(let*
((n 75)
(p 100)
(z 1)
(e (exp z n)))
(newline)
(printf "Computing exp(~a) using ~a terms...~%" z n)
(printf "the computed exact rational:~%~a~%" e)
(printf "converted to decimal (~a places):~%~a~%" p (rat->dec-str e p))
(printf "converted to an inexact (float):~%~a~%" (exact->inexact e)))
- Output:
Computing exp(1) using 75 terms... the computed exact rational: 179835297726127476904046655197496828465249950976990919915482284588791312285099346749580175495960957663725089/66157708830387728245190605644250756429136650364186994234122385367082247140194313091850174464000000000000000 converted to decimal (100 places): 2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274 converted to an inexact (float): 2.718281828459045
Seed7
The Seed7 library math.s7i defines the constant E. The program below computes e:
$ include "seed7_05.s7i";
include "float.s7i";
const float: EPSILON is 1.0e-15;
const proc: main is func
local
var integer: fact is 1;
var float: e is 2.0;
var float: e0 is 0.0;
var integer: n is 2;
begin
repeat
e0 := e;
fact *:= n;
incr(n);
e +:= 1.0 / flt(fact);
until abs(e - e0) < EPSILON;
writeln("e = " <& e digits 15);
end func;
- Output:
e = 2.718281828459046
Sidef
func calculate_e(n=50) {
sum(0..n, {|k| 1/k! })
}
say calculate_e()
say calculate_e(69).as_dec(100)
- Output:
2.7182818284590452353602874713526624977572470937 2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427
For finding the number of required terms for calculating e to a given number of decimal places, using the formula Sum_{k=0..n} 1/k!, we have:
func f(n) {
var t = n*log(10)
(n + 10).bsearch_le { |k|
lngamma(k+1) <=> t
}
}
for k in (1..10) {
var n = f(10**k)
say "Sum_{k=0..#{n}} 1/k! = e correct to #{10**k->commify} decimal places"
}
- Output:
Sum_{k=0..13} 1/k! = e correct to 10 decimal places Sum_{k=0..69} 1/k! = e correct to 100 decimal places Sum_{k=0..449} 1/k! = e correct to 1,000 decimal places Sum_{k=0..3248} 1/k! = e correct to 10,000 decimal places Sum_{k=0..25205} 1/k! = e correct to 100,000 decimal places Sum_{k=0..205022} 1/k! = e correct to 1,000,000 decimal places Sum_{k=0..1723507} 1/k! = e correct to 10,000,000 decimal places Sum_{k=0..14842906} 1/k! = e correct to 100,000,000 decimal places Sum_{k=0..130202808} 1/k! = e correct to 1,000,000,000 decimal places Sum_{k=0..1158787577} 1/k! = e correct to 10,000,000,000 decimal places
Standard ML
fun calcEToEps() =
let
val eps = 1.0e~15
fun calcToEps'(eest: real, prev: real, denom, i) =
if Real.abs(eest - prev) < eps then
eest
else
let
val denom' = denom * i;
val prev' = eest
in
calcToEps'(eest + 1.0/denom', prev', denom', i + 1.0)
end
in
calcToEps'(2.0, 1.0, 1.0, 2.0)
end;
- Output:
- val eEst = calcEToEps(); val eEst = 2.71828182846 : real - Math.e - eEst; val it = ~4.4408920985E~16 : real
Swift
import Foundation
func calculateE(epsilon: Double = 1.0e-15) -> Double {
var fact: UInt64 = 1
var e = 2.0, e0 = 0.0
var n = 2
repeat {
e0 = e
fact *= UInt64(n)
n += 1
e += 1.0 / Double(fact)
} while fabs(e - e0) >= epsilon
return e
}
print(String(format: "e = %.15f\n", arguments: [calculateE()]))
- Output:
e = 2.718281828459046
Tcl
By the power series of exp(x)
set ε 1.0e-15
set fact 1
set e 2.0
set e0 0.0
set n 2
while {[expr abs($e - $e0)] > ${ε}} {
set e0 $e
set fact [expr $fact * $n]
incr n
set e [expr $e + 1.0/$fact]
}
puts "e = $e"
- Output:
e = 2.7182818284590455
By the continued fraction for e
This has the advantage, that arbitrary large precision can be achieved, should that become a demand. Also, full precision for the floating point value can be guaranteed.
## We use (regular) continued fractions, step by step.
## The partial CF is coded (a n b m) for (a+nr) / (b+mr) for rest r.
## The (current) approximation is a/b (for r=0)
proc cfExt {anbm u} {
if {$u <= 0} {
return $anbm
}
lassign $anbm a n b m
set na [expr {($a * $u) + $n}]
set nn $a
set nb [expr {($b * $u) + $m}]
set nm $b
return [list $na $nn $nb $nm]
}
proc cfPrec {anbm} {
lassign $anbm a n b m
## The next term will change about 1 / (b*m)
return [expr {[string length $b$m] - 1}]
}
proc cfInt {k} {
return [list $k 1 1 0]
}
proc calcE {decplaces} {
## cf for e is [2;1, 2,1,1, 4,1,1, 6,1,1, 8,1,1, ...]
set ecf [cfInt 2]
set ecf [cfExt $ecf 1]
for {set j 2} {1} {incr j 2} {
if {[cfPrec $ecf] >= $decplaces} {
break
}
set ecf [cfExt $ecf $j]
set ecf [cfExt $ecf 1]
set ecf [cfExt $ecf 1]
}
lassign $ecf a n b m
set q [expr {(10**$decplaces * $a) / $b}]
puts "e = $a / $b ([string range $q 0 0].[string range $q 1 end])"
puts "e = [expr {(0.0 + $a) / $b}]"
}
calcE 17
- Output:
e = 848456353 / 312129649 (2.71828182845904523) e = 2.718281828459045
TI-83 BASIC
Guided by the Awk version.
0->D
2->N
2->E
1->F
1.0E-12->Z
While abs(E-D)>Z
F*N->F
N+1->N
E->D
E+1/F->E
End
Disp E
- Output:
2.718281828
VBScript
e0 = 0 : e = 2 : n = 0 : fact = 1
While (e - e0) > 1E-15
e0 = e
n = n + 1
fact = fact * 2*n * (2*n + 1)
e = e + (2*n + 2)/fact
Wend
WScript.Echo "Computed e = " & e
WScript.Echo "Real e = " & Exp(1)
WScript.Echo "Error = " & (Exp(1) - e)
WScript.Echo "Number of iterations = " & n
- Output:
Computed e = 2.71828182845904 Real e = 2.71828182845905 Error = 4.44089209850063E-16 Number of iterations = 9
Verilog
module main;
real n, n1;
real e1, e;
initial begin
n = 1.0;
n1 = 1.0;
e1 = 0.0;
e = 1.0;
while (e != e1) begin
e1 = e;
e = e + (1.0 / n);
n1 = n1 + 1;
n = n * n1;
end
$display("The value of e = ", e);
$finish ;
end
endmodule
- Output:
The value of e = 2.71828
Visual Basic .NET
Automatically determines number of padding digits required for the arbitrary precision output. Can calculate a quarter million digits of e in under a half a minute.
Imports System, System.Numerics, System.Math, System.Console
Module Program
Function CalcE(ByVal nDigs As Integer) As String
Dim pad As Integer = Round(Log10(nDigs)), n = 1,
f As BigInteger = BigInteger.Pow(10, nDigs + pad), e = f + f
Do : n+= 1 : f /= n : e += f : Loop While f > n
Return (e / BigInteger.Pow(10, pad + 1)).ToString().Insert(1, ".")
End Function
Sub Main()
WriteLine(Exp(1)) ' double precision built-in function
WriteLine(CalcE(100)) ' arbitrary precision result
Dim st As DateTime = DateTime.Now, qmil As Integer = 250_000,
es As String = CalcE(qmil) ' large arbitrary precision result string
WriteLine("{0:n0} digits in {1:n3} seconds.", qmil, (DateTime.Now - st).TotalSeconds)
WriteLine("partial: {0}...{1}", es.Substring(0, 46), es.Substring(es.Length - 45))
End Sub
End Module
- Output:
2.71828182845905 2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427 250,000 digits in 22.559 seconds. partial: 2.71828182845904523536028747135266249775724709...026587951482508371108187783411598287506586313
Vlang
import math
const epsilon = 1.0e-15
fn main() {
mut fact := u64(1)
mut e := 2.0
mut n := u64(2)
for {
e0 := e
fact *= n
n++
e += 1.0 / f64(fact)
if math.abs(e - e0) < epsilon {
break
}
}
println("e = ${e:.15f}")
}
- Output:
e = 2.718281828459046
Wren
var epsilon = 1e-15
var fact = 1
var e = 2
var n = 2
while (true) {
var e0 = e
fact = fact * n
n = n + 1
e = e + 1/fact
if ((e - e0).abs < epsilon) break
}
System.print("e = %(e)")
- Output:
e = 2.718281828459
XPL0
real N, E, E0, F; \index, Euler numbers, factorial
[Format(1, 16); \show 16 places after decimal point
N:= 1.0; E:= 1.0; F:= 1.0;
loop [E0:= E;
E:= E + 1.0/F;
if E = E0 then quit;
N:= N + 1.0;
F:= F*N;
];
RlOut(0, E); CrLf(0);
IntOut(0, fix(N)); Text(0, " iterations");
]
- Output:
2.7182818284590500 18 iterations
Zig
This uses the continued fraction method to generate the maximum ratio that can be computed using 64 bit math. The final ratio is correct to 35 decimal places.
const std = @import("std");
const math = std.math;
const stdout = std.io.getStdOut().writer();
pub fn main() !void {
var n: u32 = 0;
var state: u2 = 0;
var p0: u64 = 0;
var q0: u64 = 1;
var p1: u64 = 1;
var q1: u64 = 0;
while (true) {
var a: u64 = undefined;
switch (state) {
0 => {
a = 2;
state = 1;
},
1 => {
a = 1;
state = 2;
},
2 => {
n += 2;
a = n;
state = 3;
},
3 => {
a = 1;
state = 1;
},
}
var p2: u64 = undefined;
var q2: u64 = undefined;
if (@mulWithOverflow(u64, a, p1, &p2) or
@addWithOverflow(u64, p2, p0, &p2) or
@mulWithOverflow(u64, a, q1, &q2) or
@addWithOverflow(u64, q2, q0, &q2))
{
break;
}
try stdout.print("e ~= {d:>19} / {d:>19} = ", .{p2, q2});
try dec_print(stdout, p2, q2, 36);
try stdout.writeByte('\n');
p0 = p1;
p1 = p2;
q0 = q1;
q1 = q2;
}
}
fn dec_print(ostream: anytype, num: u64, den: u64, prec: usize) !void {
// print out integer part.
try ostream.print("{}.", .{num / den});
// arithmetic with the remainders is done with u128, as the
// multiply by 10 could potentially overflow a u64.
//
const m = @intCast(u128, den);
var r = @as(u128, num) % m;
var dec: usize = 0; // decimal place we're in.
while (dec < prec and r > 0) {
const n = 10 * r;
r = n % m;
dec += 1;
const ch = @intCast(u8, n / m) + '0';
try ostream.writeByte(ch);
}
}
- Output:
e ~= 2 / 1 = 2. e ~= 3 / 1 = 3. e ~= 8 / 3 = 2.666666666666666666666666666666666666 e ~= 11 / 4 = 2.75 e ~= 19 / 7 = 2.714285714285714285714285714285714285 e ~= 87 / 32 = 2.71875 e ~= 106 / 39 = 2.717948717948717948717948717948717948 e ~= 193 / 71 = 2.718309859154929577464788732394366197 e ~= 1264 / 465 = 2.718279569892473118279569892473118279 e ~= 1457 / 536 = 2.718283582089552238805970149253731343 e ~= 2721 / 1001 = 2.718281718281718281718281718281718281 e ~= 23225 / 8544 = 2.718281835205992509363295880149812734 e ~= 25946 / 9545 = 2.718281822943949711891042430591932949 e ~= 49171 / 18089 = 2.718281828735695726684725523798993863 e ~= 517656 / 190435 = 2.718281828445401318035025074172289757 e ~= 566827 / 208524 = 2.718281828470583721777828930962383226 e ~= 1084483 / 398959 = 2.718281828458563411277850606202642376 e ~= 13580623 / 4996032 = 2.718281828459065114074529546648220027 e ~= 14665106 / 5394991 = 2.718281828459028013207065591026935911 e ~= 28245729 / 10391023 = 2.718281828459045851404621084949961134 e ~= 410105312 / 150869313 = 2.718281828459045213521983758221262663 e ~= 438351041 / 161260336 = 2.718281828459045254624795027092092875 e ~= 848456353 / 312129649 = 2.718281828459045234757560631479773329 e ~= 14013652689 / 5155334720 = 2.718281828459045235379013372772815806 e ~= 14862109042 / 5467464369 = 2.718281828459045235343535532787301096 e ~= 28875761731 / 10622799089 = 2.718281828459045235360753230188480692 e ~= 534625820200 / 196677847971 = 2.718281828459045235360274593941296140 e ~= 563501581931 / 207300647060 = 2.718281828459045235360299120911002524 e ~= 1098127402131 / 403978495031 = 2.718281828459045235360287179900086259 e ~= 22526049624551 / 8286870547680 = 2.718281828459045235360287478611074351 e ~= 23624177026682 / 8690849042711 = 2.718281828459045235360287464726031034 e ~= 46150226651233 / 16977719590391 = 2.718281828459045235360287471503357984 e ~= 1038929163353808 / 382200680031313 = 2.718281828459045235360287471349248563 e ~= 1085079390005041 / 399178399621704 = 2.718281828459045235360287471355803092 e ~= 2124008553358849 / 781379079653017 = 2.718281828459045235360287471352597036 e ~= 52061284670617417 / 19152276311294112 = 2.718281828459045235360287471352663857 e ~= 54185293223976266 / 19933655390947129 = 2.718281828459045235360287471352661238 e ~= 106246577894593683 / 39085931702241241 = 2.718281828459045235360287471352662521 e ~= 2816596318483412024 / 1036167879649219395 = 2.718281828459045235360287471352662497 e ~= 2922842896378005707 / 1075253811351460636 = 2.718281828459045235360287471352662498 e ~= 5739439214861417731 / 2111421691000680031 = 2.718281828459045235360287471352662497
zkl
const EPSILON=1.0e-15;
fact,e,n := 1, 2.0, 2;
do{
e0:=e;
fact*=n; n+=1;
e+=1.0/fact;
}while((e - e0).abs() >= EPSILON);
println("e = %.15f".fmt(e));
- Output:
e = 2.718281828459046
ZX Spectrum Basic
10 LET p=13: REM precision, or the number of terms in the Taylor expansion, from 0 to 33...
20 LET k=1: REM ...the Spectrum's maximum expressible precision is reached at p=13, while...
30 LET e=0: REM ...the factorial can't go any higher than 33
40 FOR x=1 TO p
50 LET e=e+1/k
60 LET k=k*x
70 NEXT x
80 PRINT e
90 PRINT e-EXP 1: REM the Spectrum ROM uses Chebyshev polynomials to evaluate EXP x = e^x
- Output:
2.7182818 9.3132257E-10
- Programming Tasks
- Solutions by Programming Task
- 11l
- 360 Assembly
- Action!
- Action! Tool Kit
- Action! Real Math
- Ada
- ALGOL 68
- AppleScript
- Applesoft BASIC
- Arturo
- Asymptote
- AWK
- BASIC
- BASIC256
- QBasic
- True BASIC
- Yabasic
- Befunge
- Burlesque
- C
- C sharp
- System.Numerics
- C++
- Clojure
- COBOL
- Commodore BASIC
- Common Lisp
- D
- Dc
- Delphi
- Dyalect
- EasyLang
- EDSAC order code
- Emacs Lisp
- Epoxy
- Excel
- F Sharp
- Factor
- FOCAL
- Forth
- Fortran
- Free Pascal
- FreeBASIC
- GMP
- Fōrmulæ
- Furor
- Go
- Groovy
- Haskell
- Icon
- Unicon
- IS-BASIC
- J
- Java
- JavaScript
- Jq
- Julia
- K
- Klingphix
- Kotlin
- Lambdatalk
- Langur
- Lua
- M2000 Interpreter
- Maple
- Mathematica
- Wolfram Language
- Min
- МК-61/52
- Modula-2
- Myrddin
- Nanoquery
- Nim
- Pascal
- Perl
- Phix
- Phixmonti
- PicoLisp
- PowerShell
- Processing
- Prolog
- PureBasic
- Python
- R
- Quackery
- Racket
- Raku
- REXX
- Ring
- Ruby
- Rust
- Scala
- Scheme
- Seed7
- Sidef
- Standard ML
- Swift
- Tcl
- TI-83 BASIC
- VBScript
- Verilog
- Visual Basic .NET
- Vlang
- Wren
- XPL0
- Zig
- Zkl
- ZX Spectrum Basic