Explain Go's complex number types.

0138

Go has built-in support for complex numbers, which are represented using two types:

  1. complex64: This type represents a complex number where both the real and imaginary parts are 32-bit floating-point numbers (float32).

  2. complex128: This type represents a complex number where both the real and imaginary parts are 64-bit floating-point numbers (float64).

Usage

You can create complex numbers in Go using the complex function or by using the i notation. Here’s how you can work with complex numbers:

package main

import (
    "fmt"
)

func main() {
    // Initialize complex numbers
    c1 := complex(3, 4)  // 3 + 4i
    c2 := 1 + 2i         // 1 + 2i

    // Perform operations
    sum := c1 + c2       // Addition
    product := c1 * c2   // Multiplication

    // Access real and imaginary parts
    realPart := real(c1)
    imaginaryPart := imag(c1)

    // Output results
    fmt.Printf("c1: %v, c2: %v\n", c1, c2)
    fmt.Printf("Sum: %v, Product: %v\n", sum, product)
    fmt.Printf("Real part of c1: %v, Imaginary part of c1: %v\n", realPart, imaginaryPart)
}

Key Functions

  • real(c): Returns the real part of the complex number c.
  • imag(c): Returns the imaginary part of the complex number c.

Example Output

When you run the above program, you might see output like:

c1: (3+4i), c2: (1+2i)
Sum: (4+6i), Product: (-5+10i)
Real part of c1: 3, Imaginary part of c1: 4

This demonstrates how to create, manipulate, and access components of complex numbers in Go.

0 Comments

no data
Be the first to share your comment!