Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I calculate the log of a number using bc?

Tags:

unix

bc

This is the first time I am using bc. I want to calculate the log (base 10) of a number. How do I this?

like image 380
Bruce Avatar asked Nov 01 '11 03:11

Bruce


3 Answers

Invoke bc with the -l option (to enable the math library) like so

$ echo 'l(100)/l(10)' | bc -l
2.00000000000000000000

Use the l function which is the natural log. Take the log of the number you are interested in then divide by the natural log of 10.

like image 87
Ray Toal Avatar answered Nov 08 '22 16:11

Ray Toal


the logarithm of x in respect to base b can be computed given any logarithm function to an arbitrary base k -- that's actually pretty cool!

log_b(x) = log_k(x) / log_k(b)

e.g.

log_b(x) = ln(x) / ln(b)

if b=10:

log_10(x) = ln(x) / ln(10)

and -l in bc enables the math library

so that's why this works:

# bc -l
l(100) / l(10)
2.00000000000000000000
like image 52
Tilo Avatar answered Nov 08 '22 15:11

Tilo


If you start bc with the -l switch, then there's a function l() that calculates the natural log of its argument.

like image 6
Ernest Friedman-Hill Avatar answered Nov 08 '22 15:11

Ernest Friedman-Hill