]> git.ipfire.org Git - thirdparty/bash.git/blob - examples/shellmath/faster_e_demo.sh
bash-5.2 distribution sources and documentation
[thirdparty/bash.git] / examples / shellmath / faster_e_demo.sh
1 #!/usr/bin/env bash
2
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.
8 #
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:
12 #
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 ###############################################################################
17
18 source shellmath.sh
19
20 # Setting the '-t' flag will cause the script to time the algorithm
21 if [[ "$1" == '-t' ]]; then
22 do_timing=${__shellmath_true}
23 shift
24 fi
25
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."
31 exit 0
32 elif [[ ! "$1" =~ ^[0-9]+$ ]]; then
33 echo "Illegal argument. Whole numbers only, please."
34 exit 1
35 fi
36
37 __shellmath_isOptimized=${__shellmath_true}
38
39
40 function run_algorithm()
41 {
42 # Initialize
43 n=0; N=$1; zero_factorial=1
44
45 # Initialize "e" to its zeroth-order term
46 _shellmath_divide 1 $zero_factorial
47 _shellmath_getReturnValue term
48 e=$term
49
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
56 done
57
58 echo "e = $e"
59 }
60
61 if (( do_timing == __shellmath_true )); then
62 time run_algorithm "$1"
63 else
64 run_algorithm "$1"
65 fi
66
67 exit 0
68