Shell中的浮点数运算

来自Shiyin's note
Shen讨论 | 贡献2012年4月6日 (五) 01:53的版本
跳到导航 跳到搜索

with awk:

  1. x=3.1; y=3.2; echo "$x $y" | awk '{if ($1 > $2) print $1; else print $2}'

3.2 echo 3.14 + 5.16 | bc

with bc:

  1. !/bin/bash

echo "Enter value1" read value1 echo "Enter value2" read value2

Result=`echo "$Value1 > $Value2" | bc `

if [ $Result -eq 1 ] then echo "$value1 is greater" fi

> echo 3.14 + 5.16 | bc 8.30


Bash does not understand floating point arithmetic. It treats numbers containing a decimal point as strings. Some shells like zsh understand floating point. Here's a sample comparing bash and zsh. It writes a file t1, then asks bash and zsh to execute it:

  1. !/bin/sh
  2. @(#) s1 Compare bash and zsh for arithmetic.

set -o nounset cat >t1 <<'EOF'

if [ -n "$BASH_VERSION" ] then echo " From bash, version :$BASH_VERSION:" elif [ -n "$ZSH_VERSION" ] then echo " From zsh, version :$ZSH_VERSION:" else echo " Unknown shell." fi

float X Y (( X = 3.0 + 0.5 )) (( Y = 33.0 / 10.0 )) if (( $X < $Y )) # is $X less than $Y ? then echo "\$X=${X}, which is less than \$Y=${Y}" elif (( $X > $Y )) then echo "\$X=${X}, which is greater than \$Y=${Y}" fi

EOF

echo bash t1 echo zsh t1 exit 0

Producing: % ./s1

From bash, version :2.05b.0(1)-release: t1: line 12: float: command not found t1: line 13: ((: X = 3.0 + 0.5 : syntax error in expression (error token is ".0+ 0.5 ") t1: line 14: ((: Y = 33.0 / 10.0 : syntax error in expression (error token is ".0 / 10.0 ") $X=3, which is less than $Y=33

From zsh, version :4.2.4: $X=3.500000000e+00, which is greater than $Y=3.300000000e+00


Here is another example change float to integer

a=2.25 b=1.35

function f_dec2int() { n=$1 if [ "`echo $n | grep '.'`" != "" ] then echo $n | sed 's/\.//' fi }

if [ `f_dec2int $a` -lt `f_dec2int $b` ] then echo true else echo false fi

    1. `f_dec2int $a` \\ 225
    2. `f_dec2int $b` \\ 135