With the very simple code :
package main
import (
"fmt"
"math"
"math/cmplx"
)
func sqrt(x float64) string {
if x < 0 {
return fmt.Sprint(cmplx.Sqrt(complex128(x)))
}
return fmt.Sprint(math.Sqrt(x))
}
func main() {
fmt.Println(sqrt(2), sqrt(-4))
}
I get the following error message :
main.go:11: cannot convert x (type float64) to type complex128
I tried different ways, but couldn't find out how to convert a float64 to complex128 (just to be able to use cmplx.Sqrt() function on a negative number).
Which is the correct way to handle this ?
You don't really want to convert a
float64tocomplex128but rather you want to construct acomplex128value where you specify the real part.For that can use the builtin
complex()function:Using it your
sqrt()function:Try it on the Go Playground.
Note:
You can calculate the square root of a negative
floatnumber without using complex numbers: it will be a complex value whose real part is0and imaginary part ismath.Sqrt(-x)i(so the result:(0+math.Sqrt(-x)i)):