Home > Back-end >  AWK: Getting nan when calculating power of number
AWK: Getting nan when calculating power of number

Time:01-07

Problem when using variable

echo ""| awk '{
x=-0.35
print x^1.35
print -0.35^1.35
}'

Result

 nan
-0.242377

Using GNU awk

CodePudding user response:

The output is correct.

The power operator ^ has higher precedence than the negation operator. Therefore, x^1.35 is (-0.35)^1.35 (a negative number to a non-integer power is a complex number, interpreted as a -nan), but -0.35^1.35 is -(0.35^1.35), a negated positive power of a positive number.

CodePudding user response:

Please see the answer from DYZ. My answer now looks a bit funny, but I think it should be kept for educational purposes for at least a few days.


Actually, both of your expressions produce nan, when properly parenthesized to yield identical math operations.

echo ""| awk '{ x=-0.35; print x^1.35; print (-0.35)^1.35; x=0.35; print x^1.35; print (0.35)^1.35; }'
 nan
 nan
0.242377
0.242377

And Perl has the same bug:

perl -le '$x = -0.35; print $x**1.35; print "" . (-0.35)**1.35; $x = 0.35; print $x**1.35; print "" . (0.35)**1.35; '
NaN
NaN
0.242377253454738
0.242377253454738

As you might have guessed by now, negative numbers to the non-integer power produce NaN:

perl -le 'for $y (qw(0.1 0.5 1 1.35 2)) { for $x (qw(-2 -0.35 -0.1)) { print join "\t", "($x)", "**$y", $x**$y; } }' 
(-2)    **0.1   NaN
(-0.35) **0.1   NaN
(-0.1)  **0.1   NaN
(-2)    **0.5   NaN
(-0.35) **0.5   NaN
(-0.1)  **0.5   NaN
(-2)    **1     -2
(-0.35) **1     -0.35
(-0.1)  **1     -0.1
(-2)    **1.35  NaN
(-0.35) **1.35  NaN
(-0.1)  **1.35  NaN
(-2)    **2     4
(-0.35) **2     0.1225
(-0.1)  **2     0.01

I suspect that both Perl and awk use similar low-level libraries that produce NaN in such cases.

  • Related