When performing exponential calculations using a negative number as the base, inconsistent results are returned when using the raw value as opposed to a variable containing the value.
In IRB:
1.9.3p194 :001 > -4.5 ** 0.5
=> -2.1213203435596424
1.9.3p194 :002 > foo = -4.5
=> -4.5
1.9.3p194 :003 > foo ** 0.5
=> (1.2989340843532398e-16+2.1213203435596424i)
1.9.3p194 :004 > (-4.5) ** 0.5
=> (1.2989340843532398e-16+2.1213203435596424i)
What gives? Obviously the compiler is interpreting -4.5 ** 0.5 as -(4.5 ** 0.5), but why the different behavior when using a variable?
It’s taking the first line as
which gives the negative square root of 4.5.
The second equation is equivalent to
hence the complex answer.