我正在努力比较Bash脚本中的两个浮点数。我有两个变量,例如。
let num1=3.17648e-22
let num2=1.5
现在,我想对这两个数字做一个简单的比较:
st=`echo "$num1 < $num2" | bc`
if [ $st -eq 1]; then
echo -e "$num1 < $num2"
else
echo -e "$num1 >= $num2"
fi
不幸的是,我有一些问题与num1的正确处理可以是“电子格式”。
我正在努力比较Bash脚本中的两个浮点数。我有两个变量,例如。
let num1=3.17648e-22
let num2=1.5
现在,我想对这两个数字做一个简单的比较:
st=`echo "$num1 < $num2" | bc`
if [ $st -eq 1]; then
echo -e "$num1 < $num2"
else
echo -e "$num1 >= $num2"
fi
不幸的是,我有一些问题与num1的正确处理可以是“电子格式”。
当前回答
只需将echo替换为printf(它理解浮点数):
st=$( printf '%50G < %50G\n' "$num1" "$num2" | bc -l )
其他回答
AWK和类似的工具(我在盯着你看sed…)应该被扔进旧项目的垃圾箱里,因为它们的代码是用永不读的语言写的,所以每个人都不敢碰。
或者你是一个相对罕见的需要优先考虑CPU使用优化而不是代码维护优化的项目……既然如此,那就继续吧。
如果不是,那么就使用一些可读且显式的语言,比如Python。你的程序员同事和未来的自己都会感谢你。您可以像所有其他代码一样,在Bash中使用Python代码。
num1=3.17648E-22
num2=1.5
if python -c "exit(0 if $num1 < $num2 else 1)"; then
echo "yes, $num1 < $num2"
else
echo "no, $num1 >= $num2"
fi
num1=0.555
num2=2.555
if [ `echo "$num1>$num2"|bc` -eq 1 ]; then
echo "$num1 is greater then $num2"
else
echo "$num2 is greater then $num1"
fi
Bash只处理整数数学,但是你可以像下面这样使用bc命令:
$ num1=3.17648E-22
$ num2=1.5
$ echo $num1'>'$num2 | bc -l
0
$ echo $num2'>'$num1 | bc -l
1
注意,指数符号必须是大写的。
使用KornShell。在Bash中,你可能需要单独比较小数部分:
#!/bin/ksh
X=0.2
Y=0.2
echo $X
echo $Y
if [[ $X -lt $Y ]]
then
echo "X is less than Y"
elif [[ $X -gt $Y ]]
then
echo "X is greater than Y"
elif [[ $X -eq $Y ]]
then
echo "X is equal to Y"
fi
支持所有可能的表示法的解决方案,包括大小写指数的科学表示法(例如,12.00e4):
if (( $(bc -l <<< "${value1/e/E} < ${value2/e/E}") ))
then
echo "$value1 is smaller than $value2"
fi