LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   calculate logarithm in bash script (http://www.linuxquestions.org/questions/programming-9/calculate-logarithm-in-bash-script-690036/)

bluesmoke 12-12-2008 04:17 AM

calculate logarithm in bash script
 
Hi I want to calculate log in bash script. I searched but could not find any bash command to directly do it. Can any one give some idea to do it in simple way

Alternatively:
I am also thinking to send the variable in C program, calculate in C and get the answer back in bash script. But I think it is a long process. as I have to do this
i) gcc -o log log.c
ii) ./log > log_result.txt
iii) then read the result from log_result.txt

Can any body suggest a simple way. Thank You

colucix 12-12-2008 04:29 AM

Writing your own C code is like to create a new linux command. You can do the first step only once, then put the executable somewhere in your path and preserve it for future uses. Step 2 can be skipped as well if the C program send the output to stdout, so that you can do something like:
Code:

my_log=$(log 8)
but beware that bash does not support floating point numbers.

A ready alternative is to use some application which has the natural log function as a built in, like awk or bc:
Code:

my_log=$(echo "l(8)" | bc -l)
my_log=$(echo 8 | awk '{printf "%11.9f\n",log($1)}'


acid_kewpie 12-12-2008 04:29 AM

http://www.phodd.net/cyrek/gnu-bc/bcfaq.php#bashlogh

unihiekka 12-12-2008 05:14 AM

Or simply a for loop where you calculate the logarithm through it's Taylor's series around a point in the vicinity, which is how it's done anyway. OK, some algorithms use better series expansions. Check Wiki for some more.

bluesmoke 12-12-2008 07:08 AM

Thanks to all of you for guiding.
http://www.phodd.net/cyrek/gnu-bc/bcfaq.php#bashlogh

@acid_kewpie : thanx..the link is usefull

arunmathew1984 12-14-2008 01:41 AM

Wow ... This thread was pretty informative. Nice work folks.
:)

Linux Archive


All times are GMT -5. The time now is 11:11 PM.