Calculating the value of e: Difference between revisions

Content deleted Content added
Rdm (talk | contribs)
m →‎{{header|J}}: Remove "well, duh" statement.
Thundergnat (talk | contribs)
m syntax highlighting fixup automation
Line 13: Line 13:
=={{header|11l}}==
=={{header|11l}}==
{{trans|Python}}
{{trans|Python}}
<lang 11l>V e0 = 0.0
<syntaxhighlight lang=11l>V e0 = 0.0
V e = 2.0
V e = 2.0
V n = 0
V n = 0
Line 26: Line 26:
print(‘Real e = ’math:e)
print(‘Real e = ’math:e)
print(‘Error = ’(math:e - e))
print(‘Error = ’(math:e - e))
print(‘Number of iterations = ’n)</lang>
print(‘Number of iterations = ’n)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 38: Line 38:
The 'include' file FORMAT, to format a floating point number, can be found in:
The 'include' file FORMAT, to format a floating point number, can be found in:
[[360_Assembly_include|Include files 360 Assembly]].
[[360_Assembly_include|Include files 360 Assembly]].
<lang 360asm>* Calculating the value of e - 21/07/2018
<syntaxhighlight lang=360asm>* Calculating the value of e - 21/07/2018
CALCE PROLOG
CALCE PROLOG
LE F0,=E'0'
LE F0,=E'0'
Line 65: Line 65:
PG DC CL80' ' buffer
PG DC CL80' ' buffer
REGEQU
REGEQU
END CALCE </lang>
END CALCE </syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 74: Line 74:
{{libheader|Action! Tool Kit}}
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
{{libheader|Action! Real Math}}
<lang Action!>INCLUDE "H6:REALMATH.ACT"
<syntaxhighlight lang=Action!>INCLUDE "H6:REALMATH.ACT"


PROC Euler(REAL POINTER e)
PROC Euler(REAL POINTER e)
Line 108: Line 108:
Print("calculated e=") PrintRE(calc)
Print("calculated e=") PrintRE(calc)
Print(" error=") PrintRE(diff)
Print(" error=") PrintRE(diff)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Calculating_the_value_of_e.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Calculating_the_value_of_e.png Screenshot from Atari 8-bit computer]
Line 119: Line 119:
=={{header|Ada}}==
=={{header|Ada}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang=ada>with Ada.Text_IO; use Ada.Text_IO;
with Ada.Long_Float_Text_IO; use Ada.Long_Float_Text_IO;
with Ada.Long_Float_Text_IO; use Ada.Long_Float_Text_IO;


Line 143: Line 143:
New_Line;
New_Line;


end Euler;</lang>
end Euler;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 151: Line 151:
=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang algol68>BEGIN
<syntaxhighlight lang=algol68>BEGIN
# calculate an approximation to e #
# calculate an approximation to e #
LONG REAL epsilon = 1.0e-15;
LONG REAL epsilon = 1.0e-15;
Line 165: Line 165:
DO SKIP OD;
DO SKIP OD;
print( ( "e = ", fixed( e, -17, 15 ), newline ) )
print( ( "e = ", fixed( e, -17, 15 ), newline ) )
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 174: Line 174:
For the purposes of 32 bit floating point, the value seems to stabilise after summing c. 16 terms.
For the purposes of 32 bit floating point, the value seems to stabilise after summing c. 16 terms.


<lang applescript>--------------- CALCULATING THE VALUE OF E ----------------
<syntaxhighlight lang=applescript>--------------- CALCULATING THE VALUE OF E ----------------
on run
on run
Line 271: Line 271:
foldl(add, 0, xs)
foldl(add, 0, xs)
end sum</lang>
end sum</syntaxhighlight>
{{Out}}
{{Out}}
<pre>2.718281828459</pre>
<pre>2.718281828459</pre>


Or, as a single fold:
Or, as a single fold:
<lang AppleScript>------------- APPROXIMATION OF THE VALUE OF E ------------
<syntaxhighlight lang=AppleScript>------------- APPROXIMATION OF THE VALUE OF E ------------


-- eApprox :: Int -> Float
-- eApprox :: Int -> Float
Line 340: Line 340:
end script
end script
end if
end if
end mReturn</lang>
end mReturn</syntaxhighlight>
{{Out}}
{{Out}}
<pre>2.718281828459</pre>
<pre>2.718281828459</pre>


=={{header|Applesoft BASIC}}==
=={{header|Applesoft BASIC}}==
<lang>?"E = "EXP(1)</lang>
<syntaxhighlight lang=text>?"E = "EXP(1)</syntaxhighlight>
{{Out}}
{{Out}}
<pre>E = 2.71828183</pre>
<pre>E = 2.71828183</pre>
Line 351: Line 351:
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>fact: 1
<syntaxhighlight lang=rebol>fact: 1
e: 2.0
e: 2.0
e0: 0.0
e0: 0.0
Line 364: Line 364:
]
]


print e</lang>
print e</syntaxhighlight>


{{out}}
{{out}}
Line 371: Line 371:


=={{header|Asymptote}}==
=={{header|Asymptote}}==
<lang Asymptote>real n, n1;
<syntaxhighlight lang=Asymptote>real n, n1;
real e1, e;
real e1, e;
Line 385: Line 385:
n *= n1;
n *= n1;
}
}
write("The value of e = ", e);</lang>
write("The value of e = ", e);</syntaxhighlight>
{{out}}
{{out}}
<pre>The value of e = 2.71828182845905</pre>
<pre>The value of e = 2.71828182845905</pre>


=={{header|AWK}}==
=={{header|AWK}}==
<lang AWK>
<syntaxhighlight lang=AWK>
# syntax: GAWK -f CALCULATING_THE_VALUE_OF_E.AWK
# syntax: GAWK -f CALCULATING_THE_VALUE_OF_E.AWK
BEGIN {
BEGIN {
Line 406: Line 406:
}
}
function abs(x) { if (x >= 0) { return x } else { return -x } }
function abs(x) { if (x >= 0) { return x } else { return -x } }
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 414: Line 414:
=={{header|BASIC}}==
=={{header|BASIC}}==
==={{header|BASIC256}}===
==={{header|BASIC256}}===
<lang freebasic>n = 1 : n1 = 1
<syntaxhighlight lang=freebasic>n = 1 : n1 = 1
e1 = 0 : e = 1 / 1
e1 = 0 : e = 1 / 1


Line 425: Line 425:


print "The value of e = "; e
print "The value of e = "; e
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>The value of e = 2.71828182829</pre>
<pre>The value of e = 2.71828182829</pre>
Line 432: Line 432:
{{works with|QBasic|1.1}}
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
{{works with|QuickBasic|4.5}}
<lang QBasic>n = 1: n1 = 1
<syntaxhighlight lang=QBasic>n = 1: n1 = 1


e! = 1 / 1
e! = 1 / 1
Line 443: Line 443:
LOOP
LOOP


PRINT "The value of e ="; e</lang>
PRINT "The value of e ="; e</syntaxhighlight>
{{out}}
{{out}}
<pre>The value of e = 2.718282</pre>
<pre>The value of e = 2.718282</pre>
Line 449: Line 449:
==={{header|True BASIC}}===
==={{header|True BASIC}}===
{{works with|QBasic}}
{{works with|QBasic}}
<lang qbasic>LET n = 1
<syntaxhighlight lang=qbasic>LET n = 1
LET n1 = 1
LET n1 = 1


Line 462: Line 462:


