Calculating the value of e: Difference between revisions
Content added Content deleted
(→Python: →UNIX Shell: simplify) |
|||
Line 2: | Line 2: | ||
;Task: |
;Task: |
||
Calculate the value of <big>''e''</big>. |
Calculate the value of <big>''e''</big>. |
||
(<big>''e''</big> is also known as ''Euler's number'' and ''Napier's constant''.) |
(<big>''e''</big> is also known as ''Euler's number'' and ''Napier's constant''.) |
||
Line 3,055: | Line 3,055: | ||
{{out}} |
{{out}} |
||
<pre>e=2.718281828459046</pre> |
<pre>e=2.718281828459046</pre> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
===Imperative=== |
===Imperative=== |
||
Line 3,083: | Line 3,084: | ||
;Using integer arithmetic only |
;Using integer arithmetic only |
||
Easily generate thousands of digits: |
Easily generate thousands of digits: |
||
<syntaxhighlight lang="python">e = |
<syntaxhighlight lang="python">e = rfct = 10 ** 1000 |
||
n = 1 |
|||
while |
while rfct: |
||
e += one // fact |
|||
n += 1 |
n += 1 |
||
e += rfct |
|||
rfct //= n |
|||
print(f"{e}\n...in {n} steps")</syntaxhighlight> |
print(f"{e}\n...in {n} steps")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,015: | Line 4,016: | ||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
<syntaxhighlight lang="sh"># POSIX requires "signed long" for shell arithmetic, so assume to have |
<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 |
||
one=1000000000 |
|||
prec=29 one=$((1 << prec)) |
|||
e= |
e=0 n=0 rfct=$one |
||
while [ $ |
while [ $((rfct /= (n += 1))) -ne 0 ] |
||
do |
do |
||
e=$(( |
e=$((e + rfct)) |
||
done |
done |
||
echo "$((e / one + 1)).$((e % one))"</syntaxhighlight> |
|||
# convert to decimal string |
|||
n=9 str=$((e >> prec)). mask=$((one + one - 1)) |
|||
while [ $((n -= 1)) -ne 0 ] |
|||
do |
|||
str=$str$(((e = ((mask >>= 1) & e) * 5) >> (prec -= 1))) |
|||
done |
|||
echo "$str" |
|||
</syntaxhighlight> |
|||
{{out}} |
{{out}} |
||
<pre>2. |
<pre>2.718281823</pre> |
||
=={{header|VBScript}}== |
=={{header|VBScript}}== |