Calculating the value of e: Difference between revisions

Content added Content deleted
Line 2: Line 2:


;Task:
;Task:
Calculate the value of &nbsp; <big>''e''</big>.
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''.)
(<big>''e''</big> &nbsp; is also known as &nbsp; ''Euler's number'' &nbsp; and &nbsp; ''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 = one = 10 ** 1000
<syntaxhighlight lang="python">e = rfct = 10 ** 1000
fact = n = 1
n = 1
while fact < one:
while rfct:
e += one // fact
n += 1
n += 1
fact *= n
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
# at least 31 bits available, and do 2:29 bits fixed point arithmetic
# least 31 bits available, which is sufficient to store (e - 1) * 10^9


one=1000000000
prec=29 one=$((1 << prec))


e=$one fact=1 n=0
e=0 n=0 rfct=$one
while [ $fact -lt $one ]
while [ $((rfct /= (n += 1))) -ne 0 ]
do
do
e=$((one / (fact *= (n += 1)) + 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.71828182</pre>
<pre>2.718281823</pre>


=={{header|VBScript}}==
=={{header|VBScript}}==