Calculating the value of e: Difference between revisions

(→‎solution 1: make use of all double precision bits)
(30 intermediate revisions by 15 users not shown)
Line 2:
 
;Task:
Calculate the value of &nbsp; <big>''e''</big>.
 
 
(<big>''e''</big> &nbsp; is also known as &nbsp; ''Euler's number'' &nbsp; and &nbsp; ''Napier's constant''.)
 
 
Line 412:
{{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)
# syntax: GAWK -f CALCULATING_THE_VALUE_OF_E.AWK
e += rfact
BEGIN {
epsilonprintf "e = 1%.0e-1515f\n", e
}</syntaxhighlight>
fact = 1
e = 2.0
n = 2
do {
e0 = e
fact *= n++
e += 1.0 / fact
} while (abs(e-e0) >= epsilon)
printf("e=%.15f\n",e)
exit(0)
}
function abs(x) { if (x >= 0) { return x } else { return -x } }
</syntaxhighlight>
{{out}}
<pre>e = 2.718281828459046</pre>
<pre>
 
e=2.718281828459046
</pre>
=={{header|BASIC}}==
==={{header|BASIC256}}===
Line 450 ⟶ 438:
{{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}}===
Line 554 ⟶ 596:
{{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
Line 881 ⟶ 931:
loop e <> f
 
print "The value of e = ", e</syntaxhighlight>
{{out| Output}}<pre>The value of e = 2.72</pre>
 
end</syntaxhighlight>
 
=={{header|D}}==
Line 930 ⟶ 979:
<syntaxhighlight lang="dc">1000 sn [ n = number of iterations ]sx
2574k [ precision to use during computation ]sx
1 d se sf [ set e (kept on the stack) and f to 1 ]sx
0 si [ set i to 0 ]sx
[ [ p = begin ]sx
lf li 1 + d si */ d sf [ f = f*( / ++i) ]sx
le+ 1 lf / + se [ e = e + 1/f ]sx
ln li <p [ if i<n recur ]sx
]sp [ end ]sx
Line 945 ⟶ 993:
 
2570k [ now reset precision to match correct digits ]sx
le 1 / [ get result truncated to that precision ]sx
n 10P [ and print it out, again with n + 10P ]sx</syntaxhighlight>
{{out}}
 
{{Out}}
<pre>After 1000 iterations, e =
2.7182818284590452353602874713526624977572470936999595749669676277240\
Line 988 ⟶ 1,035:
574540161372236187893652605381558415871869255386061647798340254351284\
3961294603529133259</pre>
 
=={{header|Delphi}}==
''See [[#Pascal|Pascal]]''
Line 1,080 ⟶ 1,128:
<pre>2.71828182845905</pre>
=={{header|EasyLang}}==
<syntaxhighlight lang="text">numfmt 0 5
numfmt 5 0
fact = 1
n = 2
Line 1,090 ⟶ 1,139:
e += 1 / fact
.
print e</syntaxhighlight>
</syntaxhighlight>
 
=={{header|EDSAC order code}}==
===Simple arithmetic===
Line 1,995 ⟶ 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}}==
Line 2,023 ⟶ 2,100:
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Calculating_the_value_of_e}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
'''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]]
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
In '''[https://formulae.org/?example=Calculating_the_value_of_e this]''' page you can see the program(s) related to this task and their results.
=={{header|Go}}==
{{trans|Kotlin}}
Line 2,186 ⟶ 2,278:
computed e 2.718281828459046
keyword &e 2.718281828459045</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|J}}==
Perhaps too brief:
Line 2,280 ⟶ 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}}
<syntaxhighlight lang="java">public class CalculateE {
Line 2,299 ⟶ 2,460:
{{out}}
<pre>e = 2.718281828459046</pre>
 
=={{header|Javascript}}==
Summing over a scan
Line 2,393 ⟶ 2,555:
{{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>
Line 2,400 ⟶ 2,568:
| .[0];
e #=> 2.7182818284590455</syntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
Line 2,481 ⟶ 2,650:
" " input</syntaxhighlight>
=={{header|Kotlin}}==
<syntaxhighlight lang="scalakotlin">// Version 1.2.40
 
import kotlin.math.abs
Line 2,504 ⟶ 2,673:
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}}==
<syntaxhighlight lang="scheme">
Line 2,542 ⟶ 2,728:
for .fact, .n = 1, 2 ; ; .n += 1 {
val .e0 = .e
.fact x*= .n
.e += 1 / .fact
if abs(.e - .e0) < .epsilon: break
Line 2,558 ⟶ 2,744:
e = 2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746
</pre>
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">EPSILON = 1.0e-15;
Line 2,643 ⟶ 2,830:
{{output}}
<pre>𝕖</pre>
=={{header|min}}==
{{works with|min|0.19.3}}
<syntaxhighlight lang="min">(:n (n 0 ==) ((0)) (-1 () ((succ dup) dip append) n times) if) :iota
(iota 'succ '* map-reduce) :factorial
 
=={{header|Maxima}}==
20 iota (factorial 1 swap /) '+ map-reduce print</syntaxhighlight>
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.718281828459046
 
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}}==
<syntaxhighlight lang="mk-61">П0 П1 0 П2 1 П2 1 П3
Line 2,748 ⟶ 2,949:
 
