I need to calculate arccos()
in a bash script.
gawk can calculate cos(theta)
and sin(theta)
how to calculate arccos()
in linux ?
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With