0

I have two numbers in scientific notation and I want to do some comparison between them in an if statement in bash. While doing so, I am getting error like bwlow: E.g:

bash-4.2$ a=10e-12
bash-4.2$ b=12e-12
bash-4.2$ if (( a > b )); then r=1; else r=0; fi
bash: ((: 10e: value too great for base (error token is "10e")

The same problem doesn't arise if a and b are integers. I see problem with floating numbers to if I use the above statement. Is there a simple way by which I can do the comparison within if statement?

1

Using "awk"

As @Theophrastus has noted above, neither bash nor bc support scientific notation.

For simple comparisons and calculations, I suggest using awk (which does handle xEy numbers):

a=10e-12
b=12e-12

r=$(awk 'BEGIN{print ('$a'>'$b')?1:0}')
echo $r

For more complex expressions, you can avoid the cumbersome quote handling and escaping by passing the variables to awk with -v, which would actually be the preferred way to do it:

r=$(awk -v a="$a" -v b="$b" 'BEGIN{print (a<b)?1:0}')

Using "bc"

There are ways to reformat your notation to the alternative form x * 10^y which is understood by bc (or you could just do it yourself), however bc has some pecularities when it comes to negative exponents (as in your example):

$ bc
10^12
1000000000000
10^-12
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.