Useful GNU bc functions

Plain Text

Public Domain

Download (right click, save as, rename as appropriate)

Embed

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# A set of useful functions (and a constant) for use in GNU bc 1.06+

# If BC_ENV_ARGS is set appropriately, this file should be loaded automatically
# when bc is invoked.  Also, the -l option is needed so that the few predefined
# functions that exist will be loaded automatically, but you're using that anyway,
# right?

pi = 4 * a(1)

# Wrapper functions with normal names:
define sin(x) { return (s(x)) }
define cos(x) { return (c(x)) }
define atan(x) { return (a(x)) }
define exp(x) { return (e(x)) }
define log(x) { return (l(x)) }

define tan(x) { return (s(x) / c(x)) }
define acos(x) { return (atan2(sqrt(1 - x ^ 2), x)) }
define asin(x) { return (atan2(x, sqrt(1 - x ^ 2))) }

define atan2(y, x) {
 auto z
 if (x == 0) { if (y >= 0) return (pi/2) else return (-pi/2) }
 z = a(y/x)
 if (x < 0) { if (z < 0) z += pi else z -= pi }
 return z
}

define deg2rad(x) { return (x / 180 * pi) }
define rad2deg(x) { return (x / pi * 180) }

define pow(b, x) { return (e(l(b) * x)) }

define quadratic(a, b, c) {
 # "Support" for arrays in bc (both POSIX and GNU) is incredibly crippled, so
 # pairs of solutions to quadratic equations cannot be returned directly.
 auto d
 d = sqrt(b^2 - 4*a*c)
 q1 = (-b + d)/(2*a)
 q2 = (-b - d)/(2*a)
 print "  q1 = ", q1, "\n  q2 = ", q2, "\n"
}