Guide to Unix/Explanations/bc

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

bc is an arbitrary-precision calculator language. The arbitrary-precision means that numbers can contain unlimited digits (limited by memory); most other languages limit numbers to eight bytes at most. For addition, subtraction, and multiplication, there is unlimited precision. Division stops after a certain number of decimal places (usually 0 or 20), so "bc" is often bad with very small numbers (like 10e-44).

"bc" is often called using the "-l" option, which loads the standard library (which mostly contains trig functions) and sets the number of decimal places for division to 20. (Doing trig with the default precision of 0 decimal places is not so useful.)

This is an example of a user starting bc, doing two calculations, and exitting with "quit". Note that pressing ^D (control-D) also exits.

$ bc -l
3 + 4
7
2 / 5
.40000000000000000000
quit
$

[edit] Example script


This script implements Simpson's rule for integration. The function "integrate" approximates the definate integral from "a" to "b" using "n" parabola sections. The formula for "simpson" is taken from the Wikipedia article. This example integrates the sine function, but different functions can be used by replacing f.

define f(x) {
  return s(x);
}

define simpson(a,b) {
  return ( (b-a)/6 ) * ( f(a) + 4*f((a+b)/2) + f(b) );
}

define integrate(a,b,n) {
  delta = (b - a) / n;
  result = 0;

  for(i = a; (n = n - 1) + 1; i = i + delta) {
    /*print "calling simpson(", i, ", ", i + delta, ") with n = ", n, "\n";*/
    result = result + simpson(i, i + delta);
  }
  return result;
}

Put this in a file, say "simpson", load it, and integrate f from 0 to pi (pi is "4*a(1)", 4 times arctangent of 1) with 100 intervals:

$ bc -l simpson
integrate(0, 4*a(1), 100)
2.00000000067647189101
^D

[edit] Explain

Now explain these features so users can understand the script.

  • variables and statements
  • "for" loops
  • functions ("define" and "return")
  • standard library functions ("s" is sine)

[edit] Reference