Complex Numbers With math cmplx

Use complex128 with math/cmplx to inspect magnitude and phase, multiply by a conjugate, and take the square root of a negative real onto the imaginary axis.

GoData Integrity

Code

gosnippet
27 lines
package main

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

func main() {
	z := complex(3, 4)

	// 实部/虚部/模/辐角:3-4-5 直角三角形
	fmt.Println("real:", real(z), "imag:", imag(z))
	fmt.Println("abs:", cmplx.Abs(z))
	fmt.Println("phase:", cmplx.Phase(z))

	// 共轭相乘得到模的平方
	conj := cmplx.Conj(z)
	fmt.Println("z*conj:", real(z*conj))

	// 负实数的平方根落在虚轴上
	root := cmplx.Sqrt(-4)
	fmt.Println("sqrt(-4):", real(root), imag(root))

	// 欧拉公式:e^{iπ} 的实部为 -1
	fmt.Println("re(e^{iπ}):", real(cmplx.Exp(complex(0, math.Pi))))
}

A close look at the run

Complex Numbers With math cmplx comes down to the function main.

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.

Using it

Signature: func main()

Running the file prints labeled results such as real:, abs:, phase: — each operation’s effect is visible in the output.

Key statements

root := cmplx.Sqrt(-4)

Interactive Tools for This Topic

FAQ

What does Complex Numbers With math cmplx print when run?
No setup needed: run the file and look for labeled lines like `real:`, `abs:`, `phase:` in the output.