3 ###############################################################################
4 # This script performs the same task as "slower_e_demo.sh" but with a major
5 # performance optimization. The speedup is especially noticeable on GNU
6 # emulation layers for Windows such as Cygwin and minGW, where the overhead
7 # of subshelling is quite significant.
9 # The speedup uses global storage space to simulate pass-and-return by
10 # reference so that you can capture the side effects of a function call without
11 # writing to stdout and wrapping the call in a subshell. How to use:
13 # Turn on "__shellmath_isOptimized" as shown below.
14 # Then instead of invoking "mySum = $(_shellmath_add $x $y)",
15 # call "_shellmath_add $x $y; _shellmath_getReturnValue mySum".
16 ###############################################################################
20 # Setting the '-t' flag will cause the script to time the algorithm
21 if [[ "$1" == '-t' ]]; then
22 do_timing
=${__shellmath_true}
26 if [[ $# -ne 1 ]]; then
27 echo "USAGE: ${BASH_SOURCE##*/} [-t] *N*"
28 echo " Approximates 'e' using the N-th order Maclaurin polynomial"
29 echo " (i.e. the Taylor polynomial centered at 0)."
30 echo " Specify the '-t' flag to time the main algorithm."
32 elif [[ ! "$1" =~ ^
[0-9]+$
]]; then
33 echo "Illegal argument. Whole numbers only, please."
37 __shellmath_isOptimized
=${__shellmath_true}
40 function run_algorithm
()
43 n
=0; N
=$1; zero_factorial
=1
45 # Initialize "e" to its zeroth-order term
46 _shellmath_divide
1 $zero_factorial
47 _shellmath_getReturnValue term
50 # Compute successive terms T(n) := T(n-1)/n and accumulate into e
51 for ((n
=1; n
<=N
; n
++)); do
52 _shellmath_divide
"$term" "$n"
53 _shellmath_getReturnValue term
54 _shellmath_add
"$e" "$term"
55 _shellmath_getReturnValue e
61 if (( do_timing
== __shellmath_true
)); then
62 time run_algorithm
"$1"