Golang math.Exp() Function

Golang math.Exp() function is “used to find the e**x, where the base-e exponential of x, where x is the input parameter.”

Syntax

func Exp(x float64) float64

Parameters

x: It is the value of float64 type whose base-e exponential is to be found.

An exception to the above statements is when you pass something that is positive infinity or NAN as an argument:

  1. +Inf: If the argument has a positive infinite value, the return value will be exactly the same as the argument, i.e., +Inf.
  2. NAN: If a NAN argument is passed, the return value is also NAN.

Return value

The return type of the Exp() function is a float64, and it returns the e**x, the base-e exponential of x.

Example 1: Basic usage of math.Exp()

package main

import (
  "fmt"
  "math"
)

func main() {
  result := math.Exp(2)
  fmt.Printf("e^2 = %f\n", result)
}

Output

e^2 = 7.389056

Example 2: Using a slice of numbers

This example calculates the exponential values for a slice of numbers.

package main

import (
  "fmt"
  "math"
)

func main() {
  numbers := []float64{0, 1, 2, 3, 4}

  for _, num := range numbers {
    fmt.Printf("e^%f = %f\n", num, math.Exp(num))
  }
}

Output

Using a slice of numbers

Example 4: Passing Inf and -Inf as arguments

package main

import (
  "fmt"
  "math"
)

func main() {
  data := math.Inf(-1)
  y := math.Exp(data)
  fmt.Print(data, "'s exponential value is ", y)

  fmt.Print("\n")

  ae := math.Inf(1)
  b := math.Exp(ae)
  fmt.Print(ae, "'s exponential value is ", b)
}

Output

-Inf's exponential value is 0
+Inf's exponential value is +Inf

That’s it!

Related posts

Golang math.Dim()

Golang math.Cbrt()

Golang math.Pow()

Golang math.Ceil()

Golang math.Min()

Golang math.Floor()

Golang math.Round()

Golang math.Mod()

Leave a Comment