Calculating the value of e: Difference between revisions
Content deleted Content added
m →{{header|J}}: Remove "well, duh" statement. |
Thundergnat (talk | contribs) m syntax highlighting fixup automation |
||
Line 13:
=={{header|11l}}==
{{trans|Python}}
<
V e = 2.0
V n = 0
Line 26:
print(‘Real e = ’math:e)
print(‘Error = ’(math:e - e))
print(‘Number of iterations = ’n)</
{{out}}
<pre>
Line 38:
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:
PG DC CL80' ' buffer
REGEQU
END CALCE </
{{out}}
<pre>
Line 74:
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
<
PROC Euler(REAL POINTER e)
Line 108:
Print("calculated e=") PrintRE(calc)
Print(" error=") PrintRE(diff)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Calculating_the_value_of_e.png Screenshot from Atari 8-bit computer]
Line 119:
=={{header|Ada}}==
{{trans|Kotlin}}
<
with Ada.Long_Float_Text_IO; use Ada.Long_Float_Text_IO;
Line 143:
New_Line;
end Euler;</
{{out}}
<pre>
Line 151:
=={{header|ALGOL 68}}==
{{trans|Kotlin}}
<
# calculate an approximation to e #
LONG REAL epsilon = 1.0e-15;
Line 165:
DO SKIP OD;
print( ( "e = ", fixed( e, -17, 15 ), newline ) )
END</
{{out}}
<pre>
Line 174:
For the purposes of 32 bit floating point, the value seems to stabilise after summing c. 16 terms.
<
on run
Line 271:
foldl(add, 0, xs)
end sum</
{{Out}}
<pre>2.718281828459</pre>
Or, as a single fold:
<
-- eApprox :: Int -> Float
Line 340:
end script
end if
end mReturn</
{{Out}}
<pre>2.718281828459</pre>
=={{header|Applesoft BASIC}}==
<syntaxhighlight lang=text>?"E = "EXP(1)</
{{Out}}
<pre>E = 2.71828183</pre>
Line 351:
=={{header|Arturo}}==
<
e: 2.0
e0: 0.0
Line 364:
]
print e</
{{out}}
Line 371:
=={{header|Asymptote}}==
<
real e1, e;
Line 385:
n *= n1;
}
write("The value of e = ", e);</
{{out}}
<pre>The value of e = 2.71828182845905</pre>
=={{header|AWK}}==
<
# syntax: GAWK -f CALCULATING_THE_VALUE_OF_E.AWK
BEGIN {
Line 406:
}
function abs(x) { if (x >= 0) { return x } else { return -x } }
</syntaxhighlight>
{{out}}
<pre>
Line 414:
=={{header|BASIC}}==
==={{header|BASIC256}}===
<
e1 = 0 : e = 1 / 1
Line 425:
print "The value of e = "; e
end</
{{out}}
<pre>The value of e = 2.71828182829</pre>
Line 432:
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
<
e! = 1 / 1
Line 443:
LOOP
PRINT "The value of e ="; e</
{{out}}
<pre>The value of e = 2.718282</pre>
Line 449:
==={{header|True BASIC}}===
{{works with|QBasic}}
<
LET n1 = 1
Line 462:
PRINT "The value of e ="; e
END</
{{out}}
<pre>The value of e = 2.7182818</pre>
Line 469:
{{works with|QBasic}}
{{works with|FreeBASIC| with #lang "qb"}}
<
e1 = 0 : e = 1 / 1
Line 479:
wend
print "The value of e = ", e</
{{out}}
<pre>The value of e = 2.71828</pre>
Line 486:
=={{header|Befunge}}==
Befunge has no decimal capabilities, evaluates as fractions of 10^17
<
^ _$$>\:^ ^ p12_$>+\:#^_$554**/@</
{{out}}
<pre>2718281828459045</pre>
Line 493:
=={{header|Burlesque}}==
<
blsq ) 70rz?!{10 100**\/./}ms36.+Sh'.1iash
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274
</syntaxhighlight>
=={{header|C}}==
===solution 1===
<
#include <math.h>
Line 539:
return 0;
}</
{{output}}
<pre>
Line 552:
===solution 2===
{{trans|Kotlin}}
<
#include <math.h>
Line 569:
printf("e = %.15f\n", e);
return 0;
}</
{{output}}
Line 577:
=={{header|C sharp|C#}}==
<
namespace CalculateE {
Line 596:
}
}
}</
{{out}}
<pre>e = 2.718281828459050</pre>
Line 602:
===Using Decimal type===
<
class Calc_E
Line 619:
Console.WriteLine(CalcE()); // Decimal precision result
}
}</
{{out}}
<pre>2.71828182845905
Line 626:
{{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 648:
WriteLine("partial: {0}...{1}", es.Substring(0, 46), es.Substring(es.Length - 45));
}
}</
{{out}}
<pre>2.71828182845905
Line 658:
=={{header|C++}}==
{{trans|C}}
<
#include <iomanip>
#include <cmath>
Line 677:
cout << "e = " << setprecision(16) << e << endl;
return 0;
}</
{{output}}
Line 685:
=={{header|Clojure}}==
<
;; Calculating the number e, euler-napier number.
;; We will use two methods
Line 717:
(time (with-precision 110 (method-e 200M)))
</syntaxhighlight>
<pre>
Line 726:
=={{header|COBOL}}==
{{trans|C}}
<
IDENTIFICATION DIVISION.
PROGRAM-ID. EULER.
Line 751:
DISPLAY RESULT-MESSAGE.
STOP RUN.
</syntaxhighlight>
{{out}}
<pre>
Line 759:
=={{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 768:
160 : E = E + 1/F
170 NEXT I
180 PRINT "AFTER" N "ITERATIONS, E =" E</
{{Out}}
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:
<
(use-package :computable-reals)
Line 788:
(setq e (+ e (/ 1 f))))
(format t "After ~a iterations, e = " *iterations*)
(print-r e 2570))</
{{Out}}
Line 797:
=={{header|D}}==
<
import std.stdio;
Line 813:
} while (abs(e - e0) >= EPSILON);
writefln("e = %.15f", e);
}</
{{out}}
<pre>e = 2.718281828459046</pre>
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):
<
2574k [ precision to use during computation ]sx
1 d se sf [ set e and f to 1 ]sx
Line 840:
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</
{{Out}}
Line 889:
{{Trans|C}}
<
program Calculating_the_value_of_e;
Line 931:
end.
</syntaxhighlight>
{{out}}
Line 942:
{{trans|Swift}}
<
func abs(n) {
if n < 0 {
Line 970:
}
print(calculateE())</
{{out}}
Line 977:
=={{header|EasyLang}}==
<syntaxhighlight lang=text>numfmt 0 5
fact = 1
n = 2
Line 987:
e += 1 / fact
.
print e</
=={{header|EDSAC order code}}==
Line 997:
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 1,082:
E14Z [relative address of entry]
PF [enter with accumulator = 0]
</syntaxhighlight>
{{out}}
<pre>
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).
<
[Calculate e by multilength variables.
EDSAC program, Initial Orders 2.
Line 1,392:
E 184 Z [define entry point]
P F [acc = 0 on entry]
</syntaxhighlight>
{{out}}
<pre>
Line 1,427:
===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,457:
=={{header|Emacs Lisp}}==
<
"Compute factorial of i."
(apply #'* (number-sequence 1 i)))
Line 1,466:
(mapcar #'factorial (number-sequence 1 iter)))))
(compute-e 20)</
{{output}}
<pre>
Line 1,472:
=={{header|Epoxy}}==
<
var E:1,F:1
loop I:1;I<=P;I+:1 do
Line 1,482:
log(CalculateE(100))
log(math.e)</
{{out}}
<pre>2.7182818284590455
Line 1,495:
{{Works with|Office 365 betas 2021}}
<
=LAMBDA(n,
INDEX(
Line 1,518:
1
)
)</
and also assuming the following generic bindings in the Name Manager for the WorkBook:
<
=LAMBDA(op,
LAMBDA(a,
Line 1,568:
)
)
)</
{{Out}}
Line 1,671:
=={{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>
Line 1,686:
=={{header|Factor}}==
{{works with|Factor|0.98}}
<
IN: rosetta-code.calculate-e
CONSTANT: terms 20
terms <iota> [ n! recip ] map-sum >float .</
{{out}}
<pre>
Line 1,699:
=={{header|FOCAL}}==
{{trans|ZX Spectrum Basic}}
<
1.2 F X=1,10; D 2
1.3 Q
Line 1,705:
2.1 S E=E+1/K
2.2 S K=K*X
2.3 T %2,X,%6.5,E,!</
{{output}}
<pre>*G
Line 1,736:
* Output the next digit: The final quotient is the next digit of e.
<
: int-array create cells allot does> swap cells + ;
Line 1,756:
0 .r
LOOP ;
</syntaxhighlight>
{{out}}
<pre>
Line 1,766:
=={{header|Fortran}}==
<
Program eee
implicit none
Line 1,782:
write(*,*) ' polynomial ', ee
end Program eee</
{{out}}
<pre>
Line 1,794:
=={{header|FreeBASIC}}==
===Normal basic===
<
' compile with: fbc -s console
Line 1,815:
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,865:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>The value of e = 2.71828182845904523536028747135266249775724709369996</pre>
Line 1,878:
=={{header|Furor}}==
<
###sysinclude math.uh
1.0e-15 sto EPSILON
Line 1,896:
{ „e0” }
{ „n” }
</syntaxhighlight>
{{out}}
Line 1,907:
=={{header|Go}}==
{{trans|Kotlin}}
<
import (
Line 1,930:
}
fmt.Printf("e = %.15f\n", e)
}</
{{out}}
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.
<
def φ = 1/ε
Line 1,958:
}
def e = generateAddends().sum()</
'''Test: '''
<
'''Output: '''
<pre>2.718281828459045
Line 1,968:
For the purposes of 64 bit floating point precision, the value seems to stabilise after summing c. 17-20 terms.
<
eApprox :: Int -> Double
Line 1,976:
--------------------------- TEST -------------------------
main :: IO ()
main = print $ eApprox 20</
{{Out}}
<pre>2.7182818284590455</pre>
Line 1,982:
Or equivalently, in a single fold:
<
eApprox n =
Line 1,995:
--------------------------- TEST -------------------------
main :: IO ()
main = print $ eApprox 20</
{{Out}}
<pre>2.7182818284590455</pre>
Line 2,001:
Or in terms of iterate:
<
------------------- APPROXIMATIONS TO E ------------------
Line 2,016:
--------------------------- TEST -------------------------
main :: IO ()
main = print $ approximatEs !! 17</
{{Out}}
<pre>2.7182818284590455</pre>
Line 2,026:
For Icon, the EPSILON preprocessor constant would need to be an inline constant where tested, or set in a variable.
<
procedure main()
Line 2,043:
write("computed e ", e)
write("keyword &e ", &e)
end</
{{out}}
Line 2,051:
=={{header|IS-BASIC}}==
<
110 LET E1=0:LET E,N,N1=1
120 DO WHILE E<>E1
Line 2,057:
140 LET N1=N1+1:LET N=N*N1
150 LOOP
160 PRINT "The value of e =";E</
{{Out}}
<pre>The value of e = 2.71828183</pre>
Line 2,138:
=={{header|Java}}==
{{trans|Kotlin}}
<
public static final double EPSILON = 1.0e-15;
Line 2,153:
System.out.printf("e = %.15f\n", e);
}
}</
{{out}}
<pre>e = 2.718281828459046</pre>
Line 2,159:
=={{header|Javascript}}==
Summing over a scan
<
"use strict";
Line 2,213:
// MAIN ---
return main();
})();</
<pre>2.7182818284590455</pre>
Or as a single fold/reduce:
<
"use strict";
Line 2,248:
// MAIN ---
return main();
})();</
{{Out}}
<pre>2.7182818284590455</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 2,264:
'''Module''':
<
export NeperConst
Line 2,288:
end
end # module NeperConstant</
'''Main''':
<
println(NeperConst{F}())
end</
{{out}}
Line 2,302:
=={{header|K}}==
<syntaxhighlight lang=K>
/ Computing value of e
/ ecomp.k
Line 2,309:
evalue:{1 +/(1.0%)'fact' 1+!20}
evalue[]
</syntaxhighlight>
{{out}}
Line 2,318:
=={{header|Klingphix}}==
<syntaxhighlight lang=text>%e0 %e %n %fact %v
0 !e0 2 !e 0 !n 1 !fact
Line 2,341:
"Number of iterations = " $n printOp
" " input</
=={{header|Kotlin}}==
<
import kotlin.math.abs
Line 2,361:
while (abs(e - e0) >= EPSILON)
println("e = %.15f".format(e))
}</
{{output}}
Line 2,369:
=={{header|Lambdatalk}}==
<
1) straightforward
Line 2,395:
{euler 1 17}
-> 2.7182818284590455
</syntaxhighlight>
=={{header|langur}}==
{{trans|Go}}
<
val .epsilon = 1.0e-104
Line 2,415:
# compare to built-in constant e
writeln " e = ", e</
{{out}}
Line 2,425:
=={{header|Lua}}==
<
fact = 1
Line 2,439:
until (math.abs(e - e0) < EPSILON)
io.write(string.format("e = %.15f\n", e))</
{{out}}
<pre>e = 2.718281828459046</pre>
Line 2,446:
Using @ for Decimal, and ~ for Float, # for Currency (Double is the default type for M2000)
<
Module FindE {
Function comp_e (n){
Line 2,464:
}
FindE
</syntaxhighlight>
{{out}}
Line 2,475:
As a lambda function (also we use a faster For, using block {})
<
comp_e=lambda (n)->{n/=28:For i=27to 1 {n=1+n/i}:=n}
</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,495:
# 13823891428306770374331665289458907890372191037173036666131/5085525453460186301777867529962655859538011626631066055111
# 2.7182818284590452353602874713526624977572470937000</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
{{output}}
<pre>
Line 2,504:
</pre>
<
<
<syntaxhighlight lang
or even just
<syntaxhighlight lang
input as <syntaxhighlight lang
{{output}}
<pre>𝕖</pre>
Line 2,515:
=={{header|min}}==
{{works with|min|0.19.3}}
<
(iota 'succ '* map-reduce) :factorial
20 iota (factorial 1 swap /) '+ map-reduce print</
{{out}}
<pre>
Line 2,525:
=={{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,568:
ReadChar
END CalculateE.</
=={{header|Myrddin}}==
<
const main = {
Line 2,586:
;;
std.put("e: {}\n", e)
}</
=={{header|Nanoquery}}==
{{trans|Python}}
<
e = 2
n = 0
Line 2,602:
println "Computed e = " + e
println "Number of iterations = " + n</
{{out}}
<pre>
Line 2,610:
=={{header|Nim}}==
<
var fact : int64 = 1
var e : float64 = 2.0
Line 2,622:
e = e + 1.0 / fact.float64
echo e</
=={{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,659:
{$IFDEF WINDOWS}readln;{$ENDIF}
end.
</syntaxhighlight>
{{out}}
<pre>calc e = 2.718281828459045 intern e= 2.718281828459045</pre>
Line 2,665:
=={{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,677:
print "Computed " . substr($e, 0, 41), "\n";
print "Built-in " . e, "\n";</
{{out}}
<pre>Computed 2.718281828459045235360287471352662497757
Line 2,686:
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,711:
}
printf "\n%s\n", subset $e, 0,102;</
{{out}}
<pre>numerator: 32561133701373476427912330475884581607687531065877567210421813247164172713574202714721554378508046501
Line 2,720:
=={{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>
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;">"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,745:
=={{header|Phixmonti}}==
{{trans|Python}}
<
1e-15 var v
Line 2,768:
"Real e = " rE tostr printOp
"Error = " rE e - printOp
"Number of iterations = " n printOp</
{{out}}
<pre>
Line 2,778:
=={{header|PicoLisp}}==
<
(let (F 1 E 2.0 E0 0 N 2)
(while (> E E0)
Line 2,784:
(inc 'E (*/ 1.0 F))
(inc 'N) )
(prinl "e = " (format E *Scl)) )</
{{out}}
<pre>e = 2.718281828459046</pre>
Line 2,790:
=={{header|PowerShell}}==
{{trans|Python}}
<
$e = 2
$n = 0
Line 2,804:
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,813:
=={{header|Processing}}==
Updated to show that computed value matches library value after 21 iterations.
<
void setup() {
double e = 0;
Line 2,838:
}
</syntaxhighlight>
{{out}}
<pre>
Line 2,854:
===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,876:
?- main.
</syntaxhighlight>
{{Out}}
<pre>
Line 2,884:
===Arbitrary-precision solution===
<
% John Devou: 26-Nov-2021
% Simple program to calculate e up to n decimal digits.
Line 2,906:
?- main.
</syntaxhighlight>
{{Out}}
<pre>
Line 2,922:
=={{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,932:
=={{header|Python}}==
===Imperative===
<
#Implementation of Brother's formula
e0 = 0
Line 2,947:
print "Real e = "+str(math.e)
print "Error = "+str(math.e-e)
print "Number of iterations = "+str(n)</
{{out}}
<pre>
Line 2,960:
{{Works with|Python|3.7}}
<
from itertools import (accumulate, chain)
Line 3,007:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>2.7182818284590455</pre>
Or in terms of a single fold/reduce:
<
from functools import reduce
Line 3,043:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>2.7182818284590455</pre>
=={{header|R}}==
<syntaxhighlight lang=R>
options(digits=22)
cat("e =",sum(rep(1,20)/factorial(0:19)))
</syntaxhighlight>
{{Out}}
<pre>
Line 3,062:
Using the Quackery bignum rational arithmetic library.
<
[ swap number$
Line 3,086:
3 times drop temp release ] is approximate-e ( n n --> )
55 70 approximate-e</
{{Out}}
Line 3,151:
=={{header|Racket}}==
<
(require math/number-theory)
Line 3,161:
(displayln e)
(displayln (real->decimal-string e 20))
(displayln (real->decimal-string (- (exp 1) e) 20))))</
{{out}}
<pre>82666416490601/30411275102208
Line 3,170:
(formerly Perl 6)
{{works with|Rakudo|2018.03}}
<syntaxhighlight lang=raku
# Adjust the terms parameter to suit. Theoretically the
# terms could be ∞. Practically, calculating an infinite
Line 3,183:
# Or, if you don't need high precision, it's a built-in.
say e;</
{{out}}
<pre>2.718281828459045235360287471352662497757247093699959574966967627724076630353547
Line 3,217:
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 3,231:
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 3,321:
===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 3,336:
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 3,356:
Else ok=ok+1
End
Say ok 'comparisons are ok' </
{{out}}
<pre>J:\>rexx compez
Line 3,362:
=={{header|Ring}}==
<
# Project : Calculating the value of e
Line 3,386:
return n * factorial(n-1)
ok
</syntaxhighlight>
Output:
<pre>
Line 3,397:
=={{header|Ruby}}==
{{trans|C}}
<
fact = 1
e = 2
Line 3,411:
puts e
</syntaxhighlight>
Built in:
<
puts BigMath.E(50).to_s # 50 decimals
</syntaxhighlight>
{{out}}
<pre>
Line 3,423:
=={{header|Rust}}==
<
fn main() {
Line 3,439:
}
println!("e = {:.15}", e);
}</
{{out}}
<pre>e = 2.718281828459046</pre>
Line 3,445:
=={{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,459:
println(f"ℯ = ${iter(1L, 2.0, 2, 0)}%.15f")
}</
=={{header|Scheme}}==
{{trans|JavaScript}}
<
(import (rnrs))
Line 3,500:
(display (e))
(newline)</
===High Precision===
{{works with|Chez Scheme}}
Line 3,508:
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.
<
; n-1
; exp(z) ~ SUM ( z^k / k! )
Line 3,525:
(if (<= n 0)
1
(* n (fact (1- n))))))</
'''Convert for Display'''
<
; 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.
Line 3,568:
(if (null? frc-list)
int-part
(format "~a.~a" int-part (list->string frc-list))))))</
'''The Task'''
<
(let*
Line 3,581:
(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)))</
{{out}}
<pre>Computing exp(1) using 75 terms...
Line 3,596:
The program below computes e:
<
include "float.s7i";
Line 3,615:
until abs(e - e0) < EPSILON;
writeln("e = " <& e digits 15);
end func;</
{{out}}
Line 3,624:
=={{header|Sidef}}==
<
sum(0..n, {|k| 1/k! })
}
say calculate_e()
say calculate_e(69).as_dec(100)</
{{out}}
<pre>
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:
<
var t = n*log(10)
(n + 10).bsearch_le { |k|
Line 3,648:
var n = f(10**k)
say "Sum_{k=0..#{n}} 1/k! = e correct to #{10**k->commify} decimal places"
}</
{{out}}
<pre>
Line 3,664:
=={{header|Standard ML}}==
<
let
val eps = 1.0e~15
Line 3,679:
in
calcToEps'(2.0, 1.0, 1.0, 2.0)
end;</
{{out}}
Line 3,693:
{{trans|C}}
<
Line 3,711:
}
print(String(format: "e = %.15f\n", arguments: [calculateE()]))</
{{out}}
Line 3,719:
=={{header|Tcl}}==
=== By the power series of exp(x) ===
<
set ε 1.0e-15
set fact 1
Line 3,732:
set e [expr $e + 1.0/$fact]
}
puts "e = $e"</
{{Out}}
<pre>
Line 3,739:
=== 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,788:
calcE 17
</syntaxhighlight>
{{out}}
<pre>
Line 3,797:
=={{header|TI-83 BASIC}}==
Guided by the Awk version.
<
2->N
2->E
Line 3,809:
End
Disp E
</syntaxhighlight>
{{Out}}
<pre>2.718281828</pre>
Line 3,815:
=={{header|VBScript}}==
{{Trans|Python}}
<
While (e - e0) > 1E-15
e0 = e
Line 3,826:
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,834:
=={{header|Verilog}}==
<
real n, n1;
real e1, e;
Line 3,853:
$finish ;
end
endmodule</
{{out}}
<pre>The value of e = 2.71828</pre>
Line 3,860:
{{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,878:
WriteLine("partial: {0}...{1}", es.Substring(0, 46), es.Substring(es.Length - 45))
End Sub
End Module</
{{out}}
<pre>2.71828182845905
Line 3,887:
=={{header|Vlang}}==
{{trans|Go}}
<
const epsilon = 1.0e-15
Line 3,904:
}
println("e = ${e:.15f}")
}</
{{out}}
Line 3,913:
=={{header|Wren}}==
{{trans|Go}}
<
var fact = 1
var e = 2
Line 3,924:
if ((e - e0).abs < epsilon) break
}
System.print("e = %(e)")</
{{out}}
Line 3,932:
=={{header|XPL0}}==
<
[Format(1, 16); \show 16 places after decimal point
N:= 1.0; E:= 1.0; F:= 1.0;
Line 3,943:
RlOut(0, E); CrLf(0);
IntOut(0, fix(N)); Text(0, " iterations");
]</
{{out}}
Line 3,953:
=={{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.
<
const std = @import("std");
const math = std.math;
Line 4,023:
}
}
</syntaxhighlight>
{{Out}}
<pre>
Line 4,071:
=={{header|zkl}}==
{{trans|C}}
<
fact,e,n := 1, 2.0, 2;
do{
Line 4,078:
e+=1.0/fact;
}while((e - e0).abs() >= EPSILON);
println("e = %.15f".fmt(e));</
{{out}}
<pre>
Line 4,086:
=={{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 4,094:
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}}
|