Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to calculate arccos() in bash?

Tags:

linux

bash

I need to calculate arccos() in a bash script.
gawk can calculate cos(theta) and sin(theta)
how to calculate arccos() in linux ?

like image 651
questionhang Avatar asked Dec 09 '22 09:12

questionhang


2 Answers

You can do what you want by calling out to, perl for example:

acos_05=`perl -E 'use Math::Trig; say acos(0.5)'`

However, as michas pointed out, why would you want to do that in bash? If you need to do anything more than adding and multiplying numbers, bash is just not the tool for the job. It never was designed to do that, it lacks builtin functions for it, and most of all, its quoting behavior (treating everything as string) makes it a pain to get anything done in practice.

I'd recommend any programming language (not shell scripting language) of your choice: Python, Ruby, Tcl, Perl, ...; all of them are better languages than bash.

like image 65
Christian Aichinger Avatar answered Dec 11 '22 07:12

Christian Aichinger


By using command line tool bc and refer to Advantage Bash, arccosine function is shown as below while $1 is first argument for arccos() function.

arccos ()
{
    scale=3
    if (( $(echo "$1 == 0" | bc -l) )); then
        echo "a(1)*2" | bc -l
    elif (( $(echo "(-1 <= $1) && ($1 < 0)" | bc -l) )); then
        echo "scale=${scale}; a(1)*4 - a(sqrt((1/($1^2))-1))" | bc -l
    elif (( $(echo "(0 < $1) && ($1 <= 1)" | bc -l) )); then
        echo "scale=${scale}; a(sqrt((1/($1^2))-1))" | bc -l
    else
        echo "input out of range"
        return 1
    fi
}
like image 36
V-SHY Avatar answered Dec 11 '22 09:12

V-SHY