Golang math.Cbrt() Function

Go math.Cbrt() function is used to find the cubic root of a number.

Syntax

func Cbrt(x float64) float64

Parameters

x: It is a value whose cube root value is to be found.

Return value

It returns a single value of type float64. This value represents the cube root of the argument.

Below are the return values that are only used by the function under certain circumstances:

  1. NAN: Not a number, or NAN, is returned when the input argument is an undefined numeric value.
  2. +Inf: This is returned if the input value is positive infinity or equivalent.
  3. -Inf: This is returned if the input value is negative infinity or equivalent.

Example 1: Usage of math.Cbrt()

package main

import (
  "fmt"
  "math"
)

func main() {
  var x float64 = math.Cbrt(27)
  fmt.Println(x)
}

Output

3

Example 2: Newton’s Method

Newton’s method is an iterative numerical method for finding successively better approximations of a real-valued function’s roots (or zeroes).

package main

import (
  "fmt"
)

func Cbrt(x float64) float64 {
  if x == 0 {
    return 0
  }

  z := x
  for i := 0; i < 1000; i++ {
    z = (2*z + x/(z*z)) / 3
  }
  return z
}

func main() {
  fmt.Println(Cbrt(27))
}

Output

3

That’s it!

Related posts

math.Pow()

math.Ceil()

math.Min()

math.Floor()

math.Round()

math.Mod()