Skip to content

Instantly share code, notes, and snippets.

@flc
Created August 28, 2013 20:20
Show Gist options
  • Save flc/6370720 to your computer and use it in GitHub Desktop.
Save flc/6370720 to your computer and use it in GitHub Desktop.
A Tour of Go - Advanced Exercise: Complex cube roots http://tour.golang.org/#48
package main
import (
"fmt"
"math/cmplx"
)
const e = 1e-10
func Cbrt(x complex128) complex128 {
/*
For cube roots, Newton's method amounts to repeating:
z = z - (z*z*z - x) / (3 * z*z)
*/
z := x
for {
new_z := z - ((cmplx.Pow(z, 3) - x) / (3 * cmplx.Pow(z, 2)))
if cmplx.Abs(new_z - z) < e {
return new_z
}
z = new_z
}
}
func main() {
x := complex128(2.0)
fmt.Println(Cbrt(x))
fmt.Println(cmplx.Pow(x, 1/3.0))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment