find the nth root of a number in go

To find the nth root of a number in Go, we can use the math.Pow function along with a simple algorithm.

Here's an implementation:

main.go
package main

import (
    "fmt"
    "math"
)

func nthRoot(x float64, n float64) float64 {
    var res float64 = 1.0
    var tol float64 = 0.0001
    var diff float64 = tol + 1

    for diff > tol {
        resNext := ((n - 1) * res / n) + (x / (n * math.Pow(res, n-1)))
        diff = math.Abs(resNext - res)
        res = resNext
    }

    return res
}

func main() {
    x := 8.0
    n := 3.0
    fmt.Printf("The %vth root of %v is: %v\n", n, x, nthRoot(x, n))
}
468 chars
27 lines

Here, the nthRoot function takes in two arguments - x and n - which are the number and the index of the root to be calculated, respectively.

The algorithm used in this implementation is an implementation of Newton-Raphson method. Within the algorithm, we keep track of two variables: res is our current result and resNext is the updated result, calculated using the equation for derivative of a given root formula. We continue iterations until the current and next result values differ by less than tolerance, and return the final result.

When we run this program, we get the following output:

main.go
The 3th root of 8 is: 2
24 chars
2 lines

This means that the cube root of 8 is 2.

gistlibby LogSnag