Guide to Unix/Explanations/bc

< Guide to Unix < Explanations

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.)

Example session

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

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

Example script

This script implements Simpson's rule for integration. The function "integrate" approximates the definite 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

Explanation : Now explain these features so users can understand the script.

Basic operations

Conversions

First check default values of base for input ( ibase) and output ( obase) numbers :

ibase
10
obase
10

Note that obase and ibase are special variables which define output and input base. Obase values range from 2 to 999 and ibase values range from 2 to 16.

Then one can convert the number 12 from base 10 to base 2:[1]

$ echo 'obase=2;12' | bc

and the result is :

1100

Reference

  1. command-line calculations using bc by Rob Newcater
This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.