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.go468 chars27 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.go24 chars2 lines
This means that the cube root of 8 is 2.
gistlibby LogSnag