bc: Examples
1
1 6 Examples
1 **********
1
1 In /bin/sh, the following will assign the value of "pi" to the shell
1 variable PI.
1
1 pi=$(echo "scale=10; 4*a(1)" | bc -l)
1
1
1 The following is the definition of the exponential function used in
1 the math library. This function is written in POSIX 'bc'.
1
1
1 scale = 20
1
1 /* Uses the fact that e^x = (e^(x/2))^2
1 When x is small enough, we use the series:
1 e^x = 1 + x + x^2/2! + x^3/3! + ...
1 */
1
1 define e(x) {
1 auto a, d, e, f, i, m, v, z
1
1 /* Check the sign of x. */
1 if (x<0) {
1 m = 1
1 x = -x
1 }
1
1 /* Precondition x. */
1 z = scale;
1 scale = 4 + z + .44*x;
1 while (x > 1) {
1 f += 1;
1 x /= 2;
1 }
1
1 /* Initialize the variables. */
1 v = 1+x
1 a = x
1 d = 1
1
1 for (i=2; 1; i++) {
1 e = (a *= x) / (d *= i)
1 if (e == 0) {
1 if (f>0) while (f--) v = v*v;
1 scale = z
1 if (m) return (1/v);
1 return (v/1);
1 }
1 v += e
1 }
1 }
1
1
1 The following is code that uses the extended features of 'bc' to
1 implement a simple program for calculating checkbook balances. This
1 program is best kept in a file so that it can be used many times without
1 having to retype it at every use.
1
1
1 scale=2
1 print "\nCheck book program\n!"
1 print " Remember, deposits are negative transactions.\n"
1 print " Exit by a 0 transaction.\n\n"
1
1 print "Initial balance? "; bal = read()
1 bal /= 1
1 print "\n"
1 while (1) {
1 "current balance = "; bal
1 "transaction? "; trans = read()
1 if (trans == 0) break;
1 bal -= trans
1 bal /= 1
1 }
1 quit
1
1
1 The following is the definition of the recursive factorial function.
1
1
1 define f (x) {
1 if (x <= 1) return (1);
1 return (f(x-1) * x);
1 }
1
1