Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@francistm francistm commented Aug 14, 2012

thansk for giving out these codes ~

@cyxcw1

This comment has been minimized.

Copy link

@cyxcw1 cyxcw1 commented Aug 23, 2013

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

@mackross

This comment has been minimized.

Copy link

@mackross mackross commented Nov 24, 2013

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

This comment has been minimized.

Copy link

@tkintscher tkintscher commented May 16, 2014

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

This comment has been minimized.

Copy link

@KarthikNayak KarthikNayak commented Jul 3, 2014

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
You can’t perform that action at this time.