Calculating the value of e: Difference between revisions
PascalABC.NET
(PascalABC.NET) |
|||
(99 intermediate revisions by 36 users not shown) | |||
Line 2:
;Task:
Calculate the value of <big>''e''</big>.
(<big>''e''</big> is also known as ''Euler's number'' and ''Napier's constant''.)
See details: [https://en.wikipedia.org/wiki/E_(mathematical_constant) Calculating the value of e]
<br><br>
=={{header|11l}}==
{{trans|Python}}
<
V e = 2.0
V n = 0
Line 26 ⟶ 25:
print(‘Real e = ’math:e)
print(‘Error = ’(math:e - e))
print(‘Number of iterations = ’n)</
{{out}}
<pre>
Line 34 ⟶ 33:
Number of iterations = 8
</pre>
=={{header|360 Assembly}}==
The 'include' file FORMAT, to format a floating point number, can be found in:
[[360_Assembly_include|Include files 360 Assembly]].
<
CALCE PROLOG
LE F0,=E'0'
Line 65 ⟶ 63:
PG DC CL80' ' buffer
REGEQU
END CALCE </
{{out}}
<pre>
2.71828
</pre>
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
<syntaxhighlight lang="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</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Calculating_the_value_of_e.png Screenshot from Atari 8-bit computer]
<pre>
real e=2.71828183
calculated e=2.71828178
error=-5E-08
</pre>
=={{header|Ada}}==
{{trans|Kotlin}}
<
with Ada.Long_Float_Text_IO; use Ada.Long_Float_Text_IO;
Line 97 ⟶ 139:
New_Line;
end Euler;</
{{out}}
<pre>
e = 2.718281828459046
</pre>
=={{header|ALGOL 60}}==
{{works with|A60}}
<syntaxhighlight lang = "ALGOL">
begin
real fact, n, result, epsilon;
fact := 1.0;
result := 2.0;
n := 2.0;
epsilon := 0.000000000001; comment 1E-12;
for n := n while fact >= epsilon do
begin
fact := fact / n;
n := n + 1;
result := result + fact;
end;
outstring(1,"Computed value of e =");
outreal(1, result);
outstring(1,"\nValue of e as exp(1) =");
outreal(1,exp(1.0));
outstring(1,"\nPublished value of e = 2.718281828459045");
end
</syntaxhighlight>
{{out}}
<pre>
Computed value of e = 2.71828182846
Value of e as exp(1) = 2.71828182846
Published value of e = 2.718281828459045
</pre>
=={{header|ALGOL 68}}==
{{trans|Kotlin}}
<
# calculate an approximation to e #
LONG REAL epsilon = 1.0e-15;
Line 119 ⟶ 193:
DO SKIP OD;
print( ( "e = ", fixed( e, -17, 15 ), newline ) )
END</
{{out}}
<pre>
e = 2.718281828459045
</pre>
=={{header|AppleScript}}==
For the purposes of 32 bit floating point, the value seems to stabilise after summing c. 16 terms.
<
on run
Line 225 ⟶ 298:
foldl(add, 0, xs)
end sum</
{{Out}}
<pre>2.718281828459</pre>
Or, as a single fold:
<syntaxhighlight lang="applescript">------------- 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</syntaxhighlight>
{{Out}}
<pre>2.718281828459</pre>
=={{header|Applesoft BASIC}}==
<syntaxhighlight lang="text">?"E = "EXP(1)</syntaxhighlight>
{{Out}}
<pre>E = 2.71828183</pre>
=={{header|Arturo}}==
<
e: 2.0
e0: 0.0
Line 244 ⟶ 389:
]
print e</
{{out}}
<pre>2.718281828459046</pre>
=={{header|Asymptote}}==
<syntaxhighlight lang="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
}
write("The value of e = ", e);</syntaxhighlight>
{{out}}
<pre>The value of e = 2.71828182845905</pre>
=={{header|AWK}}==
<syntaxhighlight lang="awk">BEGIN {
for (e = n = rfact = 1; rfact >= 1e-15; rfact /= ++n)
e += rfact
printf "e = %.15f\n", e
}</syntaxhighlight>
{{out}}
<pre>e = 2.718281828459046</pre>
=={{header|BASIC}}==
==={{header|BASIC256}}===
<syntaxhighlight lang="freebasic">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</syntaxhighlight>
{{out}}
<pre>The value of e = 2.71828182829</pre>
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> @%=&1302
EPSILON = 1.0E-15
Fact = 1
E = 2.0
E0 = 0.0
N% = 2
WHILE ABS(E - E0) >= EPSILON
E0 = E
Fact *= N%
N% += 1
E += 1.0 / Fact
ENDWHILE
PRINT "e = ";E
END</syntaxhighlight>
{{Out}}
<pre>e = 2.718281828459045226</pre>
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{works with|GW-BASIC}}
{{trans|QBasic}}
<syntaxhighlight lang="qbasic">10 CLS
20 N = 1 : N1 = 1
30 E1 = 0 : E = 1/1
40 WHILE E <> E1
50 E1 = E
60 E = E+1/N
70 N1 = N1+1
80 N = N*N1
90 WEND
100 PRINT "The value of E = " E
110 END</syntaxhighlight>
{{out}}
<pre>The value of E = 2.718282</pre>
==={{header|IS-BASIC}}===
<syntaxhighlight lang="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</syntaxhighlight>
{{Out}}
<pre>The value of e = 2.71828183</pre>
==={{header|GW-BASIC}}===
The [[#Chipmunk_Basic|Chipmunk Basic]] solution works without any changes.
==={{header|MSX Basic}}===
The [[#Commodore_BASIC|Commodore BASIC]] solution works without any changes.
==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="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</syntaxhighlight>
{{out}}
<pre>The value of e = 2.718282</pre>
==={{header|True BASIC}}===
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">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</syntaxhighlight>
{{out}}
<pre>The value of e = 2.7182818</pre>
==={{header|Run BASIC}}===
{{works with|Just BASIC}}
{{works with|Liberty BASIC}}
<syntaxhighlight lang="freebasic">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</syntaxhighlight>
{{out}}
<pre>The value of e = 2.71828</pre>
==={{header|XBasic}}===
{{works with|Windows XBasic}}
<syntaxhighlight lang="xbasic">PROGRAM "progname"
VERSION "0.0000"
DECLARE FUNCTION Entry ()
FUNCTION Entry ()
DOUBLE e1
DOUBLE e
DOUBLE n
n = 1
n1 = 1
e1 = 0
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
END FUNCTION
END PROGRAM</syntaxhighlight>
{{out}}
<pre>The value of e = 2.718281828459</pre>
==={{header|Yabasic}}===
{{works with|QBasic}}
{{works with|FreeBASIC| with #lang "qb"}}
<syntaxhighlight lang="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</syntaxhighlight>
{{out}}
<pre>The value of e = 2.71828</pre>
=={{header|bc}}==
<syntaxhighlight lang="bc">scale = 64
for (e = n = f = 1; f != 0; f /= ++n) e += f
e</syntaxhighlight>
{{out}}
<pre>2.7182818284590452353602874713526624977572470936999595749669676254</pre>
=={{header|Befunge}}==
Befunge has no decimal capabilities, evaluates as fractions of 10^17
<syntaxhighlight lang="befunge">52*92*1->01p:01g1-:v v *_$101p011p54*21p>:11g1+:01g*01p:11p/21g1-:v v <
^ _$$>\:^ ^ p12_$>+\:#^_$554**/@</syntaxhighlight>
{{out}}
<pre>2718281828459045</pre>
=={{header|BQN}}==
<syntaxhighlight lang="bqn">E←1+´1÷·×`1+↕</syntaxhighlight>
<syntaxhighlight lang="bqn"> E 20
2.7182818284590455</syntaxhighlight>
=={{header|Burlesque}}==
<
blsq ) 70rz?!{10 100**\/./}ms36.+Sh'.1iash
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274
</syntaxhighlight>
=={{header|C}}==
===solution 1===
<
#include <math.h>
int main(
{
double e;
Line 298 ⟶ 640:
// The fast and independed method: e = lim (1 + 1/n)**n
//
e *= e;
printf("Euler constant e = %.16lf\n", e);
Line 317 ⟶ 658:
for (int i = N - 1; i > 0; i--)
e += a[i];
printf("Euler constant e = %.16lf\n", e);
return 0;
}</
{{output}}
<pre>
Line 327 ⟶ 668:
Euler constant e = 2.7182818284590451
Euler constant e = 2.
Euler constant e = 2.7182818284590455
</pre>
Line 333 ⟶ 674:
===solution 2===
{{trans|Kotlin}}
<
#include <math.h>
Line 350 ⟶ 691:
printf("e = %.15f\n", e);
return 0;
}</
{{output}}
Line 356 ⟶ 697:
e = 2.718281828459046
</pre>
=={{header|C sharp|C#}}==
<
namespace CalculateE {
Line 377 ⟶ 717:
}
}
}</
{{out}}
<pre>e = 2.718281828459050</pre>
Line 383 ⟶ 723:
===Using Decimal type===
<
class Calc_E
Line 400 ⟶ 740:
Console.WriteLine(CalcE()); // Decimal precision result
}
}</
{{out}}
<pre>2.71828182845905
Line 407 ⟶ 747:
{{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.
<
using static System.Math; using static System.Console;
Line 429 ⟶ 769:
WriteLine("partial: {0}...{1}", es.Substring(0, 46), es.Substring(es.Length - 45));
}
}</
{{out}}
<pre>2.71828182845905
Line 436 ⟶ 776:
partial: 2.71828182845904523536028747135266249775724709...026587951482508371108187783411598287506586313
</pre>
=={{header|C++}}==
{{trans|C}}
<
#include <iomanip>
#include <cmath>
Line 458 ⟶ 797:
cout << "e = " << setprecision(16) << e << endl;
return 0;
}</
{{output}}
Line 464 ⟶ 803:
e = 2.718281828459046
</pre>
=={{header|Clojure}}==
<
;; Calculating the number e, euler-napier number.
;; We will use two methods
Line 498 ⟶ 836:
(time (with-precision 110 (method-e 200M)))
</syntaxhighlight>
<pre>
Line 504 ⟶ 842:
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274274663923M
</pre>
=={{header|COBOL}}==
{{trans|C}}
<
IDENTIFICATION DIVISION.
PROGRAM-ID. EULER.
Line 532 ⟶ 869:
DISPLAY RESULT-MESSAGE.
STOP RUN.
</syntaxhighlight>
{{out}}
<pre>
e = 2.718281828459041093
</pre>
=={{header|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
Line 549 ⟶ 885:
160 : E = E + 1/F
170 NEXT I
180 PRINT "AFTER" N "ITERATIONS, E =" E</
{{Out}}
Line 555 ⟶ 891:
READY.</pre>
=={{header|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 <tt>computable-reals</tt> makes printing out precise decimal representations easy, though:
<
(use-package :computable-reals)
Line 569 ⟶ 904:
(setq e (+ e (/ 1 f))))
(format t "After ~a iterations, e = " *iterations*)
(print-r e 2570))</
{{Out}}
Line 576 ⟶ 911:
+2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746639193200305992181741359662904357290033429526059563073813232862794349076323382988075319525101901157383418793070215408914993488416750924476146066808226480016847741185374234544243710753907774499206955170276183860626133138458300075204493382656029760673711320070932870912744374704723069697720931014169283681902551510865746377211125238978442505695369677078544996996794686445490598793163688923009879312773617821542499922957635148220826989519366803318252886939849646510582093923982948879332036250944311730123819706841614039701983767932068328237646480429531180232878250981945581530175671736133206981125099618188159304169035159888851934580727386673858942287922849989208680582574927961048419844436346324496848756023362482704197862320900216099023530436994184914631409343173814364054625315209618369088870701676839642437814059271456354906130310720851038375051011574770417189861068739696552126715468895703503540212340784981933432106817012100562788023519303322474501585390473041995777709350366041699732972508868769664035557071622684471625607988265178713419512466520103059212366771943252786753985589448969709640975459185695638023637016211204774272283648961342251644507818244235294863637214174023889344124796357437026375529444833799801612549227850925778256209262264832627793338656648162772516401910590049164499828931505660472580277863186415519565324425869829469593080191529872117255634754639644791014590409058629849679128740687050489585867174798546677575732056812884592054133405392200011378630094556068816674001698420558040336379537645203040243225661352783695117788386387443966253224985065499588623428189970773327617178392803494650143455889707194258639877275471096295374152111513683506275260232648472870392076431005958411661205452970302364725492966693811513732275364509888903136020572481765851180630364428123149655070475102544650117272115551948668508003685322818315219600373562527944951582841882947876108526398139559900673764829224437528718462457803619298197139914756448826260390338144182326251509748279877799643730899703888677822713836057729788241256119071766394650706330452795466185509666618566470971134447401607046262156807174818778443714369882185596709591025968620023537185887485696522000503117343920732113908032936344797273559552773490717837934216370120500545132638354400018632399149070547977805669785335804896690629511943247309958765523681285904138324116072260299833053537087613893963917795745401613722361878936526053815584158718692553860616477983402543512843961294603529133259...
</pre>
=={{header|Craft Basic}}==
<syntaxhighlight lang="basic">let n = 1
let m = 1
let f = 0
let e = 1
do
if e <> f then
let f = e
let e = e + 1 / n
let m = m + 1
let n = n * m
endif
loop e <> f
print "The value of e = ", e</syntaxhighlight>
{{out| Output}}<pre>The value of e = 2.72</pre>
=={{header|D}}==
<
import std.stdio;
Line 594 ⟶ 951:
} while (abs(e - e0) >= EPSILON);
writefln("e = %.15f", e);
}</
{{out}}
<pre>e = 2.718281828459046</pre>
=={{header|Dart}}==
{{trans|C++}}
<syntaxhighlight lang="dart">void main() {
const double EPSILON = 1.0e-15;
double fact = 1;
double e = 2.0, e0;
int n = 2;
do {
e0 = e;
fact *= n++;
e += 1.0 / fact;
} while ((e-e0).abs() >= EPSILON);
print('The value of e = $e');
}</syntaxhighlight>
{{out}}
<pre>The value of e = 2.7182818284590455</pre>
=={{header|dc}}==
Line 603 ⟶ 977:
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):
<
2574k [ precision to use during computation ]sx
1 d
[ [ p = begin ]sx
lf li 1 + d si
ln li <p [ if i<n recur ]sx
]sp [ end ]sx
Line 620 ⟶ 993:
2570k [ now reset precision to match correct digits ]sx
n 10P [ and print it out, again with n + 10P ]sx</
{{out}}
<pre>After 1000 iterations, e =
2.7182818284590452353602874713526624977572470936999595749669676277240\
Line 670 ⟶ 1,042:
{{Trans|C}}
<syntaxhighlight lang="delphi">
program Calculating_the_value_of_e;
Line 712 ⟶ 1,084:
end.
</syntaxhighlight>
{{out}}
Line 718 ⟶ 1,090:
e = 2,718281828459045
</pre>
=={{header|Dyalect}}==
{{trans|Swift}}
<
func abs(n) {
if n < 0 {
Line 751 ⟶ 1,122:
}
print(calculateE())</
{{out}}
<pre>2.71828182845905</pre>
=={{header|EasyLang}}==
<syntaxhighlight lang="text">
numfmt 5 0
fact = 1
n = 2
Line 768 ⟶ 1,139:
e += 1 / fact
.
print e
</syntaxhighlight>
=={{header|EDSAC order code}}==
Line 778 ⟶ 1,150:
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]
Line 863 ⟶ 1,235:
E14Z [relative address of entry]
PF [enter with accumulator = 0]
</syntaxhighlight>
{{out}}
<pre>
Line 882 ⟶ 1,254:
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.
Line 1,173 ⟶ 1,545:
E 184 Z [define entry point]
P F [acc = 0 on entry]
</syntaxhighlight>
{{out}}
<pre>
Line 1,208 ⟶ 1,580:
===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.]
</syntaxhighlight>
{{out}}
<pre>
Line 1,236 ⟶ 1,608:
9559900673764829224437528718462457803619298197139914756448826260390338
</pre>
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="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)</syntaxhighlight>
{{output}}
<pre>
2.7182818284590455</pre>
=={{header|Epoxy}}==
<syntaxhighlight lang="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)</syntaxhighlight>
{{out}}
<pre>2.7182818284590455
2.718281828459045</pre>
=={{header|Excel}}==
===LAMBDA===
Line 1,245 ⟶ 1,645:
{{Works with|Office 365 betas 2021}}
<
=LAMBDA(n,
INDEX(
Line 1,268 ⟶ 1,668:
1
)
)</
and also assuming the following generic bindings in the Name Manager for the WorkBook:
<
=LAMBDA(op,
LAMBDA(a,
Line 1,318 ⟶ 1,718:
)
)
)</
{{Out}}
Line 1,419 ⟶ 1,819:
| style="text-align:right" | 0
|}
=={{header|F_Sharp|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)
</syntaxhighlight>
Which may be used:
<
printfn "%.14f" (float (e |> Seq.take 20 |> Seq.sum))
</syntaxhighlight>
{{out}}
<pre>
2.71828182845905
</pre>
=={{header|Factor}}==
{{works with|Factor|0.98}}
<
IN: rosetta-code.calculate-e
CONSTANT: terms 20
terms <iota> [ n! recip ] map-sum >float .</
{{out}}
<pre>
2.718281828459045
</pre>
=={{header|FOCAL}}==
{{trans|ZX Spectrum Basic}}
<syntaxhighlight lang="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,!</syntaxhighlight>
{{output}}
<pre>*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</pre>
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:
<pre>*T FEXP(1),!
= 2.71828</pre>
=={{header|Forth}}==
Line 1,461 ⟶ 1,884:
* Output the next digit: The final quotient is the next digit of e.
<
: int-array create cells allot does> swap cells + ;
Line 1,481 ⟶ 1,904:
0 .r
LOOP ;
</syntaxhighlight>
{{out}}
<pre>
Line 1,489 ⟶ 1,912:
.e = 2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427 ok
</pre>
=={{header|Fortran}}==
<
Program eee
implicit none
Line 1,507 ⟶ 1,931:
write(*,*) ' polynomial ', ee
end Program eee</
{{out}}
<pre>
Line 1,513 ⟶ 1,937:
polynomial 2.71828182845904523543
</pre>
=={{header|Free Pascal}}==
''See [[#Pascal|Pascal]]''
=={{header|FreeBASIC}}==
===Normal basic===
<
' compile with: fbc -s console
Line 1,540 ⟶ 1,966:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>The value of e = 2.718281828459046</pre>
===GMP version===
{{libheader|GMP}}
<
' compile with: fbc -s console
Line 1,590 ⟶ 2,017:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>The value of e = 2.71828182845904523536028747135266249775724709369996</pre>
=={{header|Furor}}==
<syntaxhighlight lang="furor">
###sysinclude math.uh
1.0e-15 sto EPSILON
Line 1,621 ⟶ 2,039:
{ „e0” }
{ „n” }
</syntaxhighlight>
{{out}}
Line 1,628 ⟶ 2,046:
</pre>
=={{header|Peri}}==
<syntaxhighlight lang="peri">
###sysinclude standard.uh
###sysinclude math.uh
1.0e-15 sto EPSILON
one fact
2. sto en
2 sto nn
ciklus:
@en sto e0
#g @nn++ prd fact
1.0 @fact !(#d) / sum en
@en @e0 - abs @EPSILON < else §ciklus
."e = " @en printnl
end
{ „EPSILON” }
{ „fact” }
{ „en” }
{ „e0” }
{ „nn” }
</syntaxhighlight>
{{out}}
<pre>
e = +2.71828182845905
</pre>
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
local fn EulerConstant_e as double
UInt64 n = 1, n1 = 1
double e1 = 0, e = 1 / 1
while ( e <> e1 )
e1 = e
e = e + 1 / n
n1 = n1 + 1
n = n * n1
wend
end fn = e
window 1
print "Euler constant e = "; fn EulerConstant_e
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Euler constant e = 2.718281828459046
</pre>
=={{header|Fōrmulæ}}==
{{FormulaeEntry|page=https://formulae.org/?script=examples/Calculating_the_value_of_e}}
'''Solution 1.''' In Fōrmulæ, the Euler's number can be directly calculated within an arbitrary given precision.
[[File:Fōrmulæ - Calculating the value of e 01.png]]
[[File:Fōrmulæ - Calculating the value of e 02.png]]
'''Solution 2.''' Using series
[[File:Fōrmulæ - Calculating the value of e 03.png]]
[[File:Fōrmulæ - Calculating the value of e 04.png]]
'''Solution 3.''' Using a program
[[File:Fōrmulæ - Calculating the value of e 05.png]]
[[File:Fōrmulæ - Calculating the value of e 06.png]]
=={{header|Go}}==
{{trans|Kotlin}}
<
import (
Line 1,655 ⟶ 2,145:
}
fmt.Printf("e = %.15f\n", e)
}</
{{out}}
Line 1,661 ⟶ 2,151:
e = 2.718281828459046
</pre>
=={{header|Groovy}}==
'''Solution: '''<br>
Line 1,667 ⟶ 2,156:
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/ε
Line 1,683 ⟶ 2,172:
}
def e = generateAddends().sum()</
'''Test: '''
<
'''Output: '''
<pre>2.718281828459045
2.718281828459045</pre>
=={{header|Haskell}}==
For the purposes of 64 bit floating point precision, the value seems to stabilise after summing c. 17-20 terms.
<syntaxhighlight lang="haskell">------ 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</
{{Out}}
<pre>2.7182818284590455</pre>
Line 1,703 ⟶ 2,195:
Or equivalently, in a single fold:
<syntaxhighlight lang="haskell">------ APPROXIMATION OF E OBTAINED AFTER N ITERATIONS ----
eApprox n =
snd $
( \x (fl, e) ->
(
--------------------------- TEST -------------------------
main :: IO ()
main = print
{{Out}}
<pre>2.7182818284590455</pre>
Or in terms of iterate:
<syntaxhighlight lang="haskell">{-# 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</syntaxhighlight>
{{Out}}
<pre>2.7182818284590455</pre>
=={{header|Hoon}}==
<syntaxhighlight lang="hoon">:- %say
|= *
:- %noun
=/ i .~2
=/ e .~1
=/ e0 .~0
=/ denom .~1
|-
?: (lth:rd (sub:rd e e0) .~1e-15)
e
%= $
i (add:rd i .~1)
e (add:rd e (div:rd .~1 denom))
e0 e
denom (mul:rd denom i)
==</syntaxhighlight>
=={{header|Icon}} and {{header|Unicon}}==
Line 1,726 ⟶ 2,255:
For Icon, the EPSILON preprocessor constant would need to be an inline constant where tested, or set in a variable.
<
procedure main()
Line 1,743 ⟶ 2,272:
write("computed e ", e)
write("keyword &e ", &e)
end</
{{out}}
Line 1,750 ⟶ 2,279:
keyword &e 2.718281828459045</pre>
=={{header|
Perhaps too brief:
<syntaxhighlight lang=J> 0j100": +/%!i.100x
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274</syntaxhighlight>
<hr/>
The j language has expressive notations for numbers. Examples:
<pre>
NB. rational one half times pi to the first power
Line 1,772 ⟶ 2,296:
</pre>
<pre>
1x1 NB. 1 times e^1
2.71828
</pre>
This is a floating point value (and, thus, accurate to 16 decimal places (15 places after the decimal point, in this example)).
The unary power verb ^ uses Euler's number as the base, hence
Line 1,784 ⟶ 2,310:
</pre>
<pre>
NB. approximation to e as a rational number
Line 1,792 ⟶ 2,318:
NB. 31 places shown with 20 terms
2.718281828459045234928752728335
NB. 40 terms
2.718281828459045235360287471353
NB. 50 terms,
2.718281828459045235360287471353
Line 1,837 ⟶ 2,363:
=={{header|Java}}==
<p>
If you wanted to do this with the basic, bounded, primitive data-types, you could use the following implementation.
</p>
<syntaxhighlight lang="java">
double e(long limit) {
double e = 1;
for (long term = 1; term <= limit; term++)
e += 1d / factorial(term);
return e;
}
long factorial(long value) {
return value == 1 ? value : value * factorial(--value);
}
</syntaxhighlight>
Here is an execution with 65 terms.
<pre>
2.7182818284590455
</pre>
<p>
Alternately, this can be done using the <code>BigDecimal</code> and <code>BigInteger</code> classes.<br />
Each which offer the ability to compute values beyond the constraints of both <code>double</code> and <code>long</code>, respectively.
</p>
<p>
I used a <kbd>rounding-mode</kbd> of "half-up", which rounds at 0.5 to 1, and at -0.5 to -1.
</p>
<p>
You can set the scale with the <kbd>scale</kbd> argument, which will ultimately be the <code>int</code> maximum, which is 2,147,483,647.
</p>
<syntaxhighlight lang="java">
import static java.math.RoundingMode.HALF_UP;
import java.math.BigDecimal;
import java.math.BigInteger;
</syntaxhighlight>
<syntaxhighlight lang="java">
BigDecimal e(BigInteger limit, int scale) {
BigDecimal e = BigDecimal.ONE.setScale(scale, HALF_UP);
BigDecimal n;
BigInteger term = BigInteger.ONE;
while (term.compareTo(limit) <= 0) {
n = new BigDecimal(String.valueOf(factorial(term)));
e = e.add(BigDecimal.ONE.divide(n, scale, HALF_UP));
term = term.add(BigInteger.ONE);
}
return e;
}
BigInteger factorial(BigInteger value) {
if (value.compareTo(BigInteger.ONE) > 0) {
return value.multiply(factorial(value.subtract(BigInteger.ONE)));
} else {
return BigInteger.ONE;
}
}
</syntaxhighlight>
<p>
Here is a execution using 100 terms, and a scale of 1000.
</p>
<syntaxhighlight lang="java">
BigDecimal e = e(BigInteger.valueOf(100), 1000);
</syntaxhighlight>
<pre>
2.718281828459045235360287471352662497757247093699959574966967627724076630353547
59457138217852516642742746639193200305992181741359662904357290033429526059563073
80251882050351967424723324653614466387706813388353430034139974174573454428990064
20505625641288373144866257181218169558839675319515277938384101062576645231282166
05239098395155129969477630231658550707025356578811143735087981194929233692894922
18803532415232263419815664514069500471960037083157525314472746953376422185585970
49072791947918398790373277485203358571021151276932683987895240761723360600431495
39142130255178704446106587993897518897018555141736300685184133175671746042499671
27787770519325213151660446607713922514023318509164691235154486907393983388487303
71051660145947922319807187020285702323658476026591320639392924337656895542820166
62247170847987607703419588398315167187799994627689255589861192622972941592318112
80945595959314875046163012079992544503657235607075679104723168137049185311508243
129582873013636538450324418025276976013009
</pre>
<br />
Or, you could use the following implementation.
{{trans|Kotlin}}
<
public static final double EPSILON = 1.0e-15;
Line 1,853 ⟶ 2,457:
System.out.printf("e = %.15f\n", e);
}
}</
{{out}}
<pre>e = 2.718281828459046</pre>
=={{header|Javascript}}==
Summing over a scan
<syntaxhighlight lang="javascript">(() => {
"use strict";
// - APPROXIMATION OF E OBTAINED AFTER N ITERATIONS --
// eApprox : Int ->
const eApprox =
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);
//
const
b => a *
// scanl :: (b -> a -> b) -> b -> [a] -> [b]
const scanl =
// The series of interim values arising
// from a catamorphism. Parallel to foldl.
xs.reduce((a, x) => {
const v = f(a
return [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);
return main();
})();</syntaxhighlight>
<pre>2.7182818284590455</pre>
Or as a single fold/reduce:
<syntaxhighlight lang="javascript">(() => {
"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();
})();</syntaxhighlight>
{{Out}}
<pre>2.7182818284590455</pre>
=={{header|Joy}}==
<syntaxhighlight lang="joy">1 dup 2 52 pow dup [/ +] dip pow.</syntaxhighlight>
{{out}}
<pre>2.71828</pre>
=={{header|jq}}==
<syntaxhighlight lang="text">1|exp #=> 2.718281828459045</
<syntaxhighlight lang="text">def e:
[null,0,1,1]
| until(.[0] == .[1]; .[0]=.[1] | .[1]+=1/.[2] | .[2] *= .[3] | .[3]+=1)
| .[0];
e #=> 2.7182818284590455</
=={{header|Julia}}==
Line 1,923 ⟶ 2,573:
'''Module''':
<
export NeperConst
Line 1,947 ⟶ 2,597:
end
end # module NeperConstant</
'''Main''':
<
println(NeperConst{F}())
end</
{{out}}
Line 1,959 ⟶ 2,609:
(Float64) 2.7182818284590455
(BigFloat) 2.718281828459045235360287471352662497757247093699959574966967627724076630353416</pre>
=={{header|K}}==
<syntaxhighlight lang="k">
/ Computing value of e
/ ecomp.k
Line 1,968 ⟶ 2,617:
evalue:{1 +/(1.0%)'fact' 1+!20}
evalue[]
</syntaxhighlight>
{{out}}
Line 1,975 ⟶ 2,624:
2.7182818284590455
</pre>
=={{header|Klingphix}}==
<syntaxhighlight lang="text">%e0 %e %n %fact %v
0 !e0 2 !e 0 !n 1 !fact
Line 2,000 ⟶ 2,648:
"Number of iterations = " $n printOp
" " input</
=={{header|Kotlin}}==
<
import kotlin.math.abs
Line 2,020 ⟶ 2,667:
while (abs(e - e0) >= EPSILON)
println("e = %.15f".format(e))
}</
{{output}}
<pre>
e = 2.718281828459046
</pre>
This can also be done in a functional style. Empirically, 17 iterations are enough to get the maximum precision for 64-bit floating-point numbers. Also, for best results, we should sum smaller values before larger values; otherwise we can lose precision when adding a small value to a large value. The `asReversed()` call below is optional but highly recommended. The result of the calculation is identical to the standard library constant.
<syntaxhighlight lang="kotlin">fun main() {
val e = (1..17).runningFold(1L, Long::times)
.asReversed() // summing smaller values first improves accuracy
.sumOf { 1.0 / it }
println(e)
println(e == kotlin.math.E)
}</syntaxhighlight>
{{output}}
<pre>
2.718281828459045
true
</pre>
=={{header|Lambdatalk}}==
<
1) straightforward
Line 2,054 ⟶ 2,717:
{euler 1 17}
-> 2.7182818284590455
</syntaxhighlight>
=={{header|langur}}==
{{trans|Go}}
<
val .epsilon = 1.0e-104
Line 2,066 ⟶ 2,728:
for .fact, .n = 1, 2 ; ; .n += 1 {
val .e0 = .e
.fact
.e += 1 / .fact
if abs(.e - .e0) < .epsilon: break
Line 2,074 ⟶ 2,736:
# compare to built-in constant e
writeln " e = ", e</
{{out}}
Line 2,084 ⟶ 2,746:
=={{header|Lua}}==
<
fact = 1
Line 2,098 ⟶ 2,760:
until (math.abs(e - e0) < EPSILON)
io.write(string.format("e = %.15f\n", e))</
{{out}}
<pre>e = 2.718281828459046</pre>
=={{header|M2000 Interpreter}}==
Using @ for Decimal, and ~ for Float, # for Currency (Double is the default type for M2000)
<syntaxhighlight lang="m2000 interpreter">
Module FindE {
Function comp_e (n){
Line 2,123 ⟶ 2,784:
}
FindE
</syntaxhighlight>
{{out}}
Line 2,134 ⟶ 2,795:
As a lambda function (also we use a faster For, using block {})
<syntaxhighlight lang="m2000 interpreter">
comp_e=lambda (n)->{n/=28:For i=27to 1 {n=1+n/i}:=n}
</syntaxhighlight>
=={{header|Maple}}==
<
# 2.7182818284590452353602874713526624977572470937000
evalf[50](exp(1));
# 2.7182818284590452353602874713526624977572470937000</
With [https://en.wikipedia.org/wiki/Continued_fraction continued fractions]:
<
e:=ContinuedFraction(exp(1)):
Convergent(e,100);
Line 2,154 ⟶ 2,814:
# 13823891428306770374331665289458907890372191037173036666131/5085525453460186301777867529962655859538011626631066055111
# 2.7182818284590452353602874713526624977572470937000</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
{{output}}
<pre>
Line 2,163 ⟶ 2,822:
</pre>
<
<
<syntaxhighlight lang
or even just
<syntaxhighlight lang
input as <syntaxhighlight lang
{{output}}
<pre>𝕖</pre>
=={{header|
Using the expansion of an associated continued fraction
<syntaxhighlight lang="maxima">
block(cfexpand([2,1,2,1,1,4,1,1,6,1,1,8,1,1,10,1,1,12,1,1,14]),float(%%[1,1]/%%[2,1]));
/* Comparing with built-in constant */
%e,numer;
</syntaxhighlight>
{{out}}
<pre>
2.718281828459045
2.718281828459045
</pre>
=={{header|min}}==
{{works with|min|0.37.0}}
<syntaxhighlight lang="min">1 0
(dup 16 >) 'pop (succ over over / swap) '+ linrec
puts!</syntaxhighlight>
{{out}}
<pre>2.718281828459045</pre>
=={{header|МК-61/52}}==
<
ИП3 ИП2 ИП1 ИП0 - 1 + * П2 1/x + П3
ИП0 x#0 25 L0 08 ИП3 С/П</
At n = 10, the value is 2.7182819.
=={{header|Modula-2}}==
<
FROM RealStr IMPORT RealToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 2,227 ⟶ 2,897:
ReadChar
END CalculateE.</
=={{header|Myrddin}}==
<
const main = {
Line 2,245 ⟶ 2,914:
;;
std.put("e: {}\n", e)
}</
=={{header|Nanoquery}}==
{{trans|Python}}
<
e = 2
n = 0
Line 2,261 ⟶ 2,929:
println "Computed e = " + e
println "Number of iterations = " + n</
{{out}}
<pre>
Line 2,267 ⟶ 2,935:
Number of iterations = 9
</pre>
=={{header|Nim}}==
<
var fact : int64 = 1
var e : float64 = 2.0
Line 2,281 ⟶ 2,948:
e = e + 1.0 / fact.float64
echo e</
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">let n = 0x1p52
let e = (1. /. n +. 1.) ** n
let () = Printf.printf "%.15f (%B)\n" e (exp(1.) = e)</syntaxhighlight>
{{out}}
<pre>2.718281828459045 (true)</pre>
=={{header|Pascal}}==
Like delphi and many other.Slightly modified to calculate (1/n!) not n! and then divide to (1/n!)
<
{$IFDEF FPC}
{$MODE DELPHI}
Line 2,318 ⟶ 2,994:
{$IFDEF WINDOWS}readln;{$ENDIF}
end.
</syntaxhighlight>
{{out}}
<pre>calc e = 2.718281828459045 intern e= 2.718281828459045</pre>
=={{header|PascalABC.NET}}==
<syntaxhighlight lang="delphi">
function MyExp(x: real): real;
const eps = 1e-15;
begin
var y := 1.0;
var s := y;
var i := 1;
while y > eps do
begin
y *= x / i;
s += y;
i += 1;
end;
Result := s;
end;
begin
Println(MyExp(1));
Println(Exp(1));
end.
</syntaxhighlight>
{{out}}
<pre>
2.71828182845905
2.71828182845905
</pre>
=={{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>.
<
$e = 2;
Line 2,336 ⟶ 3,040:
print "Computed " . substr($e, 0, 41), "\n";
print "Built-in " . e, "\n";</
{{out}}
<pre>Computed 2.718281828459045235360287471352662497757
Line 2,345 ⟶ 3,049:
Here, 71 terms of the Taylor series yield 𝑒 to 101 digits.
<
use Math::Decimal qw(dec_canonise dec_mul dec_rndiv_and_rem);
Line 2,370 ⟶ 3,074:
}
printf "\n%s\n", subset $e, 0,102;</
{{out}}
<pre>numerator: 32561133701373476427912330475884581607687531065877567210421813247164172713574202714721554378508046501
Line 2,379 ⟶ 3,083:
=={{header|Phix}}==
{{trans|Python}}
<!--<
<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: #004080;">atom</span> <span style="color: #000000;">e0</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">e</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">fact</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">while</span> <span style="color: #7060A8;">abs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">e</span><span style="color: #0000FF;">-</span><span style="color: #000000;">e0</span><span style="color: #0000FF;">)>=</span><span style="color: #000000;">1e-15</span> <span style="color: #008080;">do</span>
Line 2,389 ⟶ 3,094:
<span style="color: #008080;">end</span> <span style="color: #008080;">while</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;">"Computed e = %.15f\n"</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;">" Real e = %.15f\n"</span><span style="color: #0000FF;">,</span><span style="color: #004600;">
<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;">
<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>
<!--</
{{out}}
<pre>
Line 2,400 ⟶ 3,105:
Number of iterations = 9
</pre>
=={{header|Phixmonti}}==
{{trans|Python}}
<
1e-15 var v
Line 2,426 ⟶ 3,130:
"Real e = " rE tostr printOp
"Error = " rE e - printOp
"Number of iterations = " n printOp</
{{out}}
<pre>
Line 2,434 ⟶ 3,138:
Number of iterations = 9
</pre>
=={{header|PicoLisp}}==
<
(let (F 1 E 2.0 E0 0 N 2)
(while (> E E0)
Line 2,442 ⟶ 3,145:
(inc 'E (*/ 1.0 F))
(inc 'N) )
(prinl "e = " (format E *Scl)) )</
{{out}}
<pre>e = 2.718281828459046</pre>
=={{header|PowerShell}}==
{{trans|Python}}
<
$e = 2
$n = 0
Line 2,462 ⟶ 3,164:
Write-Host " Real e = $([Math]::Exp(1))"
Write-Host " Error = $([Math]::Exp(1) - $e)"
Write-Host "Number of iterations = $n"</
{{out}}
<pre>Computed e = 2.71828182845904
Line 2,468 ⟶ 3,170:
Error = 4.44089209850063E-16
Number of iterations = 9</pre>
=={{header|Processing}}==
Updated to show that computed value matches library value after 21 iterations.
<syntaxhighlight lang="java">
void setup() {
double e = 0;
long factorial = 1;
for (int i = 0; i < iterations; i++) {
e += (double) (2 * i + 1) / factorial;
factorial *= (2 * i + 1) * (2 * i + 2);
}
println("After
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));
}
</syntaxhighlight>
{{out}}
<pre>
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
</pre>
=={{header|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)
Line 2,513 ⟶ 3,234:
?- main.
</syntaxhighlight>
{{Out}}
<pre>
Line 2,520 ⟶ 3,241:
</pre>
===Arbitrary-precision solution===
<syntaxhighlight lang="prolog">
% 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.
</syntaxhighlight>
{{Out}}
<pre>
$ swipl e.pl 1000
e = 2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427427466391932003059921817413596629
043572900334295260595630738132328627943490763233829880753195251019011573834187930702154089149934884167509244761460668082264800168477411853
742345442437107539077744992069551702761838606261331384583000752044933826560297606737113200709328709127443747047230696977209310141692836819
025515108657463772111252389784425056953696770785449969967946864454905987931636889230098793127736178215424999229576351482208269895193668033
182528869398496465105820939239829488793320362509443117301238197068416140397019837679320683282376464804295311802328782509819455815301756717
361332069811250996181881593041690351598888519345807273866738589422879228499892086805825749279610484198444363463244968487560233624827041978
623209002160990235304369941849146314093431738143640546253152096183690888707016768396424378140592714563549061303107208510383750510115747704
1718986106873969655212671546889570350354
Computed in 0.000998 sec
</pre>
=={{header|PureBasic}}==
<
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)</
{{out}}
<pre>e=2.718281828459046</pre>
Line 2,531 ⟶ 3,289:
=={{header|Python}}==
===Imperative===
<
#Implementation of Brother's formula
e0 = 0
Line 2,546 ⟶ 3,304:
print "Real e = "+str(math.e)
print "Error = "+str(math.e-e)
print "Number of iterations = "+str(n)</
{{out}}
<pre>
Line 2,554 ⟶ 3,312:
Number of iterations = 9
</pre>
;Using integer arithmetic only
Easily generate thousands of digits:
<syntaxhighlight lang="python">e = rfct = 10 ** 1000
n = 1
while rfct:
n += 1
e += rfct
rfct //= n
print(f"{e}\n...in {n} steps")</syntaxhighlight>
{{out}}
Turns out that just the last three decimal places are wrong.
<pre>27182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274274663919320030599218174135966290435729003342952605956307381323286279434907632338298807531952510190115738341879307021540891499348841675092447614606680822648001684774118537423454424371075390777449920695517027618386062613313845830007520449338265602976067371132007093287091274437470472306969772093101416928368190255151086574637721112523897844250569536967707854499699679468644549059879316368892300987931277361782154249992295763514822082698951936680331825288693984964651058209392398294887933203625094431173012381970684161403970198376793206832823764648042953118023287825098194558153017567173613320698112509961818815930416903515988885193458072738667385894228792284998920868058257492796104841984443634632449684875602336248270419786232090021609902353043699418491463140934317381436405462531520961836908887070167683964243781405927145635490613031072085103837505101157477041718986106873969655212671546889570350116
...in 450 steps</pre>
===Functional===
Line 2,559 ⟶ 3,331:
{{Works with|Python|3.7}}
<
from itertools import (accumulate, chain)
Line 2,606 ⟶ 3,378:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>2.7182818284590455</pre>
Or in terms of a single fold/reduce:
<syntaxhighlight lang="python">'''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()</syntaxhighlight>
{{Out}}
<pre>2.7182818284590455</pre>
=={{header|Quackery}}==
Using the Quackery bignum rational arithmetic library.
<
[ swap number$
Line 2,649 ⟶ 3,445:
3 times drop temp release ] is approximate-e ( n n --> )
55 70 approximate-e</
{{Out}}
Line 2,710 ⟶ 3,506:
54 : 2.7182818284590452353602874713526624977572470936999595749669676277240766
55 : 2.7182818284590452353602874713526624977572470936999595749669676277240766</pre>
=={{header|R}}==
<syntaxhighlight lang="r">
options(digits=22)
cat("e =",sum(rep(1,20)/factorial(0:19)))
</syntaxhighlight>
{{Out}}
<pre>
e = 2.718281828459046
</pre>
=={{header|Racket}}==
<
(require math/number-theory)
Line 2,724 ⟶ 3,526:
(displayln e)
(displayln (real->decimal-string e 20))
(displayln (real->decimal-string (- (exp 1) e) 20))))</
{{out}}
<pre>82666416490601/30411275102208
2.71828182845904523493
0.00000000000000000000</pre>
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|
<syntaxhighlight lang="raku"
# 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.
.say for 𝑒
say '';
# Or, if you don't need high precision, it's a built-in.
say e;</
{{out}}
<pre>2.718281828459045235360287471352662497757247093699959574966967627724076630353547
Line 2,762 ⟶ 3,562:
04171898610687396965521267154688957035035402123407849819334321068170121005627880
23519303322474501585390473041995777709350366041699732972508868769664035557071622
68447162560798827
2.
=={{header|REXX}}==
Line 2,780 ⟶ 3,580:
If the argument (digs) is negative, a running number of decimal digits of <big>''e''</big> is
shown.
<
parse arg digs . /*get optional number of decimal digits*/
if digs=='' | digs=="," then digs= 101 /*Not specified? Then use the default.*/
Line 2,794 ⟶ 3,594:
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).
Line 2,884 ⟶ 3,684:
===version 2===
Using the series shown in version 1 compute e to the specified precision.
<
Parse Arg dig /* the desired precision */
Numeric Digits (dig+3) /* increase precision */
Line 2,899 ⟶ 3,699:
Numeric Digits dig /* the desired precision */
e=e/1 /* the desired approximation */
Return left(e,dig+1) '('n 'iterations required)'</
{{out}}
<pre>J:\>rexx eval compey(66)
compey(66)=2.71828182845904523536028747135266249775724709369995957496696762772 (52 iterations required)</pre>
Check the function's correctness
<
e_='2.7182818284590452353602874713526624977572470936999595749669676277240'||,
'766303535475945713821785251664274274663919320030599218174135966290435'||,
Line 2,919 ⟶ 3,719:
Else ok=ok+1
End
Say ok 'comparisons are ok' </
{{out}}
<pre>J:\>rexx compez
98 comparisons are ok</pre>
=={{header|Ring}}==
<
# Project : Calculating the value of e
Line 2,949 ⟶ 3,748:
return n * factorial(n-1)
ok
</syntaxhighlight>
Output:
<pre>
Line 2,956 ⟶ 3,755:
Calculating the value of e with method #2:
e = 2.71828182828617
</pre>
=={{header|RPL}}==
{{trans|Forth}}
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! Code
! Comments
|-
|
≪ "e = 2." → n result
≪ {} n 1 + + 1 CON
2 n '''START'''
0 SWAP
n 1 + 1 '''FOR''' j
DUP j GET 10 * ROT +
j 1 + MOD LAST / IP ROT ROT
j SWAP PUT
-1 '''STEP'''
result ROT →STR + 'result' STO
'''NEXT'''
DROP result
≫ ≫ ‘°e’ STO
|
''( n -- "2.718..." )''
Create a (n+1)-array filled with 1s
Loop n-1 times
Reset carry
Scan array from the right
multiply by 10, add carry
a(j) modulo j+1 , send quotient to stack
Replace a(j) with a(j) mod j+1
Add final quotient to output string
Show only result
|}
The following line of command delivers what is required:
100 °e
{{out}}
<pre>
1: "e = 2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427"
</pre>
=={{header|Ruby}}==
{{trans|C}}
<
fact = 1
e = 2
Line 2,974 ⟶ 3,815:
puts e
</syntaxhighlight>
Built in:
<
puts BigMath.E(50).to_s # 50 decimals
</syntaxhighlight>
{{out}}
<pre>
Line 2,986 ⟶ 3,827:
=={{header|Rust}}==
<
fn main() {
Line 3,002 ⟶ 3,843:
}
println!("e = {:.15}", e);
}</
{{out}}
<pre>e = 2.718281828459046</pre>
=={{header|S-BASIC}}==
<syntaxhighlight lang="BASIC">
rem - return double-precision value of e
function e = real.double
var fact, n, result, epsilon = real.double
result = 2.0
fact = 1.0
n = 2.0
epsilon = 1.0E-12
repeat
begin
fact = fact / n
n = n + 1.0
result = result + fact
end
until fact < epsilon
end = result
rem - test the function
print "Calculated value of e ="; e
print "Value of e as exp(1.0) ="; exp(1.0)
print "Published value of e = 2.718281828459045"
end
</syntaxhighlight>
{{out}}
<pre>
Calculated value of e = 2.718281828459
Value of e as exp(1.0) = 2.71828
Published value of e = 2.718281828459045
</pre>
=={{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)].
<
object CalculateE extends App {
Line 3,022 ⟶ 3,896:
println(f"ℯ = ${iter(1L, 2.0, 2, 0)}%.15f")
}</
=={{header|Scheme}}==
{{trans|JavaScript}}
<syntaxhighlight lang="scheme">
(import (rnrs))
Line 3,063 ⟶ 3,939:
(display (e))
(newline)</
===High Precision===
{{works with|Chez Scheme}}
'''Series Implementation'''
<br />
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.
<syntaxhighlight lang="scheme">; 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))))))</syntaxhighlight>
'''Convert for Display'''
<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 '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))))))</syntaxhighlight>
'''The Task'''
<syntaxhighlight lang="scheme">; 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)))</syntaxhighlight>
{{out}}
<pre>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</pre>
=={{header|Seed7}}==
The Seed7 library [http://seed7.sourceforge.net/libraries/math.htm math.s7i] defines
Line 3,070 ⟶ 4,034:
The program below computes e:
<
include "float.s7i";
Line 3,089 ⟶ 4,053:
until abs(e - e0) < EPSILON;
writeln("e = " <& e digits 15);
end func;</
{{out}}
Line 3,095 ⟶ 4,059:
e = 2.718281828459046
</pre>
=={{header|Sidef}}==
<
sum(0..n, {|k| 1/k! })
}
say calculate_e()
say calculate_e(69).as_dec(100)</
{{out}}
<pre>
Line 3,112 ⟶ 4,075:
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:
<
var t = n*log(10)
(n + 10).bsearch_le { |k|
Line 3,122 ⟶ 4,085:
var n = f(10**k)
say "Sum_{k=0..#{n}} 1/k! = e correct to #{10**k->commify} decimal places"
}</
{{out}}
<pre>
Line 3,136 ⟶ 4,099:
Sum_{k=0..1158787577} 1/k! = e correct to 10,000,000,000 decimal places
</pre>
=={{header|Standard ML}}==
<
let
val eps = 1.0e~15
Line 3,153 ⟶ 4,115:
in
calcToEps'(2.0, 1.0, 1.0, 2.0)
end;</
{{out}}
Line 3,162 ⟶ 4,124:
val it = ~4.4408920985E~16 : real
</pre>
=={{header|Swift}}==
{{trans|C}}
<
Line 3,185 ⟶ 4,146:
}
print(String(format: "e = %.15f\n", arguments: [calculateE()]))</
{{out}}
<pre>e = 2.718281828459046</pre>
=={{header|Tcl}}==
=== By the power series of exp(x) ===
<
set ε 1.0e-15
set fact 1
Line 3,206 ⟶ 4,166:
set e [expr $e + 1.0/$fact]
}
puts "e = $e"</
{{Out}}
<pre>
Line 3,213 ⟶ 4,173:
=== 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.
Line 3,262 ⟶ 4,222:
calcE 17
</syntaxhighlight>
{{out}}
<pre>
Line 3,268 ⟶ 4,228:
e = 2.718281828459045
</pre>
=={{header|TI-83 BASIC}}==
Guided by the Awk version.
<
2->N
2->E
Line 3,283 ⟶ 4,242:
End
Disp E
</syntaxhighlight>
{{Out}}
<pre>2.718281828</pre>
=={{header|UNIX Shell}}==
<syntaxhighlight lang="sh"># POSIX requires "signed long" for shell arithmetic, so assume to have at
# least 31 bits available, which is sufficient to store (e - 1) * 10^9
declare -ir one=10**9
declare -i e n rfct=one
while (( rfct /= ++n ))
do e+=rfct
done
echo "$((e / one + 1)).$((e % one))"</syntaxhighlight>
{{out}}
<pre>2.718281823</pre>
=={{header|VBScript}}==
{{Trans|Python}}
<
While (e - e0) > 1E-15
e0 = e
Line 3,300 ⟶ 4,274:
WScript.Echo "Real e = " & Exp(1)
WScript.Echo "Error = " & (Exp(1) - e)
WScript.Echo "Number of iterations = " & n</
{{Out}}
<pre>Computed e = 2.71828182845904
Line 3,307 ⟶ 4,281:
Number of iterations = 9</pre>
=={{header|Verilog}}==
<syntaxhighlight lang="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</syntaxhighlight>
{{out}}
<pre>The value of e = 2.71828</pre>
=={{header|Visual Basic .NET}}==
{{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.
<
Module Program
Line 3,328 ⟶ 4,325:
WriteLine("partial: {0}...{1}", es.Substring(0, 46), es.Substring(es.Length - 45))
End Sub
End Module</
{{out}}
<pre>2.71828182845905
Line 3,334 ⟶ 4,331:
250,000 digits in 22.559 seconds.
partial: 2.71828182845904523536028747135266249775724709...026587951482508371108187783411598287506586313</pre>
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (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}")
}</syntaxhighlight>
{{out}}
<pre>
e = 2.718281828459046
</pre>
=={{header|Wren}}==
{{trans|Go}}
<
var fact = 1
var e = 2
Line 3,348 ⟶ 4,370:
if ((e - e0).abs < epsilon) break
}
System.print("e = %(e)")</
{{out}}
Line 3,356 ⟶ 4,378:
=={{header|XPL0}}==
<
[Format(1, 16); \show 16 places after decimal point
N:= 1.0; E:= 1.0; F:= 1.0;
Line 3,367 ⟶ 4,389:
RlOut(0, E); CrLf(0);
IntOut(0, fix(N)); Text(0, " iterations");
]</
{{out}}
Line 3,373 ⟶ 4,395:
2.7182818284590500
18 iterations
</pre>
=={{header|Zig}}==
{{works with|Zig|0.11.0}}
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.
<syntaxhighlight lang="zig">
const std = @import("std");
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
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;
},
}
const ov1 = @mulWithOverflow(a, p1);
if (ov1[1] != 0) break;
const ov2 = @addWithOverflow(ov1[0], p0);
if (ov2[1] != 0) break;
const ov3 = @mulWithOverflow(a, q1);
if (ov3[1] != 0) break;
const ov4 = @addWithOverflow(ov3[0], q0);
if (ov4[1] != 0) break;
const p2 = ov2[0];
const q2 = ov4[0];
try stdout.print("e ~= {d:>19} / {d:>19} = ", .{ p2, q2 });
try decPrint(stdout, p2, q2, 36);
try stdout.writeByte('\n');
p0 = p1;
p1 = p2;
q0 = q1;
q1 = q2;
}
}
fn decPrint(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: u128 = @intCast(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 = @as(u8, @intCast(n / m)) + '0';
try ostream.writeByte(ch);
}
}
</syntaxhighlight>
{{Out}}
<pre>
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
</pre>
=={{header|zkl}}==
{{trans|C}}
<
fact,e,n := 1, 2.0, 2;
do{
Line 3,384 ⟶ 4,526:
e+=1.0/fact;
}while((e - e0).abs() >= EPSILON);
println("e = %.15f".fmt(e));</
{{out}}
<pre>
e = 2.718281828459046
</pre>
=={{header|ZX Spectrum Basic}}==
<
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
Line 3,400 ⟶ 4,541:
70 NEXT x
80 PRINT e
90 PRINT e-EXP 1: REM the Spectrum ROM uses Chebyshev polynomials to evaluate EXP x = e^x</
{{Out}}
|