Skip to content

Instantly share code, notes, and snippets.

@tetsuok
Created April 2, 2012 09:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tetsuok/2282036 to your computer and use it in GitHub Desktop.
Save tetsuok/2282036 to your computer and use it in GitHub Desktop.
An answer of the advanced exercise: complex cube roots on a tour of Go
package main
import (
"fmt"
"math/cmplx"
)
// FIXME:
// Currently calculate only real part of the input
// complex number.
func Cbrt(x complex128) complex128 {
z := 1.0
tmp := 0.0
rx := real(x)
for i := 0; i < 100000; i++ {
tmp = z - (z * z * z - rx) / (3 * z * z)
z = tmp
// DEBUG
// fmt.Printf("i = %d, %g\n", i, tmp)
}
return complex(tmp, imag(x))
}
func main() {
fmt.Println(Cbrt(2))
fmt.Println(cmplx.Pow(2, 0.3333333))
}
@francistm
Copy link

thansk for giving out these codes ~

@cyxcw1
Copy link

cyxcw1 commented Aug 23, 2013

thanks, now I know Go has the real function, oh...

@mackross
Copy link

func Cbrt(x complex128) complex128 {
    z := complex128(1)
    for i := 0; i < 10; i++ {
        z = z - (((z*z*z)-x)/(3*z*z))
    }
    return z
 }

func main() {
    fmt.Println(Cbrt(2))
    fmt.Println(cmplx.Pow(2,0.33333333333))
}

@tkintscher
Copy link

In order to take into account roots of negative and imaginary numbers, I did the following:

package main

import "fmt"
import "math/cmplx"

func Cbrt(x complex128) complex128 {
    z := complex128(1)
    if (imag(x) != 0.) || (real(x) < 0) {
        z += 1i
    }

    for i := 0; i < 30; i++ {
        z = z - (z*z*z - x)/(3*z*z)
    }

    return z
}

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

@KarthikNayak
Copy link

func Cbrt(x complex128) complex128 {
    z := complex128(1)
    for i := 0; i < 100; i++ {
        z = z - (cmplx.Pow(z,complex128(3)) - x) / (3 * cmplx.Pow(z, complex128(2)))
    }
    return z
}

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