如何将浮点数转换为复数?

huangapple go评论68阅读模式
英文:

How to convert float to complex?

问题

使用complex()函数可以将float64类型转换为complex128类型。在这种情况下,你可以将x作为实部,0作为虚部传递给complex()函数。以下是修改后的代码:

package main

import (
	"fmt"
	"math"
	"math/cmplx"
)

func sqrt(x float64) string {
	if x < 0 {
		return fmt.Sprint(cmplx.Sqrt(complex(x, 0)))
	}
	return fmt.Sprint(math.Sqrt(x))
}

func main() {
	fmt.Println(sqrt(2), sqrt(-4))
}

这样修改后的代码将能够正确处理将float64转换为complex128的情况。

英文:

With the very simple code :

package main

import (
    &quot;fmt&quot;
	&quot;math&quot;
    &quot;math/cmplx&quot;
)

func sqrt(x float64) string {
	if x &lt; 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 ?

答案1

得分: 11

你不是真的想将float64转换为complex128,而是想构造一个指定实部的complex128值。

为此,可以使用内置的complex()函数:

func complex(r, i FloatType) ComplexType

在你的sqrt()函数中使用它:

func sqrt(x float64) string {
    if x < 0 {
        return fmt.Sprint(cmplx.Sqrt(complex(x, 0)))
    }
    return fmt.Sprint(math.Sqrt(x))
}

Go Playground上尝试一下。

注意:

你可以计算负数的平方根而不使用复数:结果将是一个实部为0,虚部为math.Sqrt(-x)i的复数值(即结果为(0+math.Sqrt(-x)i)):

func sqrt2(x float64) string {
    if x < 0 {
        return fmt.Sprintf("(0+%.15fi)", math.Sqrt(-x))
    }
    return fmt.Sprint(math.Sqrt(x))
}
英文:

You don't really want to convert a float64 to complex128 but rather you want to construct a complex128 value where you specify the real part.

For that can use the builtin complex() function:

func complex(r, i FloatType) ComplexType

Using it your sqrt() function:

func sqrt(x float64) string {
	if x &lt; 0 {
		return fmt.Sprint(cmplx.Sqrt(complex(x, 0)))
	}
	return fmt.Sprint(math.Sqrt(x))
}

Try it on the Go Playground.

Note:

You can calculate the square root of a negative float number without using complex numbers: it will be a complex value whose real part is 0 and imaginary part is math.Sqrt(-x)i (so the result: (0+math.Sqrt(-x)i)):

func sqrt2(x float64) string {
	if x &lt; 0 {
		return fmt.Sprintf(&quot;(0+%.15fi)&quot;, math.Sqrt(-x))
	}
	return fmt.Sprint(math.Sqrt(x))
}

huangapple
  • 本文由 发表于 2015年6月24日 17:13:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/31022456.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定