×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang math.Abs() Function with Examples

Golang | math.Abs() Function: Here, we are going to learn about the Abs() function of the math package with its usages, syntax, and examples.
Submitted by IncludeHelp, on August 29, 2021

math.Abs()

The Abs() function is an inbuilt function of the math package which is used to get the absolute value of the given value.

It accepts one parameter and returns its absolute value.

Syntax

func Abs(x float64) float64

Parameters

  • x : The number whose absolute value is to be found.

Return Value

The return type of Abs() function is a float64, it returns the absolute value of the given value.

Special cases are:

  • Abs(±Inf) = +Inf
    If the parameter is either positive or negative infinity (±Inf), it returns the positive infinity (+Inf).
  • Abs(NaN) = NaN
    If the parameter is NaN (Not-A-Number), it returns NaN.

Example 1

// Golang program to demonstrate the
// example of math.Abs() Function

package main

import (
	"fmt"
	"math"
)

func main() {
	fmt.Println(math.Abs(-2))
	fmt.Println(math.Abs(2))

	fmt.Println(math.Abs(-213.456))
	fmt.Println(math.Abs(213.456))

	fmt.Println(math.Abs(math.Inf(-3)))
	fmt.Println(math.Abs(math.Inf(3)))

	fmt.Println(math.Abs(math.NaN()))

	// square root of a negative value is NaN
	fmt.Println(math.Abs(math.Sqrt(-3)))
}

Output:

2
2
213.456
213.456
+Inf
+Inf
NaN
NaN

Example 2

// Golang program to demonstrate the
// example of math.Abs() Function

package main

import (
	"fmt"
	"math"
)

func main() {
	var x float64
	var absX float64

	x = -2
	absX = math.Abs(x)
	fmt.Println("Absolute value of", x, "is", absX)

	x = 2
	absX = math.Abs(x)
	fmt.Println("Absolute value of", x, "is", absX)

	x = -123456.78912
	absX = math.Abs(x)
	fmt.Println("Absolute value of", x, "is", absX)

	x = math.Inf(-3)
	absX = math.Abs(x)
	fmt.Println("Absolute value of", x, "is", absX)

	x = math.Inf(3)
	absX = math.Abs(x)
	fmt.Println("Absolute value of", x, "is", absX)

	x = math.Sqrt(-3)
	absX = math.Abs(x)
	fmt.Println("Absolute value of", x, "is", absX)
}

Output:

Absolute value of -2 is 2
Absolute value of 2 is 2
Absolute value of -123456.78912 is 123456.78912
Absolute value of -Inf is +Inf
Absolute value of +Inf is +Inf
Absolute value of NaN is NaN

Golang math Package Constants and Functions »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.