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

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

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/5a38a7fe-426b-4f94-905e-79b42dcaa611n%40googlegroups.com.

Reply via email to