echo e</syntaxhighlight>
 
=={{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!)
Line 3,045 ⟶ 3,256:
{{out}}
<pre>e=2.718281828459046</pre>
 
=={{header|Python}}==
===Imperative===
Line 3,070 ⟶ 3,282:
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 3,277 ⟶ 3,503:
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|20222023.0709}}
<syntaxhighlight lang="raku" line># If you need high precision: Sum of a Taylor series method.
# Adjust the terms parameter to suit. Theoretically the
Line 3,283 ⟶ 3,509:
# series takes an awfully long time so limit to 500.
 
constant 𝑒 = [\+] 1.FatRat X/flat 1, |[\*/] 1.FatRat..*;
 
.say for 𝑒[500].comb(80);
Line 3,500 ⟶ 3,726:
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}}
Line 3,526 ⟶ 3,795:
0.27182818284590452353602874713526624977572470937e1
</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">const EPSILON: f64 = 1e-15;
Line 3,945 ⟶ 4,215:
{{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}}
Line 3,964 ⟶ 4,250:
Error = 4.44089209850063E-16
Number of iterations = 9</pre>
 
=={{header|Verilog}}==
<syntaxhighlight lang="verilog">module main;
Line 4,042 ⟶ 4,329:
=={{header|Wren}}==
{{trans|Go}}
<syntaxhighlight lang="ecmascriptwren">var epsilon = 1e-15
var fact = 1
var e = 2
Line 4,059 ⟶ 4,346:
e = 2.718281828459
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">real N, E, E0, F; \index, Euler numbers, factorial
Line 4,079 ⟶ 4,367:
</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");
const math = std.math;
const stdout = std.io.getStdOut().writer();
 
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
 
var n: u32 = 0;
var state: u2 = 0;
Line 4,113 ⟶ 4,402:
},
}
varconst p2: u64ov1 = undefined@mulWithOverflow(a, p1);
varif q2: u64(ov1[1] != undefined0) break;
ifconst ov2 = (@mulWithOverflowaddWithOverflow(u64ov1[0], a, p1, &p2p0) or;
if @addWithOverflow(u64, p2,ov2[1] p0,!= &p20) orbreak;
const ov3 = @mulWithOverflow(u64, a, q1, &q2) or;
if @addWithOverflow(u64,ov3[1] q2,!= q0,0) &q2))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 dec_print(stdout, p2, q2, 36);
try stdout.print("e ~= {d:>19} / {d:>19} = ", .{ p2, q2 });
try decPrint(stdout, p2, q2, 36);
try stdout.writeByte('\n');
p0 = p1;
Line 4,132 ⟶ 4,423:
}
 
fn dec_printdecPrint(ostream: anytype, num: u64, den: u64, prec: usize) !void {
// print out integer part.
try ostream.print("{}.", .{num / den});
Line 4,139 ⟶ 4,430:
// multiply by 10 could potentially overflow a u64.
//
const m: u128 = @intCast(u128, den);
var r = @as(u128, num) % m;
var dec: usize = 0; // decimal place we're in.
Line 4,146 ⟶ 4,437:
r = n % m;
dec += 1;
const ch = @intCastas(u8, @intCast(n / m)) + '0';
try ostream.writeByte(ch);
}
Line 4,195 ⟶ 4,486:
e ~= 5739439214861417731 / 2111421691000680031 = 2.718281828459045235360287471352662497
</pre>
 
=={{header|zkl}}==
{{trans|C}}
885

edits