如何比较Bash中的两个浮点数? [英] How to compare two floating point numbers in Bash?

查看:195
本文介绍了如何比较Bash中的两个浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力比较一个bash脚本中的两个浮点数。我有变量,例如

  let num1 = 3.17648e-22 
let num2 = 1.5

现在,我只想对这两个数字进行简单比较:

  st =`echo$ num1 <$ num2| bc` 
if [$ st -eq 1];那么
echo -e$ num1< $ num2
else
echo -e$ num1> = $ num2
fi

不幸的是,我对num1的正确处理有一些问题,可能是e-format。 :



欢迎提供任何帮助,提示!

解决方案

bash只处理整数数学
,但是你可以使用 bc 命令如下:

  $ num1 = 3.17648E-22 
$ num2 = 1.5
$ echo $ num1'>'$ num2 | bc -l
0
$ echo $ num2 '>'$ num1 | bc -l
1

注意指数符号必须是大写

I am trying hard to compare two floating point numbers within a bash script. I have to 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

Unfortunately, I have some problems with the right treatment of the num1 which can be of the "e-format". :(

Any help, hints are welcome!

解决方案

bash handles only integer maths but you can use bc command as follows:

$ num1=3.17648E-22
$ num2=1.5
$ echo $num1'>'$num2 | bc -l
0
$ echo $num2'>'$num1 | bc -l
1

Note that exponent sign must be uppercase

这篇关于如何比较Bash中的两个浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