How to Find Absolute Value in Golang

The absolute value of a number is just the distance of that number from zero on the number line.

Golang absolute value

The math.Abs() is a built-in Golang library function that calculates the absolute value of a number. 

The math.Abs() function accepts a single argument, which is a floating-point number and returns the absolute value of that number.

To use the Abs() function in your script file, you must import the math package and access it using the. notation like: math.Abs().

Syntax

math.Abs(input)

Parameters

An input is a floating point value of type float64.

Return value

The Abs() function returns a floating point value of type float64.

If you pass negative or positive infinity as an argument, it will return positive infinity.

If you pass a non-numeric argument like a string, the Abs() function returns NAN.

Example

package main

import (
  "fmt"
  "math"
)

func main() {
  var data float64 = -19
  result := math.Abs(data)
  fmt.Println("Absolute Value is:", result)
}

Output

Absolute Value : 19

In this example, we defined float variable data whose value is -19, which is negative.

Using the Abs() method, we calculated the absolute value of the negative value -19, which is positive 19.

Absolute value of the positive number in Go

To calculate the absolute value of a positive number in Golang, use the math.Abs() function.

package main

import (
  "fmt"
  "math"
)

func main() {
  var data float64 = 21
  result := math.Abs(data)
  fmt.Println("Absolute Value of positive number is:", result)
}

Output

Absolute Value of positive number is: 21

Find the distance between two points

You can use the math.Abs() function to find the distance between two points in Golang.

package main

import (
  "fmt"
  "math"
)

func main() {
  x1 := 10.0
  x2 := 8.0
  y1 := 6.0
  y2 := 4.0
  distance := math.Sqrt(math.Pow(math.Abs(x1-x2), 2) + math.Pow(math.Abs(y1-y2), 2))
  fmt.Println(distance)
}

Output

2.8284271247461903

The math.Abs() function returns an error; if you directly pass an integer value to it, the value gets automatically typecasted into a float64, and the function works as intended, as displayed.

That’s it for this tutorial.

Leave a Comment