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))
}