Skip to content

Instantly share code, notes, and snippets.

@zgiber
Last active December 10, 2015 16:48
Show Gist options
  • Select an option

  • Save zgiber/4463321 to your computer and use it in GitHub Desktop.

Select an option

Save zgiber/4463321 to your computer and use it in GitHub Desktop.
A Tour of Go. Advanced Exercise: Complex cube roots.
package main
import (
"fmt"
"math"
)
func Cbrt(x complex128) complex128 {
next := func(z complex128) (complex128, float64) { //takes the result of the last iteration, and returns new result and difference
newz := z - (((z * z * z) - x) / (3 * (z * z)))
diff := math.Abs(real(z - newz))
return newz, diff
}
newz, diff := next(x)
for diff > 0.00001 {
fmt.Println(newz) // Optional to print out each iteration
newz, diff = next(newz)
}
return newz
}
func main() {
fmt.Println(Cbrt(2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment