Created
October 23, 2013 06:29
-
-
Save satyrius/7113470 to your computer and use it in GitHub Desktop.
A Tour of Go.
Advanced Exercise: Complex cube roots. Let's explore Go's built-in support for complex numbers via the complex64 and complex128 types. For cube roots, Newton's method amounts to repeating: Find the cube root of 2, just to make sure the algorithm works. There is a Pow function in the math/cmplx package.
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" | |
"math/cmplx" | |
) | |
func Cbrt(x complex128) complex128 { | |
z := complex128(1) | |
for i := 1; i <= 10; i++ { | |
z = z - (cmplx.Pow(z, 3) - x) / (3 * z * z) | |
} | |
return z | |
} | |
func main() { | |
fmt.Println(Cbrt(2)) | |
fmt.Println(math.Cbrt(2)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment