"bc" 外部工具转化为函数

"bc" external tool into a function

"Despite producing floating point results. Bash does not support other type of arguments than integers, so you need to rather invoke external tools like bc for your math or stick to integers only." 4.5: syntax error: invalid arithmetic operator (error token is ".5") - but the code still seems to work, why? 平时都是用bc这个外部工具修复的,现在有一个功能,不知道具体用在什么地方,能帮帮我吗?

    #!/bin/bash

function crossProduct {
  declare -a v1=("${!1}")
  declare -a v2=("${!2}") 

#Note:  Can't pass by reference, so the global variable must be used
  vectResult[0]=$(( (v1[1] * v2[2]) - (v1[2] * v2[1]) ))
  vectResult[1]=$(( - ((v1[0] * v2[2]) - (v1[2] * v2[0])) ))
  vectResult[2]=$(( (v1[0] * v2[1]) - (v1[1] * v2[0]) ))
}

vect1[0]=0.3
vect1[1]=-0.3
vect1[2]=0.1

vect2[0]=0.4
vect2[1]=0.9
vect2[2]=2.3

crossProduct vect1[@] vect2[@]
echo ${vectResult[0]} ${vectResult[1]} ${vectResult[2]}

可以传递引用,即local -n arr=:

$ function _tmp {
    local -n arr=
    for i in ${arr[@]}; do echo $i; done
}
$ TMP=(1 2 3)
$ _tmp TMP
1
2
3

现在回答bc问题;它解析一个字符串和 returns 它的值。因此,您应该将其用作:

# make sure you declare vectResult first.

function crossProduct {
  declare -a v1=("${!1}")
  declare -a v2=("${!2}") 

  vectResult[0]=$( echo "(${v1[1]} * ${v2[2]}) - (${v1[2]} * ${v2[1]}) " | bc)
  vectResult[1]=$( echo "- ((${v1[0]} * ${v2[2]}) - (${v1[2]} * ${v2[0]}))" | bc )
  vectResult[2]=$( echo "(${v1[0]} * ${v2[1]}) - (${v1[1]} * ${v2[0]})" | bc )
}

将两者结合起来我将如何实现它:

#!/bin/bash

function crossProduct {
    local -n v1=
    local -n v2=
    local result=()

    # You should remain to use bc because Bash only does integers. 
    result+=($( echo "(${v1[1]} * ${v2[2]}) - (${v1[2]} * ${v2[1]}) " | bc))
    result+=($( echo "-((${v1[0]} * ${v2[2]}) - (${v1[2]} * ${v2[0]}))" | bc ))
    result+=($( echo "(${v1[0]} * ${v2[1]}) - (${v1[1]} * ${v2[0]})" | bc ))
    echo "${result[@]}"
}

vect1[0]=0.3
vect1[1]=-0.3
vect1[2]=0.1

vect2[0]=0.4
vect2[1]=0.9
vect2[2]=2.3

vectResult=($(crossProduct vect1 vect2))
echo ${vectResult[0]} ${vectResult[1]} ${vectResult[2]}
exit 0

这会产生 -.6 -.6 .3