Find n-th root of a big number

i can’t find get n-th root in document of go big package so i decided to do it myself using newton’s method. i found a solution at https://www.geeksforgeeks.org/n-th-root-number/ and start to implement in go. but my code only work fine for base 2. other base result gone too far from correct.

Anyone could show me where am i wrong.

Here’s my code

package main

import (
	"fmt"
	"math/big"
	"math/rand"
)

// PowFloat return x^n
func PowFloat(x *big.Float, n int64) *big.Float {
	result := new(big.Float).SetInt64(1)
	for i := 0; i < int(n); i++ {
		result.Mul(result, x)
	}
	return result
}

// GetNthRoothFloat get nth root of a using newton's method
func GetNthRoothFloat(a *big.Float, n int64) *big.Float {
	N := new(big.Float).SetInt64(n)
	xPre := new(big.Float).SetInt64(int64(rand.Intn(10) + 1))
	eps := new(big.Float).SetFloat64(0.00000000001)
	delX := new(big.Float).SetInt64(2147483647)
	xK := new(big.Float).SetInt64(0)

	for delX.Cmp(eps) > 0 {
		t1 := new(big.Float).Sub(N, new(big.Float).SetFloat64(1.0)) // t1 = n-1
		t1 = t1.Mul(t1, xPre)                                       // t1 = (N-1) * xPre
		t2 := new(big.Float).Quo(a, PowFloat(xPre, n-1))            // t2 = a/( xPre^(n-1) )
		t3 := new(big.Float).Add(t1, t2)                            // t3 = t1 + t2
		xK.Quo(t3, N)
		delX = new(big.Float).Sub(xK, xPre)
		delX.Abs(delX)
		xPre = xK.Copy(xK)
	}
	return xK
}

func main() {
	t := new(big.Float).SetInt64(64)
	fmt.Println(GetNthRoothFloat(t, 3))
}

The formula is

x(K + 1) = (1 / N) * ((N - 1) * x(K) + A / x(K) ^ (N - 1))

I think you’ve implemented that ok.

I’m dubious of your initial approximation though. Try using something nearer the correct value.

You could calculate the initial approximation with math.Pow in float64.

Printing the value each iteration should shed some light