BC

Convert between numerical bases

#!/bin/bash                                                
printf "hex2dec=";echo "ibase=16;$1"|bc                         
printf "dec2hex=";echo "obase=16;$1"|bc                         
printf "oct2dec=";echo "ibase=8;$1"|bc                          
printf "dec2oct=";echo "obase=8;$1"|bc


 

Pi

Using bc to crank out pi. The answer becomes more trustworthy the longer you let bc think about it.

#!/bin/bash
echo “scale=$1;a(1)*4” | bc -l

Calculate absolute magnitude of Sirius

  • Visual magnitude = -1.46
  • Distance = 8.6 light-years

$ echo ‘mvis=-1.46; dist=8.6; mvis-5*((l(dist/3.26156)/l(10))-1)’ |bc -l

1.43463460507643045915

Calculate absolute magnitude of Tau Ceti

  • Visual magnitude = 3.5
  • Distance = 11.912

$ echo ‘mvis=3.5; dist=11.912; mvis-5*((l(dist/3.26156)/l(10))-1)’ |bc -l

5.68720343757367040805

Doubly-recursive Fibonacci function in bc (used here to zero in on phi, the Golden Mean):

define fibonacci(n) {if((n==1)||(n==0)) {return(n);} else {return(fibonacci(n-1)+fibonacci(n-2));}}

Calculate the square root of 2 to 2,500 decimal places:

bc
scale=2500
sqrt(2)