使用shell比较两个浮点数

浮点数比较方法
本文介绍了在Shell脚本中比较浮点数大小的两种有效方法:使用bc进行数学计算及利用awk实现条件判断。这两种方法均能准确地解决浮点数比较的问题。

 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,如需转载请自行联系原作者
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值