PRINT "The value of e ="; e
PRINT "The value of e ="; e
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>The value of e = 2.7182818</pre>
<pre>The value of e = 2.7182818</pre>
Line 469: Line 469:
{{works with|QBasic}}
{{works with|QBasic}}
{{works with|FreeBASIC| with #lang "qb"}}
{{works with|FreeBASIC| with #lang "qb"}}
<lang yabasic>n = 1 : n1 = 1
<syntaxhighlight lang=yabasic>n = 1 : n1 = 1
e1 = 0 : e = 1 / 1
e1 = 0 : e = 1 / 1


Line 479: Line 479:
wend
wend


print "The value of e = ", e</lang>
print "The value of e = ", e</syntaxhighlight>
{{out}}
{{out}}
<pre>The value of e = 2.71828</pre>
<pre>The value of e = 2.71828</pre>
Line 486: Line 486:
=={{header|Befunge}}==
=={{header|Befunge}}==
Befunge has no decimal capabilities, evaluates as fractions of 10^17
Befunge has no decimal capabilities, evaluates as fractions of 10^17
<lang befunge>52*92*1->01p:01g1-:v v *_$101p011p54*21p>:11g1+:01g*01p:11p/21g1-:v v <
<syntaxhighlight lang=befunge>52*92*1->01p:01g1-:v v *_$101p011p54*21p>:11g1+:01g*01p:11p/21g1-:v v <
^ _$$>\:^ ^ p12_$>+\:#^_$554**/@</lang>
^ _$$>\:^ ^ p12_$>+\:#^_$554**/@</syntaxhighlight>
{{out}}
{{out}}
<pre>2718281828459045</pre>
<pre>2718281828459045</pre>
Line 493: Line 493:


=={{header|Burlesque}}==
=={{header|Burlesque}}==
<lang burlesque>
<syntaxhighlight lang=burlesque>
blsq ) 70rz?!{10 100**\/./}ms36.+Sh'.1iash
blsq ) 70rz?!{10 100**\/./}ms36.+Sh'.1iash
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274
</syntaxhighlight>
</lang>


=={{header|C}}==
=={{header|C}}==
===solution 1===
===solution 1===
<lang c>#include <stdio.h>
<syntaxhighlight lang=c>#include <stdio.h>
#include <math.h>
#include <math.h>


Line 539: Line 539:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{output}}
{{output}}
<pre>
<pre>
Line 552: Line 552:
===solution 2===
===solution 2===
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang c>#include <stdio.h>
<syntaxhighlight lang=c>#include <stdio.h>
#include <math.h>
#include <math.h>


Line 569: Line 569:
printf("e = %.15f\n", e);
printf("e = %.15f\n", e);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{output}}
{{output}}
Line 577: Line 577:


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>using System;
<syntaxhighlight lang=csharp>using System;


namespace CalculateE {
namespace CalculateE {
Line 596: Line 596:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>e = 2.718281828459050</pre>
<pre>e = 2.718281828459050</pre>
Line 602: Line 602:


===Using Decimal type===
===Using Decimal type===
<lang csharp>using System;
<syntaxhighlight lang=csharp>using System;


class Calc_E
class Calc_E
Line 619: Line 619:
Console.WriteLine(CalcE()); // Decimal precision result
Console.WriteLine(CalcE()); // Decimal precision result
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>2.71828182845905
<pre>2.71828182845905
Line 626: Line 626:
{{libheader|System.Numerics}}
{{libheader|System.Numerics}}
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.
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.
<lang csharp>using System; using System.Numerics;
<syntaxhighlight lang=csharp>using System; using System.Numerics;
using static System.Math; using static System.Console;
using static System.Math; using static System.Console;


Line 648: Line 648:
WriteLine("partial: {0}...{1}", es.Substring(0, 46), es.Substring(es.Length - 45));
WriteLine("partial: {0}...{1}", es.Substring(0, 46), es.Substring(es.Length - 45));
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>2.71828182845905
<pre>2.71828182845905
Line 658: Line 658:
=={{header|C++}}==
=={{header|C++}}==
{{trans|C}}
{{trans|C}}
<lang cpp>#include <iostream>
<syntaxhighlight lang=cpp>#include <iostream>
#include <iomanip>
#include <iomanip>
#include <cmath>
#include <cmath>
Line 677: Line 677:
cout << "e = " << setprecision(16) << e << endl;
cout << "e = " << setprecision(16) << e << endl;
return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{output}}
{{output}}
Line 685: Line 685:


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>
<syntaxhighlight lang=clojure>
;; Calculating the number e, euler-napier number.
;; Calculating the number e, euler-napier number.
;; We will use two methods
;; We will use two methods
Line 717: Line 717:
(time (with-precision 110 (method-e 200M)))
(time (with-precision 110 (method-e 200M)))


</syntaxhighlight>
</lang>


<pre>
<pre>
Line 726: Line 726:
=={{header|COBOL}}==
=={{header|COBOL}}==
{{trans|C}}
{{trans|C}}
<lang COBOL> >>SOURCE FORMAT IS FIXED
<syntaxhighlight lang=COBOL> >>SOURCE FORMAT IS FIXED
IDENTIFICATION DIVISION.
IDENTIFICATION DIVISION.
PROGRAM-ID. EULER.
PROGRAM-ID. EULER.
Line 751: Line 751:
DISPLAY RESULT-MESSAGE.
DISPLAY RESULT-MESSAGE.
STOP RUN.
STOP RUN.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 759: Line 759:
=={{header|Commodore BASIC}}==
=={{header|Commodore BASIC}}==
Commodore BASIC floats have a 40-bit mantissa, so we get max precision after just 11 iterations:
Commodore BASIC floats have a 40-bit mantissa, so we get max precision after just 11 iterations:
<lang basic>
<syntaxhighlight lang=basic>
100 REM COMPUTE E VIA INVERSE FACTORIAL SUM
100 REM COMPUTE E VIA INVERSE FACTORIAL SUM
110 N = 11:REM NUMBER OF ITERATIONS
110 N = 11:REM NUMBER OF ITERATIONS
Line 768: Line 768:
160 : E = E + 1/F
160 : E = E + 1/F
170 NEXT I
170 NEXT I
180 PRINT "AFTER" N "ITERATIONS, E =" E</lang>
180 PRINT "AFTER" N "ITERATIONS, E =" E</syntaxhighlight>


{{Out}}
{{Out}}
Line 778: Line 778:
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 <tt>computable-reals</tt> makes printing out precise decimal representations easy, though:
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 <tt>computable-reals</tt> makes printing out precise decimal representations easy, though:


<lang lisp>(ql:quickload :computable-reals :silent t)
<syntaxhighlight lang=lisp>(ql:quickload :computable-reals :silent t)
(use-package :computable-reals)
(use-package :computable-reals)


Line 788: Line 788:
(setq e (+ e (/ 1 f))))
(setq e (+ e (/ 1 f))))
(format t "After ~a iterations, e = " *iterations*)
(format t "After ~a iterations, e = " *iterations*)
(print-r e 2570))</lang>
(print-r e 2570))</syntaxhighlight>


{{Out}}
{{Out}}
Line 797: Line 797:


=={{header|D}}==
=={{header|D}}==
<lang d>import std.math;
<syntaxhighlight lang=d>import std.math;
import std.stdio;
import std.stdio;


Line 813: Line 813:
} while (abs(e - e0) >= EPSILON);
} while (abs(e - e0) >= EPSILON);
writefln("e = %.15f", e);
writefln("e = %.15f", e);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>e = 2.718281828459046</pre>
<pre>e = 2.718281828459046</pre>
Line 822: Line 822:
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):
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):


<lang dc>1000 sn [ n = number of iterations ]sx
<syntaxhighlight lang=dc>1000 sn [ n = number of iterations ]sx
2574k [ precision to use during computation ]sx
2574k [ precision to use during computation ]sx
1 d se sf [ set e and f to 1 ]sx
1 d se sf [ set e and f to 1 ]sx
Line 840: Line 840:
2570k [ now reset precision to match correct digits ]sx
2570k [ now reset precision to match correct digits ]sx
le 1 / [ get result truncated to that precision ]sx
le 1 / [ get result truncated to that precision ]sx
n 10P [ and print it out, again with n + 10P ]sx</lang>
n 10P [ and print it out, again with n + 10P ]sx</syntaxhighlight>


{{Out}}
{{Out}}
Line 889: Line 889:


{{Trans|C}}
{{Trans|C}}
<lang Delphi>
<syntaxhighlight lang=Delphi>
program Calculating_the_value_of_e;
program Calculating_the_value_of_e;


Line 931: Line 931:
end.
end.


</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 942: Line 942:
{{trans|Swift}}
{{trans|Swift}}


