Last active
December 10, 2015 16:48
-
-
Save zgiber/4463321 to your computer and use it in GitHub Desktop.
A Tour of Go. Advanced Exercise: Complex cube roots.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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