LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   square root of number using sqrt and/or awk (https://www.linuxquestions.org/questions/programming-9/square-root-of-number-using-sqrt-and-or-awk-660267/)

skuz_ball 08-04-2008 02:41 AM

square root of number using sqrt and/or awk
 
Hi all,

I'm trying to get the square root of a number and have used a couple of methods but neither has worked for me.

First method:

Quote:

sqrt($number)

Second method:

Quote:

awk '{print sqrt($number)}'

I have read somewhere that I must include <math.h> but am not exactly sure of what this is referring to and haven't seen this in any of the example scripts I have looked at. I am trying to write this using korn shell. Any help would be greatly appreciated.

Mr. C. 08-04-2008 02:44 AM

How about:

echo sqrt "($number)" | bc

skuz_ball 08-04-2008 02:58 AM

thanks heaps mate!

ghostdog74 08-04-2008 03:54 AM

Quote:

Originally Posted by skuz_ball (Post 3235883)
Hi all,

I'm trying to get the square root of a number and have used a couple of methods but neither has worked for me.

First method:




Second method:




I have read somewhere that I must include <math.h> but am not exactly sure of what this is referring to and haven't seen this in any of the example scripts I have looked at. I am trying to write this using korn shell. Any help would be greatly appreciated.

you need BEGIN in you awk script since there's no file input
Code:

awk 'BEGIN{print sqrt(400)}'
# awk 'BEGIN{print 400**0.5}'

next time when it doesn't work, don't just say it doesn't work. Describe any errors or strange phenomena clearly.

matthewg42 08-04-2008 04:18 AM

The math.h thing is for when you are writing a program in C. If you are using shell script, you will need to use some external program, as most shells do not include a built-in square root command.

bc is probably the best bet here as it is a very small program (so it is quicker to invoke than other programs), and it can give you a lot of precision, or as little as you want.

bc reads from standard input, so you can echo an expression to evaluate like these examples:
Code:

result1=$(echo "3 + 5" | bc -l)
result2=$(echo "sqrt(3)" | bc -l)



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