Skip to content

Instantly share code, notes, and snippets.

@aizatto
Last active August 31, 2016 13:00
Show Gist options
  • Save aizatto/5685204 to your computer and use it in GitHub Desktop.
Save aizatto/5685204 to your computer and use it in GitHub Desktop.
http://tour.golang.org/#47 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.
package main
import "fmt"
import "math/cmplx"
func Cbrt(x complex128) complex128 {
z := complex128(2)
s := complex128(0)
for {
z = z - (cmplx.Pow(z, 3) - x)/(3 * cmplx.Pow(z, 2))
if cmplx.Abs(s - z) < 1e17 {
break
}
s = z
}
return z
}
func main() {
fmt.Println(Cbrt(2))
}
@stargt
Copy link

stargt commented Aug 31, 2016

package main

import (
    "fmt"
    "math/cmplx"
)

func Cbrt(x complex128) complex128 {
    z := x
    for cmplx.Pow(z, 3) != x {
        z = z - (z * z * z - x) / (3 * z * z)
    }
    return z
}

func main() {
    fmt.Println(Cbrt(2), "=?" ,cmplx.Pow(2, 1./3))
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment