go中的平方负数

Square negative number in go

我在 go 中遇到负数平方问题...

(2*(1-0.5)-4)/((4*(4-2))/(2-1))^(1/2) = -1.06066017

但是用 go 我得到 NaN

package main
import (
    "fmt"
    "math"
)

func main() {
    fmt.Print(math.Sqrt((2*(1-0.5) - 4) / ((4 * (4 - 2)) / (2 - 1))))
}

或者如果我这样使用 math.Abs

fmt.Print(math.Sqrt(math.Abs((2*(1-0.5) - 4) / ((4 * (4 - 2)) / (2 - 1)))))

我回来了:0.6123724356957不正确,正确的结果是:-1.06066017

有什么办法解决这个问题吗?

问题是:

(2*(1-0.5)-4)/((4*(4-2))/(2-1))^(1/2)

在您的计算器中计算为 (2*(1-0.5)-4) 除以 ((4*(4-2))/(2-1))^(1/2),这确实会产生 -1.06..

但是你给了 Go (2*(1-0.5)-4)/((4*(4-2))/(2-1)),这是一个负数,并告诉它计算它的平方根,这会很复杂。

所以尝试:

fmt.Print((2*(1-0.5) - 4) / math.Sqrt(((4 * (4 - 2)) / (2 - 1))))