The Exponential Function
One of my favorite exercises when learning a programming language is calculating the exponential function. Two positional parameters, two loops, and the answer is easy to check. Here it is for Bash:
#!/bin/bash
# exp: calculates the terms of the series expansion of the exponential function
x=$1
n=$2
while [ $n -gt 0 ]
do
# calculate the nominator for each term
nom=$(( $x**$n ))
# calculate the denominator for each term
m=$n
factorial=$m
while [ $m -gt 1 ]
do
m=$(( $m-1 ))
factorial=$(( $factorial*$m ))
done
denom=$factorial
n=$(( $n-1 ))
# output each term
term=$nom/$denom
echo $term
done
echo 1
Here is the output
azizcodes$ ./exp 1 9
1/362880
1/40320
1/5040
1/720
1/120
1/24
1/6
1/2
1/1
1
Bash is not suited for this kind of calculations. Let’s take it to Python to verify this sum:
>>> '''1/362880
... 1/40320
... 1/5040
... 1/720
... 1/120
... 1/24
... 1/6
... 1/2
... 1/1
... 1
... '''
'1/362880\n1/40320\n1/5040\n1/720\n1/120\n1/24\n1/6\n1/2\n1/1\n1\n'
>>> s=_
>>> s1=s.split()
>>> s1
['1/362880', '1/40320', '1/5040', '1/720', '1/120', '1/24', '1/6', '1/2', '1/1', '1']
>>> s2=[eval(p) for p in s1]
>>> s2
[2.7557319223985893e-06, 2.48015873015873e-05, 0.0001984126984126984, 0.001388888888888889, 0.008333333333333333, 0.041666666666666664, 0.16666666666666666, 0.5, 1.0, 1]
>>> sum(s2)
2.7182815255731922