Skip to content

Instantly share code, notes, and snippets.

@royling
Last active December 16, 2015 03:39
Show Gist options
  • Save royling/00ec8b7708358fd15cd6 to your computer and use it in GitHub Desktop.
Save royling/00ec8b7708358fd15cd6 to your computer and use it in GitHub Desktop.
Implement cube root with Newton's method.
package main
import (
"fmt"
"math/cmplx"
)
const delta = 1e-15
func Cbrt(x complex128) complex128 {
z := complex128(1.0)
for {
d := (cmplx.Pow(z, 3) - x)/cmplx.Pow(z, 2)/3
if cmplx.Abs(d) < delta {
break
}
z -= d
}
return z
}
func main() {
fmt.Println(Cbrt(2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment