I'm having problems to square a negative number in go...
(2*(1-0.5)-4)/((4*(4-2))/(2-1))^(1/2) = -1.06066017
but with go I get NaN
package main
import (
"fmt"
"math"
)
func main() {
fmt.Print(math.Sqrt((2*(1-0.5) - 4) / ((4 * (4 - 2)) / (2 - 1))))
}
or if I use math.Abs
like this:
fmt.Print(math.Sqrt(math.Abs((2*(1-0.5) - 4) / ((4 * (4 - 2)) / (2 - 1)))))
I got back: 0.6123724356957
that is not correct, the correct result is: -1.06066017
is there any way to work around this?
The problem is:
(2*(1-0.5)-4)/((4*(4-2))/(2-1))^(1/2)
is evaluated as (2*(1-0.5)-4)
divided by ((4*(4-2))/(2-1))^(1/2)
in your calculator, which indeed yields -1.06..
.
But you gave Go (2*(1-0.5)-4)/((4*(4-2))/(2-1))
, which is a negative number, and told it to calculate the square root of that, which would be complex.
So try:
fmt.Print((2*(1-0.5) - 4) / math.Sqrt(((4 * (4 - 2)) / (2 - 1))))