使用shell比较两个浮点数

简介:

 I tried to compare floating point number by -gt but it says that point expecting integer value. That means it can not handle floating point number . Then i tried the following code

我想用-gt比较两个浮点数大小,但屏幕却提示期望整数数值。

这就意味着-gt不能处理浮点数。接着我使用以下代码

1
2
3
4
5
6
7
chi_square=4
if  "$chi_square>3.84"  bc  ]
then
echo  yes
else
echo  no
fi

但屏幕却输出以下错误信息:

1
2
3
line 3: [: missing `]'
File ] is unavailable.
no

Here the no is echoed but it should be yes. I think that's because of the error it's showing. can anybody help me.

这里,执行结果本该是yes,此刻却提示no。我认为或许与提示的错误信息有关,谁能帮帮我呢?

【解决办法】

1.使用bc

要想使用bc的话请参考以下用法:

1
2
3
4
5
6
7
8
chi_square=4
if  [[ $( bc  -l <<<  "$chi_square>3.84" ) - eq  1 ]];  then
    echo  'yes'
else
    echo  'no'
fi
if  [[ ` echo  "$chi_square > 3.84"  | bc ` - eq  1 ]] ; then  echo  yes ; else  echo  no ; fi

可通过bc的man手册来查看,若表达式成立则返回1。

expr1 > expr2
           The result is 1 if expr1 is strictly greater than expr2.

2.使用awk

Just use awk instead

1
2
3
4
5
awk  - v  chi_square=4  'BEGIN{print (chi_square > 3.84 ? "yes" : "no")}'
yes
 
awk  - v  chi_square=3  'BEGIN{print (chi_square > 3.84 ? "yes" : "no")}'
no

或许,你并不喜欢使用三目运算,我也提供了使用shell变量来解决此问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$ chi_square=4
awk  - v  chi_square= "$chi_square"  'BEGIN{
     if  (chi_square > 3.84) {
         print  "yes"
     }
     else  {
         print  "no"
     }
}'
yes
echo  "$chi_square"  |
awk  '{
     if  ($0 > 3.84) {
         print  "yes"
     }
     else  {
         print  "no"
     }
}'
yes
或者
echo  "$chi_square"  awk  '{print ($0 > 3.84 ? "yes" : "no")}'
yes




本文转自 xoyabc 51CTO博客,原文链接:http://blog.51cto.com/xoyabc/1747395,如需转载请自行联系原作者
相关文章
|
8月前
|
Shell Linux Perl
Shell 基本(整数、小数、浮点数)运算($[]、$(())、let、expr、awk、bc)
Shell 基本(整数、小数、浮点数)运算($[]、$(())、let、expr、awk、bc)
126 0
|
Shell Linux
Shell运算符、$((运算式))” 或 “$[运算式]、expr方法、条件判断、test condition、[ condition ]、两个整数之间比较、按照文件权限进行判断、按照文件类型进行判断
Shell运算符、$((运算式))” 或 “$[运算式]、expr方法、条件判断、test condition、[ condition ]、两个整数之间比较、按照文件权限进行判断、按照文件类型进行判断
Shell运算符、$((运算式))” 或 “$[运算式]、expr方法、条件判断、test condition、[ condition ]、两个整数之间比较、按照文件权限进行判断、按照文件类型进行判断
|
Shell Linux
Shell运算符、$((运算式))” 或 “$[运算式]、expr方法、条件判断、test condition、[ condition ]、两个整数之间比较、按照文件权限进行判断、按照文件类型进行判断
多条件判断(&& 表示前一条命令执行成功时,才执行后一条命令,|| 表示上一 条命令执行失败后,才执行下一条命令)、-eq 等于(equal) -ne 不等于(not equal)-lt 小于(less than) -le 小于等于(less equal)-gt 大于(greater than) -ge 大于等于(greater equal)注:如果是字符串之间的比较 ,用等号“=”判断相等;用“!=”判断不等。 -r 有读的权限(read)-w 有写的权限(write)-x 有执行的权限(execute)
108 1
Shell运算符、$((运算式))” 或 “$[运算式]、expr方法、条件判断、test condition、[ condition ]、两个整数之间比较、按照文件权限进行判断、按照文件类型进行判断
|
Shell
shell脚本比较运算
数值运算符
96 0
|
Shell Perl
shell脚本比较两个浮点数大小
shell脚本执行报错 -bash: 未期待的算数运算符
369 0
|
Shell Linux
linux shell之字符串的比较
linux shell之字符串的比较
182 0
|
Shell 数据安全/隐私保护 Windows
Linux-Shell脚本编程-学习-6-Shell编程-使用结构化命令-文件比较-case编程
这一片主要说test文件的比较,文件比较在日常使用的频率比较高,这里重点把每个部分都试着说说看
118 0
Linux-Shell脚本编程-学习-6-Shell编程-使用结构化命令-文件比较-case编程
|
Shell 机器学习/深度学习 Windows