<lang dyalect>func calculateE(epsilon = 1.0e-15) {
<syntaxhighlight lang=dyalect>func calculateE(epsilon = 1.0e-15) {
func abs(n) {
func abs(n) {
if n < 0 {
if n < 0 {
Line 970: Line 970:
}
}
print(calculateE())</lang>
print(calculateE())</syntaxhighlight>


{{out}}
{{out}}
Line 977: Line 977:


=={{header|EasyLang}}==
=={{header|EasyLang}}==
<lang>numfmt 0 5
<syntaxhighlight lang=text>numfmt 0 5
fact = 1
fact = 1
n = 2
n = 2
Line 987: Line 987:
e += 1 / fact
e += 1 / fact
.
.
print e</lang>
print e</syntaxhighlight>


=={{header|EDSAC order code}}==
=={{header|EDSAC order code}}==
Line 997: Line 997:
by calculating e - 2 and printing the result with '2' in front.
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.
It will be seen that the answer is 3 out in the 10th decimal place.
<lang edsac>
<syntaxhighlight lang=edsac>
[Calculate e]
[Calculate e]
[EDSAC program, Initial Orders 2]
[EDSAC program, Initial Orders 2]
Line 1,082: Line 1,082:
E14Z [relative address of entry]
E14Z [relative address of entry]
PF [enter with accumulator = 0]
PF [enter with accumulator = 0]
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,101: Line 1,101:


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).
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).
<lang edsac>
<syntaxhighlight lang=edsac>
[Calculate e by multilength variables.
[Calculate e by multilength variables.
EDSAC program, Initial Orders 2.
EDSAC program, Initial Orders 2.
Line 1,392: Line 1,392:
E 184 Z [define entry point]
E 184 Z [define entry point]
P F [acc = 0 on entry]
P F [acc = 0 on entry]
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,427: Line 1,427:
===Spigot algorithm===
===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".
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".
<lang edsac>
<syntaxhighlight lang=edsac>
[Code not given, as it is almost the same as the EDSAC spigot algorithm for 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.]
See the task "Pi" for the EDSAC program and the changes needed to calculate e.]
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,457: Line 1,457:


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<lang lisp>(defun factorial (i)
<syntaxhighlight lang=lisp>(defun factorial (i)
"Compute factorial of i."
"Compute factorial of i."
(apply #'* (number-sequence 1 i)))
(apply #'* (number-sequence 1 i)))
Line 1,466: Line 1,466:
(mapcar #'factorial (number-sequence 1 iter)))))
(mapcar #'factorial (number-sequence 1 iter)))))


(compute-e 20)</lang>
(compute-e 20)</syntaxhighlight>
{{output}}
{{output}}
<pre>
<pre>
Line 1,472: Line 1,472:


=={{header|Epoxy}}==
=={{header|Epoxy}}==
<lang epoxy>fn CalculateE(P)
<syntaxhighlight lang=epoxy>fn CalculateE(P)
var E:1,F:1
var E:1,F:1
loop I:1;I<=P;I+:1 do
loop I:1;I<=P;I+:1 do
Line 1,482: Line 1,482:


log(CalculateE(100))
log(CalculateE(100))
log(math.e)</lang>
log(math.e)</syntaxhighlight>
{{out}}
{{out}}
<pre>2.7182818284590455
<pre>2.7182818284590455
Line 1,495: Line 1,495:


{{Works with|Office 365 betas 2021}}
{{Works with|Office 365 betas 2021}}
<lang lisp>eApprox
<syntaxhighlight lang=lisp>eApprox
=LAMBDA(n,
=LAMBDA(n,
INDEX(
INDEX(
Line 1,518: Line 1,518:
1
1
)
)
)</lang>
)</syntaxhighlight>


and also assuming the following generic bindings in the Name Manager for the WorkBook:
and also assuming the following generic bindings in the Name Manager for the WorkBook:


<lang lisp>FOLDROW
<syntaxhighlight lang=lisp>FOLDROW
=LAMBDA(op,
=LAMBDA(op,
LAMBDA(a,
LAMBDA(a,
Line 1,568: Line 1,568:
)
)
)
)
)</lang>
)</syntaxhighlight>


{{Out}}
{{Out}}
Line 1,671: Line 1,671:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>
<syntaxhighlight lang=fsharp>
// A function to generate the sequence 1/n!). Nigel Galloway: May 9th., 2018
// 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)
let e = Seq.unfold(fun (n,g)->Some(n,(n/g,g+1N))) (1N,1N)
</syntaxhighlight>
</lang>
Which may be used:
Which may be used:
<lang fsharp>
<syntaxhighlight lang=fsharp>
printfn "%.14f" (float (e |> Seq.take 20 |> Seq.sum))
printfn "%.14f" (float (e |> Seq.take 20 |> Seq.sum))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,686: Line 1,686:
=={{header|Factor}}==
=={{header|Factor}}==
{{works with|Factor|0.98}}
{{works with|Factor|0.98}}
<lang factor>USING: math math.factorials prettyprint sequences ;
<syntaxhighlight lang=factor>USING: math math.factorials prettyprint sequences ;
IN: rosetta-code.calculate-e
IN: rosetta-code.calculate-e


CONSTANT: terms 20
CONSTANT: terms 20


terms <iota> [ n! recip ] map-sum >float .</lang>
terms <iota> [ n! recip ] map-sum >float .</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,699: Line 1,699:
=={{header|FOCAL}}==
=={{header|FOCAL}}==
{{trans|ZX Spectrum Basic}}
{{trans|ZX Spectrum Basic}}
<lang focal>1.1 S K=1; S E=0
<syntaxhighlight lang=focal>1.1 S K=1; S E=0
1.2 F X=1,10; D 2
1.2 F X=1,10; D 2
1.3 Q
1.3 Q
Line 1,705: Line 1,705:
2.1 S E=E+1/K
2.1 S E=E+1/K
2.2 S K=K*X
2.2 S K=K*X
2.3 T %2,X,%6.5,E,!</lang>
2.3 T %2,X,%6.5,E,!</syntaxhighlight>
{{output}}
{{output}}
<pre>*G
<pre>*G
Line 1,736: Line 1,736:
* Output the next digit: The final quotient is the next digit of e.
* Output the next digit: The final quotient is the next digit of e.


<lang forth>100 constant #digits
<syntaxhighlight lang=forth>100 constant #digits
: int-array create cells allot does> swap cells + ;
: int-array create cells allot does> swap cells + ;


Line 1,756: Line 1,756:
0 .r
0 .r
LOOP ;
LOOP ;
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,766: Line 1,766:


=={{header|Fortran}}==
=={{header|Fortran}}==
<lang fortran >
<syntaxhighlight lang=fortran >
Program eee
Program eee
implicit none
implicit none
Line 1,782: Line 1,782:
write(*,*) ' polynomial ', ee
write(*,*) ' polynomial ', ee
end Program eee</lang>
end Program eee</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,794: Line 1,794:
=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
===Normal basic===
===Normal basic===
<lang freebasic>' version 02-07-2018
<syntaxhighlight lang=freebasic>' version 02-07-2018
' compile with: fbc -s console
' compile with: fbc -s console


Line 1,815: Line 1,815:
Print : Print "hit any key to end program"
Print : Print "hit any key to end program"
Sleep
Sleep
End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre>The value of e = 2.718281828459046</pre>
<pre>The value of e = 2.718281828459046</pre>
===GMP version===
===GMP version===
{{libheader|GMP}}
{{libheader|GMP}}
<lang freebasic>' version 02-07-2018
<syntaxhighlight lang=freebasic>' version 02-07-2018
' compile with: fbc -s console
' compile with: fbc -s console


Line 1,865: Line 1,865:
Print : Print "hit any key to end program"
Print : Print "hit any key to end program"
Sleep
Sleep
End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre>The value of e = 2.71828182845904523536028747135266249775724709369996</pre>
<pre>The value of e = 2.71828182845904523536028747135266249775724709369996</pre>
Line 1,878: Line 1,878:


=={{header|Furor}}==
=={{header|Furor}}==
<lang Furor>
<syntaxhighlight lang=Furor>
###sysinclude math.uh
###sysinclude math.uh
1.0e-15 sto EPSILON
1.0e-15 sto EPSILON
Line 1,896: Line 1,896:
{ „e0” }
{ „e0” }
{ „n” }
{ „n” }
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,907: Line 1,907:
=={{header|Go}}==
=={{header|Go}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang go>package main
<syntaxhighlight lang=go>package main


import (
import (
Line 1,930: Line 1,930:
}
}
fmt.Printf("e = %.15f\n", e)
fmt.Printf("e = %.15f\n", e)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,942: Line 1,942:


Since the difference between partial sums is always the "last" term, it suffices to ensure that the "last" term is less than the tolerance.
Since the difference between partial sums is always the "last" term, it suffices to ensure that the "last" term is less than the tolerance.
<lang groovy>def ε = 1.0e-15
<syntaxhighlight lang=groovy>def ε = 1.0e-15
def φ = 1/ε
def φ = 1/ε


Line 1,958: Line 1,958:
}
}


def e = generateAddends().sum()</lang>
def e = generateAddends().sum()</syntaxhighlight>
'''Test: '''
'''Test: '''
<lang groovy>printf "%17.15f\n%17.15f\n", e, Math.E</lang>
<syntaxhighlight lang=groovy>printf "%17.15f\n%17.15f\n", e, Math.E</syntaxhighlight>
'''Output: '''
'''Output: '''
<pre>2.718281828459045
<pre>2.718281828459045
Line 1,968: Line 1,968:
For the purposes of 64 bit floating point precision, the value seems to stabilise after summing c. 17-20 terms.
For the purposes of 64 bit floating point precision, the value seems to stabilise after summing c. 17-20 terms.


<lang haskell>------ APPROXIMATION OF E OBTAINED AFTER N ITERATIONS ----
<syntaxhighlight lang=haskell>------ APPROXIMATION OF E OBTAINED AFTER N ITERATIONS ----


eApprox :: Int -> Double
eApprox :: Int -> Double
Line 1,976: Line 1,976:
--------------------------- TEST -------------------------
--------------------------- TEST -------------------------
main :: IO ()
main :: IO ()
main = print $ eApprox 20</lang>
main = print $ eApprox 20</syntaxhighlight>
{{Out}}
{{Out}}
<pre>2.7182818284590455</pre>
<pre>2.7182818284590455</pre>
Line 1,982: Line 1,982:
Or equivalently, in a single fold:
Or equivalently, in a single fold:


<lang haskell>------ APPROXIMATION OF E OBTAINED AFTER N ITERATIONS ----
<syntaxhighlight lang=haskell>------ APPROXIMATION OF E OBTAINED AFTER N ITERATIONS ----


eApprox n =
eApprox n =
Line 1,995: Line 1,995:
--------------------------- TEST -------------------------
--------------------------- TEST -------------------------
main :: IO ()
main :: IO ()
main = print $ eApprox 20</lang>
main = print $ eApprox 20</syntaxhighlight>
{{Out}}
{{Out}}
<pre>2.7182818284590455</pre>
<pre>2.7182818284590455</pre>
Line 2,001: Line 2,001:
Or in terms of iterate:
Or in terms of iterate:


<lang haskell>{-# LANGUAGE TupleSections #-}
<syntaxhighlight lang=haskell>{-# LANGUAGE TupleSections #-}


------------------- APPROXIMATIONS TO E ------------------
------------------- APPROXIMATIONS TO E ------------------
Line 2,016: Line 2,016:
--------------------------- TEST -------------------------
--------------------------- TEST -------------------------
main :: IO ()
main :: IO ()
main = print $ approximatEs !! 17</lang>
main = print $ approximatEs !! 17</syntaxhighlight>
{{Out}}
{{Out}}
<pre>2.7182818284590455</pre>
<pre>2.7182818284590455</pre>
Line 2,026: Line 2,026:
For Icon, the EPSILON preprocessor constant would need to be an inline constant where tested, or set in a variable.
For Icon, the EPSILON preprocessor constant would need to be an inline constant where tested, or set in a variable.


<lang unicon>$define EPSILON 1.0e-15
<syntaxhighlight lang=unicon>$define EPSILON 1.0e-15


procedure main()
procedure main()
Line 2,043: Line 2,043:
write("computed e ", e)
write("computed e ", e)
write("keyword &e ", &e)
write("keyword &e ", &e)
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 2,051: Line 2,051:


=={{header|IS-BASIC}}==
=={{header|IS-BASIC}}==
<lang IS-BASIC>100 PROGRAM "e.bas"
<syntaxhighlight lang=IS-BASIC>100 PROGRAM "e.bas"
110 LET E1=0:LET E,N,N1=1
110 LET E1=0:LET E,N,N1=1
120 DO WHILE E<>E1
120 DO WHILE E<>E1
Line 2,057: Line 2,057:
140 LET N1=N1+1:LET N=N*N1
140 LET N1=N1+1:LET N=N*N1
150 LOOP
150 LOOP
160 PRINT "The value of e =";E</lang>
160 PRINT "The value of e =";E</syntaxhighlight>
{{Out}}
{{Out}}
<pre>The value of e = 2.71828183</pre>
<pre>The value of e = 2.71828183</pre>
Line 2,138: Line 2,138:
=={{header|Java}}==
=={{header|Java}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang java>public class CalculateE {
<syntaxhighlight lang=java>public class CalculateE {
public static final double EPSILON = 1.0e-15;
public static final double EPSILON = 1.0e-15;


Line 2,153: Line 2,153:
System.out.printf("e = %.15f\n", e);
System.out.printf("e = %.15f\n", e);
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>e = 2.718281828459046</pre>
<pre>e = 2.718281828459046</pre>
Line 2,159: Line 2,159:
=={{header|Javascript}}==
=={{header|Javascript}}==
Summing over a scan
Summing over a scan
<lang javascript>(() => {
<syntaxhighlight lang=javascript>(() => {
"use strict";
"use strict";


Line 2,213: Line 2,213:
// MAIN ---
// MAIN ---
return main();
return main();
})();</lang>
})();</syntaxhighlight>
<pre>2.7182818284590455</pre>
<pre>2.7182818284590455</pre>


Or as a single fold/reduce:
Or as a single fold/reduce:
<lang javascript>(() => {
<syntaxhighlight lang=javascript>(() => {
"use strict";
"use strict";


Line 2,248: Line 2,248:
// MAIN ---
// MAIN ---
return main();
return main();
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<pre>2.7182818284590455</pre>
<pre>2.7182818284590455</pre>


=={{header|jq}}==
=={{header|jq}}==
<lang>1|exp #=> 2.718281828459045</lang>
<syntaxhighlight lang=text>1|exp #=> 2.718281828459045</syntaxhighlight>
<lang>def e:
<syntaxhighlight lang=text>def e:
[null,0,1,1]
[null,0,1,1]
| until(.[0] == .[1]; .[0]=.[1] | .[1]+=1/.[2] | .[2] *= .[3] | .[3]+=1)
| until(.[0] == .[1]; .[0]=.[1] | .[1]+=1/.[2] | .[2] *= .[3] | .[3]+=1)
| .[0];
| .[0];
e #=> 2.7182818284590455</lang>
e #=> 2.7182818284590455</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
Line 2,264: Line 2,264:


'''Module''':
'''Module''':
<lang julia>module NeperConstant
<syntaxhighlight lang=julia>module NeperConstant


export NeperConst
export NeperConst
Line 2,288: Line 2,288:
end
end


end # module NeperConstant</lang>
end # module NeperConstant</syntaxhighlight>


'''Main''':
'''Main''':
<lang julia>for F in (Float16, Float32, Float64, BigFloat)
<syntaxhighlight lang=julia>for F in (Float16, Float32, Float64, BigFloat)
println(NeperConst{F}())
println(NeperConst{F}())
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 2,302: Line 2,302:


=={{header|K}}==
=={{header|K}}==
<syntaxhighlight lang=K>
<lang K>
/ Computing value of e
/ Computing value of e
/ ecomp.k
/ ecomp.k
Line 2,309: Line 2,309:
evalue:{1 +/(1.0%)'fact' 1+!20}
evalue:{1 +/(1.0%)'fact' 1+!20}
evalue[]
evalue[]
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,318: Line 2,318:


=={{header|Klingphix}}==
=={{header|Klingphix}}==
<lang>%e0 %e %n %fact %v
<syntaxhighlight lang=text>%e0 %e %n %fact %v


0 !e0 2 !e 0 !n 1 !fact
0 !e0 2 !e 0 !n 1 !fact
Line 2,341: Line 2,341:
"Number of iterations = " $n printOp
"Number of iterations = " $n printOp


" " input</lang>
" " input</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// Version 1.2.40
<syntaxhighlight lang=scala>// Version 1.2.40


import kotlin.math.abs
import kotlin.math.abs
Line 2,361: Line 2,361:
while (abs(e - e0) >= EPSILON)
while (abs(e - e0) >= EPSILON)
println("e = %.15f".format(e))
println("e = %.15f".format(e))
}</lang>
}</syntaxhighlight>


{{output}}
{{output}}
Line 2,369: Line 2,369:


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<lang scheme>
<syntaxhighlight lang=scheme>
1) straightforward
1) straightforward


Line 2,395: Line 2,395:
{euler 1 17}
{euler 1 17}
-> 2.7182818284590455
-> 2.7182818284590455
</syntaxhighlight>
</lang>


=={{header|langur}}==
=={{header|langur}}==
{{trans|Go}}
{{trans|Go}}
<lang langur>mode divMaxScale = 104
<syntaxhighlight lang=langur>mode divMaxScale = 104


val .epsilon = 1.0e-104
val .epsilon = 1.0e-104
Line 2,415: Line 2,415:


# compare to built-in constant e
# compare to built-in constant e
writeln " e = ", e</lang>
writeln " e = ", e</syntaxhighlight>


{{out}}
{{out}}
Line 2,425: Line 2,425:


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>EPSILON = 1.0e-15;
<syntaxhighlight lang=lua>EPSILON = 1.0e-15;


fact = 1
fact = 1
Line 2,439: Line 2,439:
until (math.abs(e - e0) < EPSILON)
until (math.abs(e - e0) < EPSILON)


io.write(string.format("e = %.15f\n", e))</lang>
io.write(string.format("e = %.15f\n", e))</syntaxhighlight>
{{out}}
{{out}}
<pre>e = 2.718281828459046</pre>
<pre>e = 2.718281828459046</pre>
Line 2,446: Line 2,446:
Using @ for Decimal, and ~ for Float, # for Currency (Double is the default type for M2000)
Using @ for Decimal, and ~ for Float, # for Currency (Double is the default type for M2000)


<lang M2000 Interpreter>
<syntaxhighlight lang=M2000 Interpreter>
Module FindE {
Module FindE {
Function comp_e (n){
Function comp_e (n){
Line 2,464: Line 2,464:
}
}
FindE
FindE
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,475: Line 2,475:


As a lambda function (also we use a faster For, using block {})
As a lambda function (also we use a faster For, using block {})
<lang M2000 Interpreter>
<syntaxhighlight lang=M2000 Interpreter>
comp_e=lambda (n)->{n/=28:For i=27to 1 {n=1+n/i}:=n}
comp_e=lambda (n)->{n/=28:For i=27to 1 {n=1+n/i}:=n}
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==


<lang maple>evalf[50](add(1/n!,n=0..100));
<syntaxhighlight lang=maple>evalf[50](add(1/n!,n=0..100));
# 2.7182818284590452353602874713526624977572470937000
# 2.7182818284590452353602874713526624977572470937000


evalf[50](exp(1));
evalf[50](exp(1));
# 2.7182818284590452353602874713526624977572470937000</lang>
# 2.7182818284590452353602874713526624977572470937000</syntaxhighlight>


With [https://en.wikipedia.org/wiki/Continued_fraction continued fractions]:
With [https://en.wikipedia.org/wiki/Continued_fraction continued fractions]:


<lang maple>with(NumberTheory):
<syntaxhighlight lang=maple>with(NumberTheory):
e:=ContinuedFraction(exp(1)):
e:=ContinuedFraction(exp(1)):
Convergent(e,100);
Convergent(e,100);
Line 2,495: Line 2,495:


# 13823891428306770374331665289458907890372191037173036666131/5085525453460186301777867529962655859538011626631066055111
# 13823891428306770374331665289458907890372191037173036666131/5085525453460186301777867529962655859538011626631066055111
# 2.7182818284590452353602874713526624977572470937000</lang>
# 2.7182818284590452353602874713526624977572470937000</syntaxhighlight>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>1+Fold[1.+#1/#2&,1,Range[10,2,-1]]</lang>
<syntaxhighlight lang=Mathematica>1+Fold[1.+#1/#2&,1,Range[10,2,-1]]</syntaxhighlight>
{{output}}
{{output}}
<pre>
<pre>
Line 2,504: Line 2,504:
</pre>
</pre>


<lang Mathematica>Sum[1/x!, {x, 0, ∞}]</lang>
<syntaxhighlight lang=Mathematica>Sum[1/x!, {x, 0, ∞}]</syntaxhighlight>
<lang Mathematica>Limit[(1+1/x)^x,x->∞]</lang>
<syntaxhighlight lang=Mathematica>Limit[(1+1/x)^x,x->∞]</syntaxhighlight>
<lang Mathematica>Exp[1]</lang>
<syntaxhighlight lang=Mathematica>Exp[1]</syntaxhighlight>
or even just
or even just
<lang Mathematica>𝕖</lang>
<syntaxhighlight lang=Mathematica>𝕖</syntaxhighlight>
input as <lang Mathematica>≡ee≡</lang>
input as <syntaxhighlight lang=Mathematica>≡ee≡</syntaxhighlight>
{{output}}
{{output}}
<pre>𝕖</pre>
<pre>𝕖</pre>
Line 2,515: Line 2,515:
=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.3}}
{{works with|min|0.19.3}}
<lang min>(:n (n 0 ==) ((0)) (-1 () ((succ dup) dip append) n times) if) :iota
<syntaxhighlight lang=min>(:n (n 0 ==) ((0)) (-1 () ((succ dup) dip append) n times) if) :iota
(iota 'succ '* map-reduce) :factorial
(iota 'succ '* map-reduce) :factorial


20 iota (factorial 1 swap /) '+ map-reduce print</lang>
20 iota (factorial 1 swap /) '+ map-reduce print</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,525: Line 2,525:


=={{header|МК-61/52}}==
=={{header|МК-61/52}}==
<lang mk-61>П0 П1 0 П2 1 П2 1 П3
<syntaxhighlight lang=mk-61>П0 П1 0 П2 1 П2 1 П3
ИП3 ИП2 ИП1 ИП0 - 1 + * П2 1/x + П3
ИП3 ИП2 ИП1 ИП0 - 1 + * П2 1/x + П3
ИП0 x#0 25 L0 08 ИП3 С/П</lang>
ИП0 x#0 25 L0 08 ИП3 С/П</syntaxhighlight>


At n = 10, the value is 2.7182819.
At n = 10, the value is 2.7182819.


=={{header|Modula-2}}==
=={{header|Modula-2}}==
<lang modula2>MODULE CalculateE;
<syntaxhighlight lang=modula2>MODULE CalculateE;
FROM RealStr IMPORT RealToStr;
FROM RealStr IMPORT RealToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 2,568: Line 2,568:


ReadChar
ReadChar
END CalculateE.</lang>
END CalculateE.</syntaxhighlight>


=={{header|Myrddin}}==
=={{header|Myrddin}}==
<lang Myrrdin>use std
<syntaxhighlight lang=Myrrdin>use std


const main = {
const main = {
Line 2,586: Line 2,586:
;;
;;
std.put("e: {}\n", e)
std.put("e: {}\n", e)
}</lang>
}</syntaxhighlight>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
{{trans|Python}}
{{trans|Python}}
<lang Nanoquery>e0 = 0
<syntaxhighlight lang=Nanoquery>e0 = 0
e = 2
e = 2
n = 0
n = 0
Line 2,602: Line 2,602:


println "Computed e = " + e
println "Computed e = " + e
println "Number of iterations = " + n</lang>
println "Number of iterations = " + n</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,610: Line 2,610:


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>const epsilon : float64 = 1.0e-15
<syntaxhighlight lang=nim>const epsilon : float64 = 1.0e-15
var fact : int64 = 1
var fact : int64 = 1
var e : float64 = 2.0
var e : float64 = 2.0
Line 2,622: Line 2,622:
e = e + 1.0 / fact.float64
e = e + 1.0 / fact.float64


echo e</lang>
echo e</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
Like delphi and many other.Slightly modified to calculate (1/n!) not n! and then divide to (1/n!)
Like delphi and many other.Slightly modified to calculate (1/n!) not n! and then divide to (1/n!)
<lang pascal>program Calculating_the_value_of_e;
<syntaxhighlight lang=pascal>program Calculating_the_value_of_e;
{$IFDEF FPC}
{$IFDEF FPC}
{$MODE DELPHI}
{$MODE DELPHI}
Line 2,659: Line 2,659:
{$IFDEF WINDOWS}readln;{$ENDIF}
{$IFDEF WINDOWS}readln;{$ENDIF}
end.
end.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>calc e = 2.718281828459045 intern e= 2.718281828459045</pre>
<pre>calc e = 2.718281828459045 intern e= 2.718281828459045</pre>
Line 2,665: Line 2,665:
=={{header|Perl}}==
=={{header|Perl}}==
With the <code>bignum</code> core module in force, Brother's algorithm requires only 18 iterations to match the precision of the built-in value, <code>e</code>.
With the <code>bignum</code> core module in force, Brother's algorithm requires only 18 iterations to match the precision of the built-in value, <code>e</code>.
<lang perl>use bignum qw(e);
<syntaxhighlight lang=perl>use bignum qw(e);


$e = 2;
$e = 2;
Line 2,677: Line 2,677:


print "Computed " . substr($e, 0, 41), "\n";
print "Computed " . substr($e, 0, 41), "\n";
print "Built-in " . e, "\n";</lang>
print "Built-in " . e, "\n";</syntaxhighlight>
{{out}}
{{out}}
<pre>Computed 2.718281828459045235360287471352662497757
<pre>Computed 2.718281828459045235360287471352662497757
Line 2,686: Line 2,686:
Here, 71 terms of the Taylor series yield 𝑒 to 101 digits.
Here, 71 terms of the Taylor series yield 𝑒 to 101 digits.


<lang perl>use bigrat;
<syntaxhighlight lang=perl>use bigrat;
use Math::Decimal qw(dec_canonise dec_mul dec_rndiv_and_rem);
use Math::Decimal qw(dec_canonise dec_mul dec_rndiv_and_rem);


Line 2,711: Line 2,711:
}
}


printf "\n%s\n", subset $e, 0,102;</lang>
printf "\n%s\n", subset $e, 0,102;</syntaxhighlight>
{{out}}
{{out}}
<pre>numerator: 32561133701373476427912330475884581607687531065877567210421813247164172713574202714721554378508046501
<pre>numerator: 32561133701373476427912330475884581607687531065877567210421813247164172713574202714721554378508046501
Line 2,720: Line 2,720:
=={{header|Phix}}==
=={{header|Phix}}==
{{trans|Python}}
{{trans|Python}}
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang=Phix>(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1.0.2"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (builtin constant E renamed as EULER)</span>
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1.0.2"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (builtin constant E renamed as EULER)</span>
Line 2,734: Line 2,734:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" Error = %g\n"</span><span style="color: #0000FF;">,</span><span style="color: #004600;">EULER</span><span style="color: #0000FF;">-</span><span style="color: #000000;">e</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" Error = %g\n"</span><span style="color: #0000FF;">,</span><span style="color: #004600;">EULER</span><span style="color: #0000FF;">-</span><span style="color: #000000;">e</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Number of iterations = %d\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Number of iterations = %d\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,745: Line 2,745:
=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
{{trans|Python}}
{{trans|Python}}
<lang Phixmonti>0 var e0 2 var e 0 var n 1 var fact
<syntaxhighlight lang=Phixmonti>0 var e0 2 var e 0 var n 1 var fact
1e-15 var v
1e-15 var v


Line 2,768: Line 2,768:
"Real e = " rE tostr printOp
"Real e = " rE tostr printOp
"Error = " rE e - printOp
"Error = " rE e - printOp
"Number of iterations = " n printOp</lang>
"Number of iterations = " n printOp</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,778: Line 2,778:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(scl 15)
<syntaxhighlight lang=PicoLisp>(scl 15)
(let (F 1 E 2.0 E0 0 N 2)
(let (F 1 E 2.0 E0 0 N 2)
(while (> E E0)
(while (> E E0)
Line 2,784: Line 2,784:
(inc 'E (*/ 1.0 F))
(inc 'E (*/ 1.0 F))
(inc 'N) )
(inc 'N) )
(prinl "e = " (format E *Scl)) )</lang>
(prinl "e = " (format E *Scl)) )</syntaxhighlight>
{{out}}
{{out}}
<pre>e = 2.718281828459046</pre>
<pre>e = 2.718281828459046</pre>
Line 2,790: Line 2,790:
=={{header|PowerShell}}==
=={{header|PowerShell}}==
{{trans|Python}}
{{trans|Python}}
<lang powershell>$e0 = 0
<syntaxhighlight lang=powershell>$e0 = 0
$e = 2
$e = 2
$n = 0
$n = 0
Line 2,804: Line 2,804:
Write-Host " Real e = $([Math]::Exp(1))"
Write-Host " Real e = $([Math]::Exp(1))"
Write-Host " Error = $([Math]::Exp(1) - $e)"
Write-Host " Error = $([Math]::Exp(1) - $e)"
Write-Host "Number of iterations = $n"</lang>
Write-Host "Number of iterations = $n"</syntaxhighlight>
{{out}}
{{out}}
<pre>Computed e = 2.71828182845904
<pre>Computed e = 2.71828182845904
Line 2,813: Line 2,813:
=={{header|Processing}}==
=={{header|Processing}}==
Updated to show that computed value matches library value after 21 iterations.
Updated to show that computed value matches library value after 21 iterations.
<lang java>
<syntaxhighlight lang=java>
void setup() {
void setup() {
double e = 0;
double e = 0;
Line 2,838: Line 2,838:
}
}


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,854: Line 2,854:
===Floating-point solution===
===Floating-point solution===
Uses Newton's method to solve ln x = 1
Uses Newton's method to solve ln x = 1
<lang prolog>
<syntaxhighlight lang=prolog>
% Calculate the value e = exp 1
% Calculate the value e = exp 1
% Use Newton's method: x0 = 2; y = x(2 - ln x)
% Use Newton's method: x0 = 2; y = x(2 - ln x)
Line 2,876: Line 2,876:


?- main.
?- main.
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 2,884: Line 2,884:


===Arbitrary-precision solution===
===Arbitrary-precision solution===
<lang prolog>
<syntaxhighlight lang=prolog>
% John Devou: 26-Nov-2021
% John Devou: 26-Nov-2021
% Simple program to calculate e up to n decimal digits.
% Simple program to calculate e up to n decimal digits.
Line 2,906: Line 2,906:


?- main.
?- main.
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 2,922: Line 2,922:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>Define f.d=1.0, e.d=1.0, e0.d=e, n.i=1
<syntaxhighlight lang=PureBasic>Define f.d=1.0, e.d=1.0, e0.d=e, n.i=1
LOOP:
LOOP:
f*n : e+1.0/f
f*n : e+1.0/f
If e-e0>=1.0e-15 : e0=e : n+1 : Goto LOOP : EndIf
If e-e0>=1.0e-15 : e0=e : n+1 : Goto LOOP : EndIf
Debug "e="+StrD(e,15)</lang>
Debug "e="+StrD(e,15)</syntaxhighlight>
{{out}}
{{out}}
<pre>e=2.718281828459046</pre>
<pre>e=2.718281828459046</pre>
Line 2,932: Line 2,932:
=={{header|Python}}==
=={{header|Python}}==
===Imperative===
===Imperative===
<lang python>import math
<syntaxhighlight lang=python>import math
#Implementation of Brother's formula
#Implementation of Brother's formula
e0 = 0
e0 = 0
Line 2,947: Line 2,947:
print "Real e = "+str(math.e)
print "Real e = "+str(math.e)
print "Error = "+str(math.e-e)
print "Error = "+str(math.e-e)
print "Number of iterations = "+str(n)</lang>
print "Number of iterations = "+str(n)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,960: Line 2,960:


{{Works with|Python|3.7}}
{{Works with|Python|3.7}}
<lang python>'''Calculating an approximate value for e'''
<syntaxhighlight lang=python>'''Calculating an approximate value for e'''


from itertools import (accumulate, chain)
from itertools import (accumulate, chain)
Line 3,007: Line 3,007:
# MAIN ---
# MAIN ---
if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>2.7182818284590455</pre>
<pre>2.7182818284590455</pre>


Or in terms of a single fold/reduce:
Or in terms of a single fold/reduce:
<lang python>'''Approximation of E'''
<syntaxhighlight lang=python>'''Approximation of E'''


from functools import reduce
from functools import reduce
Line 3,043: Line 3,043:
# MAIN ---
# MAIN ---
if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>2.7182818284590455</pre>
<pre>2.7182818284590455</pre>


=={{header|R}}==
=={{header|R}}==
<syntaxhighlight lang=R>
<lang R>
options(digits=22)
options(digits=22)
cat("e =",sum(rep(1,20)/factorial(0:19)))
cat("e =",sum(rep(1,20)/factorial(0:19)))
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 3,062: Line 3,062:
Using the Quackery bignum rational arithmetic library.
Using the Quackery bignum rational arithmetic library.


<lang Quackery> $ "bigrat.qky" loadfile
<syntaxhighlight lang=Quackery> $ "bigrat.qky" loadfile


[ swap number$
[ swap number$
Line 3,086: Line 3,086:
3 times drop temp release ] is approximate-e ( n n --> )
3 times drop temp release ] is approximate-e ( n n --> )


55 70 approximate-e</lang>
55 70 approximate-e</syntaxhighlight>


{{Out}}
{{Out}}
Line 3,151: Line 3,151:


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>#lang racket
<syntaxhighlight lang=racket>#lang racket
(require math/number-theory)
(require math/number-theory)


Line 3,161: Line 3,161:
(displayln e)
(displayln e)
(displayln (real->decimal-string e 20))
(displayln (real->decimal-string e 20))
(displayln (real->decimal-string (- (exp 1) e) 20))))</lang>
(displayln (real->decimal-string (- (exp 1) e) 20))))</syntaxhighlight>
{{out}}
{{out}}
<pre>82666416490601/30411275102208
<pre>82666416490601/30411275102208
Line 3,170: Line 3,170:
(formerly Perl 6)
(formerly Perl 6)
{{works with|Rakudo|2018.03}}
{{works with|Rakudo|2018.03}}
<lang perl6># If you need high precision: Sum of a Taylor series method.
<syntaxhighlight lang=raku line># If you need high precision: Sum of a Taylor series method.
# Adjust the terms parameter to suit. Theoretically the
# Adjust the terms parameter to suit. Theoretically the
# terms could be ∞. Practically, calculating an infinite
# terms could be ∞. Practically, calculating an infinite
Line 3,183: Line 3,183:


# Or, if you don't need high precision, it's a built-in.
# Or, if you don't need high precision, it's a built-in.
say e;</lang>
say e;</syntaxhighlight>
{{out}}
{{out}}
<pre>2.718281828459045235360287471352662497757247093699959574966967627724076630353547
<pre>2.718281828459045235360287471352662497757247093699959574966967627724076630353547
Line 3,217: Line 3,217:
If the argument (digs) is negative, a running number of decimal digits of &nbsp; <big>''e''</big> &nbsp; is
If the argument (digs) is negative, a running number of decimal digits of &nbsp; <big>''e''</big> &nbsp; is
shown.
shown.
<lang rexx>/*REXX pgm calculates e to a # of decimal digits. If digs<0, a running value is shown.*/
<syntaxhighlight lang=rexx>/*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*/
parse arg digs . /*get optional number of decimal digits*/
if digs=='' | digs=="," then digs= 101 /*Not specified? Then use the default.*/
if digs=='' | digs=="," then digs= 101 /*Not specified? Then use the default.*/
Line 3,231: Line 3,231:
end /*#*/ /* -1 is for the decimal point────┘ */
end /*#*/ /* -1 is for the decimal point────┘ */
say /*stick a fork in it, we're all done. */
say /*stick a fork in it, we're all done. */
say '(with' abs(digs) "decimal digits) the value of e is:"; say e</lang>
say '(with' abs(digs) "decimal digits) the value of e is:"; say e</syntaxhighlight>
Programming note: &nbsp; the factorial of the &nbsp; '''do''' &nbsp; loop index is calculated by &nbsp; ''division'', &nbsp; not by the usual &nbsp; ''multiplication'' &nbsp; (for optimization).
Programming note: &nbsp; the factorial of the &nbsp; '''do''' &nbsp; loop index is calculated by &nbsp; ''division'', &nbsp; not by the usual &nbsp; ''multiplication'' &nbsp; (for optimization).


Line 3,321: Line 3,321:
===version 2===
===version 2===
Using the series shown in version 1 compute e to the specified precision.
Using the series shown in version 1 compute e to the specified precision.
<lang rexx>/*REXX pgm calculates e to nn of decimal digits */
<syntaxhighlight lang=rexx>/*REXX pgm calculates e to nn of decimal digits */
Parse Arg dig /* the desired precision */
Parse Arg dig /* the desired precision */
Numeric Digits (dig+3) /* increase precision */
Numeric Digits (dig+3) /* increase precision */
Line 3,336: Line 3,336:
Numeric Digits dig /* the desired precision */
Numeric Digits dig /* the desired precision */
e=e/1 /* the desired approximation */
e=e/1 /* the desired approximation */
Return left(e,dig+1) '('n 'iterations required)'</lang>
Return left(e,dig+1) '('n 'iterations required)'</syntaxhighlight>
{{out}}
{{out}}
<pre>J:\>rexx eval compey(66)
<pre>J:\>rexx eval compey(66)
compey(66)=2.71828182845904523536028747135266249775724709369995957496696762772 (52 iterations required)</pre>
compey(66)=2.71828182845904523536028747135266249775724709369995957496696762772 (52 iterations required)</pre>
Check the function's correctness
Check the function's correctness
<lang rexx> /*REXX check the correctness of compey */
<syntaxhighlight lang=rexx> /*REXX check the correctness of compey */
e_='2.7182818284590452353602874713526624977572470936999595749669676277240'||,
e_='2.7182818284590452353602874713526624977572470936999595749669676277240'||,
'766303535475945713821785251664274274663919320030599218174135966290435'||,
'766303535475945713821785251664274274663919320030599218174135966290435'||,
Line 3,356: Line 3,356:
Else ok=ok+1
Else ok=ok+1
End
End
Say ok 'comparisons are ok' </lang>
Say ok 'comparisons are ok' </syntaxhighlight>
{{out}}
{{out}}
<pre>J:\>rexx compez
<pre>J:\>rexx compez
Line 3,362: Line 3,362:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang=ring>
# Project : Calculating the value of e
# Project : Calculating the value of e


Line 3,386: Line 3,386:
return n * factorial(n-1)
return n * factorial(n-1)
ok
ok
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 3,397: Line 3,397:
=={{header|Ruby}}==
=={{header|Ruby}}==
{{trans|C}}
{{trans|C}}
<lang ruby>
<syntaxhighlight lang=ruby>
fact = 1
fact = 1
e = 2
e = 2
Line 3,411: Line 3,411:


puts e
puts e
</syntaxhighlight>
</lang>
Built in:
Built in:
<lang ruby>require "bigdecimal/math"
<syntaxhighlight lang=ruby>require "bigdecimal/math"


puts BigMath.E(50).to_s # 50 decimals
puts BigMath.E(50).to_s # 50 decimals
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,423: Line 3,423:


=={{header|Rust}}==
=={{header|Rust}}==
<lang Rust>const EPSILON: f64 = 1e-15;
<syntaxhighlight lang=Rust>const EPSILON: f64 = 1e-15;


fn main() {
fn main() {
Line 3,439: Line 3,439:
}
}
println!("e = {:.15}", e);
println!("e = {:.15}", e);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>e = 2.718281828459046</pre>
<pre>e = 2.718281828459046</pre>
Line 3,445: Line 3,445:
=={{header|Scala}}==
=={{header|Scala}}==
{{Out}}Best seen running in your browser either by [https://scalafiddle.io/sf/gLmNcH2/0 ScalaFiddle (ES aka JavaScript, non JVM)] or [https://scastie.scala-lang.org/WSvNG9xMT5GcugVTvqogVg Scastie (remote JVM)].
{{Out}}Best seen running in your browser either by [https://scalafiddle.io/sf/gLmNcH2/0 ScalaFiddle (ES aka JavaScript, non JVM)] or [https://scastie.scala-lang.org/WSvNG9xMT5GcugVTvqogVg Scastie (remote JVM)].
<lang Scala>import scala.annotation.tailrec
<syntaxhighlight lang=Scala>import scala.annotation.tailrec


object CalculateE extends App {
object CalculateE extends App {
Line 3,459: Line 3,459:


println(f"ℯ = ${iter(1L, 2.0, 2, 0)}%.15f")
println(f"ℯ = ${iter(1L, 2.0, 2, 0)}%.15f")
}</lang>
}</syntaxhighlight>
=={{header|Scheme}}==
=={{header|Scheme}}==
{{trans|JavaScript}}
{{trans|JavaScript}}
<lang Scheme>
<syntaxhighlight lang=Scheme>
(import (rnrs))
(import (rnrs))


Line 3,500: Line 3,500:


(display (e))
(display (e))
(newline)</lang>
(newline)</syntaxhighlight>
===High Precision===
===High Precision===
{{works with|Chez Scheme}}
{{works with|Chez Scheme}}
Line 3,508: Line 3,508:
exactness of the calculation. So, calling exp with the integer 1 will return an exact rational
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.
value, allowing for higher precision than floating point would.
<lang scheme>; Use series to compute approximation to exp(z) (using N terms of series).
<syntaxhighlight lang=scheme>; Use series to compute approximation to exp(z) (using N terms of series).
; n-1
; n-1
; exp(z) ~ SUM ( z^k / k! )
; exp(z) ~ SUM ( z^k / k! )
Line 3,525: Line 3,525:
(if (<= n 0)
(if (<= n 0)
1
1
(* n (fact (1- n))))))</lang>
(* n (fact (1- n))))))</syntaxhighlight>
'''Convert for Display'''
'''Convert for Display'''
<lang scheme>; Convert the given Rational number to a Decimal string.
<syntaxhighlight lang=scheme>; 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 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 'nopar, do not insert the parentheses indicating the repeating places.
Line 3,568: Line 3,568:
(if (null? frc-list)
(if (null? frc-list)
int-part
int-part
(format "~a.~a" int-part (list->string frc-list))))))</lang>
(format "~a.~a" int-part (list->string frc-list))))))</syntaxhighlight>
'''The Task'''
'''The Task'''
<lang scheme>; Use the series approximation to exp(z) to compute e (= exp(1)) to 100 places.
<syntaxhighlight lang=scheme>; Use the series approximation to exp(z) to compute e (= exp(1)) to 100 places.


(let*
(let*
Line 3,581: Line 3,581:
(printf "the computed exact rational:~%~a~%" e)
(printf "the computed exact rational:~%~a~%" e)
(printf "converted to decimal (~a places):~%~a~%" p (rat->dec-str e p))
(printf "converted to decimal (~a places):~%~a~%" p (rat->dec-str e p))
(printf "converted to an inexact (float):~%~a~%" (exact->inexact e)))</lang>
(printf "converted to an inexact (float):~%~a~%" (exact->inexact e)))</syntaxhighlight>
{{out}}
{{out}}
<pre>Computing exp(1) using 75 terms...
<pre>Computing exp(1) using 75 terms...
Line 3,596: Line 3,596:
The program below computes e:
The program below computes e:


<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang=seed7>$ include "seed7_05.s7i";
include "float.s7i";
include "float.s7i";


Line 3,615: Line 3,615:
until abs(e - e0) < EPSILON;
until abs(e - e0) < EPSILON;
writeln("e = " <& e digits 15);
writeln("e = " <& e digits 15);
end func;</lang>
end func;</syntaxhighlight>


{{out}}
{{out}}
Line 3,624: Line 3,624:
=={{header|Sidef}}==
=={{header|Sidef}}==


<lang ruby>func calculate_e(n=50) {
<syntaxhighlight lang=ruby>func calculate_e(n=50) {
sum(0..n, {|k| 1/k! })
sum(0..n, {|k| 1/k! })
}
}


say calculate_e()
say calculate_e()
say calculate_e(69).as_dec(100)</lang>
say calculate_e(69).as_dec(100)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,638: Line 3,638:
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:
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:


<lang ruby>func f(n) {
<syntaxhighlight lang=ruby>func f(n) {
var t = n*log(10)
var t = n*log(10)
(n + 10).bsearch_le { |k|
(n + 10).bsearch_le { |k|
Line 3,648: Line 3,648:
var n = f(10**k)
var n = f(10**k)
say "Sum_{k=0..#{n}} 1/k! = e correct to #{10**k->commify} decimal places"
say "Sum_{k=0..#{n}} 1/k! = e correct to #{10**k->commify} decimal places"
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,664: Line 3,664:


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>fun calcEToEps() =
<syntaxhighlight lang=sml>fun calcEToEps() =
let
let
val eps = 1.0e~15
val eps = 1.0e~15
Line 3,679: Line 3,679:
in
in
calcToEps'(2.0, 1.0, 1.0, 2.0)
calcToEps'(2.0, 1.0, 1.0, 2.0)
end;</lang>
end;</syntaxhighlight>


{{out}}
{{out}}
Line 3,693: Line 3,693:
{{trans|C}}
{{trans|C}}


<lang swift>import Foundation
<syntaxhighlight lang=swift>import Foundation




Line 3,711: Line 3,711:
}
}


print(String(format: "e = %.15f\n", arguments: [calculateE()]))</lang>
print(String(format: "e = %.15f\n", arguments: [calculateE()]))</syntaxhighlight>


{{out}}
{{out}}
Line 3,719: Line 3,719:
=={{header|Tcl}}==
=={{header|Tcl}}==
=== By the power series of exp(x) ===
=== By the power series of exp(x) ===
<lang tcl>
<syntaxhighlight lang=tcl>
set ε 1.0e-15
set ε 1.0e-15
set fact 1
set fact 1
Line 3,732: Line 3,732:
set e [expr $e + 1.0/$fact]
set e [expr $e + 1.0/$fact]
}
}
puts "e = $e"</lang>
puts "e = $e"</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 3,739: Line 3,739:
=== By the continued fraction for e ===
=== 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.
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.
<lang tcl>
<syntaxhighlight lang=tcl>
## We use (regular) continued fractions, step by step.
## 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 partial CF is coded (a n b m) for (a+nr) / (b+mr) for rest r.
Line 3,788: Line 3,788:


calcE 17
calcE 17
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,797: Line 3,797:
=={{header|TI-83 BASIC}}==
=={{header|TI-83 BASIC}}==
Guided by the Awk version.
Guided by the Awk version.
<lang ti83b>0->D
<syntaxhighlight lang=ti83b>0->D
2->N
2->N
2->E
2->E
Line 3,809: Line 3,809:
End
End
Disp E
Disp E
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>2.718281828</pre>
<pre>2.718281828</pre>
Line 3,815: Line 3,815:
=={{header|VBScript}}==
=={{header|VBScript}}==
{{Trans|Python}}
{{Trans|Python}}
<lang vb>e0 = 0 : e = 2 : n = 0 : fact = 1
<syntaxhighlight lang=vb>e0 = 0 : e = 2 : n = 0 : fact = 1
While (e - e0) > 1E-15
While (e - e0) > 1E-15
e0 = e
e0 = e
Line 3,826: Line 3,826:
WScript.Echo "Real e = " & Exp(1)
WScript.Echo "Real e = " & Exp(1)
WScript.Echo "Error = " & (Exp(1) - e)
WScript.Echo "Error = " & (Exp(1) - e)
WScript.Echo "Number of iterations = " & n</lang>
WScript.Echo "Number of iterations = " & n</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Computed e = 2.71828182845904
<pre>Computed e = 2.71828182845904
Line 3,834: Line 3,834:


=={{header|Verilog}}==
=={{header|Verilog}}==
<lang Verilog>module main;
<syntaxhighlight lang=Verilog>module main;
real n, n1;
real n, n1;
real e1, e;
real e1, e;
Line 3,853: Line 3,853:
$finish ;
$finish ;
end
end
endmodule</lang>
endmodule</syntaxhighlight>
{{out}}
{{out}}
<pre>The value of e = 2.71828</pre>
<pre>The value of e = 2.71828</pre>
Line 3,860: Line 3,860:
{{trans|C#}}
{{trans|C#}}
{{libheader|System.Numerics}}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.
{{libheader|System.Numerics}}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.
<lang vbnet>Imports System, System.Numerics, System.Math, System.Console
<syntaxhighlight lang=vbnet>Imports System, System.Numerics, System.Math, System.Console


Module Program
Module Program
Line 3,878: Line 3,878:
WriteLine("partial: {0}...{1}", es.Substring(0, 46), es.Substring(es.Length - 45))
WriteLine("partial: {0}...{1}", es.Substring(0, 46), es.Substring(es.Length - 45))
End Sub
End Sub
End Module</lang>
End Module</syntaxhighlight>
{{out}}
{{out}}
<pre>2.71828182845905
<pre>2.71828182845905
Line 3,887: Line 3,887:
=={{header|Vlang}}==
=={{header|Vlang}}==
{{trans|Go}}
{{trans|Go}}
<lang vlang>import math
<syntaxhighlight lang=vlang>import math
const epsilon = 1.0e-15
const epsilon = 1.0e-15
Line 3,904: Line 3,904:
}
}
println("e = ${e:.15f}")
println("e = ${e:.15f}")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,913: Line 3,913:
=={{header|Wren}}==
=={{header|Wren}}==
{{trans|Go}}
{{trans|Go}}
<lang ecmascript>var epsilon = 1e-15
<syntaxhighlight lang=ecmascript>var epsilon = 1e-15
var fact = 1
var fact = 1
var e = 2
var e = 2
Line 3,924: Line 3,924:
if ((e - e0).abs < epsilon) break
if ((e - e0).abs < epsilon) break
}
}
System.print("e = %(e)")</lang>
System.print("e = %(e)")</syntaxhighlight>


{{out}}
{{out}}
Line 3,932: Line 3,932:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>real N, E, E0, F; \index, Euler numbers, factorial
<syntaxhighlight lang=XPL0>real N, E, E0, F; \index, Euler numbers, factorial
[Format(1, 16); \show 16 places after decimal point
[Format(1, 16); \show 16 places after decimal point
N:= 1.0; E:= 1.0; F:= 1.0;
N:= 1.0; E:= 1.0; F:= 1.0;
Line 3,943: Line 3,943:
RlOut(0, E); CrLf(0);
RlOut(0, E); CrLf(0);
IntOut(0, fix(N)); Text(0, " iterations");
IntOut(0, fix(N)); Text(0, " iterations");
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 3,953: Line 3,953:
=={{header|Zig}}==
=={{header|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.
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.
<lang Zig>
<syntaxhighlight lang=Zig>
const std = @import("std");
const std = @import("std");
const math = std.math;
const math = std.math;
Line 4,023: Line 4,023:
}
}
}
}
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 4,071: Line 4,071:
=={{header|zkl}}==
=={{header|zkl}}==
{{trans|C}}
{{trans|C}}
<lang zkl>const EPSILON=1.0e-15;
<syntaxhighlight lang=zkl>const EPSILON=1.0e-15;
fact,e,n := 1, 2.0, 2;
fact,e,n := 1, 2.0, 2;
do{
do{
Line 4,078: Line 4,078:
e+=1.0/fact;
e+=1.0/fact;
}while((e - e0).abs() >= EPSILON);
}while((e - e0).abs() >= EPSILON);
println("e = %.15f".fmt(e));</lang>
println("e = %.15f".fmt(e));</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,086: Line 4,086:
=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==


<lang zxbasic>10 LET p=13: REM precision, or the number of terms in the Taylor expansion, from 0 to 33...
<syntaxhighlight lang=zxbasic>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...
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
30 LET e=0: REM ...the factorial can't go any higher than 33
Line 4,094: Line 4,094:
70 NEXT x
70 NEXT x
80 PRINT e
80 PRINT e
90 PRINT e-EXP 1: REM the Spectrum ROM uses Chebyshev polynomials to evaluate EXP x = e^x</lang>
90 PRINT e-EXP 1: REM the Spectrum ROM uses Chebyshev polynomials to evaluate EXP x = e^x</syntaxhighlight>


{{Out}}
{{Out}}