如何在 Bash 中比较两个浮点数? [英] How can I compare two floating point numbers in Bash?
问题描述
我正在努力比较 Bash 脚本中的两个浮点数.我有两个变量,例如
I am trying hard to compare two floating point numbers within a Bash script. I have two variables, e.g.
let num1=3.17648e-22
let num2=1.5
现在,我只想对这两个数字做一个简单的比较:
Now, I just want do a simple comparison of these two numbers:
st=`echo "$num1 < $num2" | bc`
if [ $st -eq 1]; then
echo -e "$num1 < $num2"
else
echo -e "$num1 >= $num2"
fi
不幸的是,我在正确处理 num1 时遇到了一些问题,它可能是电子格式".
Unfortunately, I have some problems with the right treatment of the num1 which can be of the "e-format".
推荐答案
更方便
使用 Bash 的数字上下文可以更方便地做到这一点:
More conveniently
This can be done more conveniently using Bash's numeric context:
if (( $(echo "$num1 > $num2" |bc -l) )); then
…
fi
说明
通过基本的计算器命令bc
返回 1 或 0.
选项-l
等价于--mathlib
;它加载标准数学库.
The option -l
is equivalent to --mathlib
; it loads the standard math library.
将整个表达式括在双括号 (( ))
之间会将这些值分别转换为 true 或 false.
Enclosing the whole expression between double parenthesis (( ))
will translate these values to respectively true or false.
请确保安装了bc
基本计算器包.
Please, ensure that the bc
basic calculator package is installed.
警告:指数符号应写成*10^
;不是E
,也不是e
.
Caveat: Exponential notation should be written as *10^
; not E
, nor e
.
例如:
$ echo "1*10^3==1000" |bc
1
然而
$ echo "1E3==1000" |bc
0
克服此bc
限制的策略在此处讨论.
Strategies to overcome this bc
limitation are discussed here.
这篇关于如何在 Bash 中比较两个浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!