Finding Absolute Value For Specified Complex Number in Golang?

Go language provides inbuilt support for basic constants and mathematical functions for complex numbers with the help of the cmplx package. You are allowed to find the absolute value of the specified complex number with the help of Abs() function provided by the math/cmplx package. So, you need to add a math/cmplx package in your program with the help of the import keyword to access the Abs() function.

Syntax:

func Abs(a complex128) float64

Let us discuss this concept with the help of the given examples:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate
// how to find absolute value
package main
  
import (
    "fmt"
    "math/cmplx"
)
  
// Main function
func main() {
  
    // Finding absolute value of
    // the specified complex number
    // Using Abs() function
    res_1 := cmplx.Abs(3 + 5i)
    res_2 := cmplx.Abs(-4 + 8i)
    res_3 := cmplx.Abs(-8 - 7i)
  
    // Displaying the result
    fmt.Println("Random Number 1:", res_1)
    fmt.Println("Random Number 2: ", res_2)
    fmt.Println("Random Number 3: ", res_3)
}

chevron_right


Output:

Random Number 1: 5.8309518948453
Random Number 2:  8.94427190999916
Random Number 3:  10.63014581273465

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate how
// to find absolute value
package main
  
import (
    "fmt"
    "math/cmplx"
)
  
// Main function
func main() {
  
    // Complex numbers
    cnumber_1 := complex(5, 7)
    cnumber_2 := complex(6, 9)
  
    // Finding absolute values
    absvalue_1 := cmplx.Abs(cnumber_1)
    absvalue_2 := cmplx.Abs(cnumber_2)
  
    // Sum of two absolute values
    res := absvalue_1 + absvalue_2
  
    // Displaying results
    fmt.Println("Complex Number 1: ", cnumber_1)
    fmt.Println("Complex Number 2: ", cnumber_2)
    fmt.Println("Sum of the absolute values of "+
                   "the given complex numbers: ")
  
    fmt.Printf("%.1f + %.1f = %.1f", absvalue_1, absvalue_2, res)
  
}

chevron_right


Output:

Complex Number 1:  (5+7i)
Complex Number 2:  (6+9i)
Sum of the absolute values of the given complex numbers: 
8.6 + 10.8 = 19.4



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.