Bc

From Christoph's Personal Wiki
Revision as of 08:37, 28 October 2021 by Christoph (Talk | contribs) (Examples)

Jump to: navigation, search

bc is an arbitrary precision calculator language found on most Linux distributions.

bc is a language that supports arbitrary precision numbers with interactive execution of statements. There are some similarities in the syntax to the C programming language. A standard mathematics library is available by command-line option. If requested, the math library is defined before processing any files. bc starts by processing code from all the files listed on the command line in the order listed. After all files have been processed, bc reads from the standard input. All code is executed as it is read. (If a file contains a command to halt the processor, bc will never read from the standard input.)

Examples

$ echo "111111111 * 111111111" | bc  # => 12345678987654321
$ echo "sqrt(25)" | bc -qi  # => 5
$ let x=3*4-6; echo $x  # => 6
$ echo $[(10+5)/2]  # => 7
$ echo "(10+5)/2" | bc -l  # => 7.50000000000000000000
  • Convert 10MB to KB from within bash by running the following:
$ expr $((size_in_MB << 10))
$ # E.g.,
$ expr $((10MB << 10))  # => 10240
  • Cube roots:
# NOTE:
# n√x = x(1/n) = e(ln x)/n
# x^y=e^(y * ln(x))
# ~or~
# echo "e(y*l(x))" | bc -l
# echo 'e(l({number})/3)' | bc -l

$ echo 'e(l(74088)/3)' | bc -l
41.99999999999999999967 => 42
$ echo 74088 | awk '{ print $1^(1/3) }'
42

Scientific notation

  • Get the result of 90 billion / 22 million / 365:
$ awk 'BEGIN { print 90e9/22e6/365 }' # => 11.208
$ awk 'BEGIN { printf "%.4f", 90e9/22e6/365 }' # => 11.2080
  • Other methods:
$ perl -le 'print 90e9/22e6/365' # => 11.2079701120797
$ perl -e 'printf "%.4f\n", 90e9/22e6/365' # => 11.2080
$ echo "$(printf '%.4f' '90e9')/$(printf '%.4f' '22e6')/365" | bc -l # => 11.20797011207970112079

See also

External links