Use math and math/cmplx
Use math and math/cmplx
math works mostly with float64 real numbers. math/cmplx provides operations on complex128 values with real and imaginary parts. Choose the numerical domain before calculating.
package main
import ( "fmt" "math")
func main() { fmt.Printf("%.1f %.1f\n", math.Sqrt(81), math.Hypot(3, 4))}Sqrt returns a square root and Hypot computes vector length from two components. Formatting precision controls displayed digits, not stored precision.
Expected output:
9.0 5.0Complex magnitude
package main
import ( "fmt" "math/cmplx")
func main() { z := complex(3.0, 4.0) fmt.Println(real(z), imag(z)) fmt.Printf("%.1f\n", cmplx.Abs(z))}Magnitude is the distance from zero in the complex plane. Use real and imag to extract components, not direct conversion to float64. Trigonometric functions in math use radians, not degrees.
Expected output:
3 45.0Try it locally
Calculate the magnitude of 5+12i and print with zero fractional digits.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Numeric engineering 03: Use math and math/cmplx
Check the lesson objective before moving on.
Which function finds a complex magnitude?
Which units does math.Sin accept?