我需要在bash脚本中计算arccos()
gawk可以计算cos(theta)
和sin(theta)
如何在linux中计算arccos()
?
答案 0 :(得分:7)
你可以通过呼叫perl来做你想做的事,例如:
acos_05=`perl -E 'use Math::Trig; say acos(0.5)'`
然而,正如米哈斯指出的那样,你为什么要在bash中这样做呢?如果你需要做更多的事情而不是添加和乘以数字,那么bash就不是工作的工具。它从未被设计为这样做,它缺乏内置函数,而且最重要的是,它的引用行为(将所有内容都视为字符串)使得在实践中完成任何事情变得很痛苦。
我推荐您选择的任何编程语言(不是shell脚本语言):Python,Ruby,Tcl,Perl,...;所有这些都是比bash更好的语言。
答案 1 :(得分:7)
通过使用命令行工具bc
并参考Advantage Bash,反余弦函数如下所示,而$1
是arccos()
函数的第一个参数。
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
}