]> git.ipfire.org Git - thirdparty/bash.git/blame - examples/shellmath/faster_e_demo.sh
bash-5.2 distribution sources and documentation
[thirdparty/bash.git] / examples / shellmath / faster_e_demo.sh
CommitLineData
74091dd4
CR
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
18source shellmath.sh
19
20# Setting the '-t' flag will cause the script to time the algorithm
21if [[ "$1" == '-t' ]]; then
22 do_timing=${__shellmath_true}
23 shift
24fi
25
26if [[ $# -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
32elif [[ ! "$1" =~ ^[0-9]+$ ]]; then
33 echo "Illegal argument. Whole numbers only, please."
34 exit 1
35fi
36
37__shellmath_isOptimized=${__shellmath_true}
38
39
40function 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
61if (( do_timing == __shellmath_true )); then
62 time run_algorithm "$1"
63else
64 run_algorithm "$1"
65fi
66
67exit 0
68