Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take a cube root in Go?

Tags:

go

I'm writing a cube root function in Google Go using Newton's method. I want to check the results using math/cmplx.Pow(), but for the life of me, I can't figure out how. How do I do this?

like image 284
Lincoln Bergeson Avatar asked Nov 07 '12 05:11

Lincoln Bergeson


People also ask

How do you take the cube root?

Cube root of a number can be found by a very simple method which is the prime factorization method. Cube root is denoted by '∛ ' symbol. Example: ∛8 = ∛(2 × 2 × 2) = 2. Since, 8 is a perfect cube number, it is easy to find the cube root of a number.


3 Answers

Have you tried myCubicRootOfx = Pow(x, 1.0/3) ?

edited: thanks to Jason McCreary comment:
We cannot use 1/3 as the 2nd parameter to Pow as this is a integer division and hence doesn't produce the expected 1/3 value. By using 1.0/3 or 1/3.0 etc. we effectively produce a float with the 0.333333... value.

like image 129
mjv Avatar answered Nov 15 '22 08:11

mjv


I wrote the cube root function using Newton's method as part of the Go Tour Exercise 47. Perhaps the two functions below (Cbrt1 and Cbrt) are helpful.

package main

import (
    "fmt"
    "math/cmplx"
)

// Newton's method cube root function that hopes for
//   convergence within 20 iterations
func Cbrt1(x complex128) complex128 {
    var z complex128 = x
    for i:= 0; i < 20; i++ {
        z = z - ((z*z*z - x) / (3.0*z*z))
    }
    return z
}

// Newton's method cube root function that runs until stable
func Cbrt(x complex128) complex128 {
    var z, z0 complex128 = x, x
    for {
        z = z - ((z*z*z - x) / (3.0*z*z))
        if cmplx.Abs(z - z0) < 1e-10 {
            break
        }
        z0 = z
    }
    return z
}

func main() {
    fmt.Println(Cbrt(2.0) , "should match" , cmplx.Pow(2, 1.0/3.0))
}
like image 43
smholloway Avatar answered Nov 15 '22 07:11

smholloway


As you're using Newton's method, I suppose you're starting with a positive real number.

So you don't need complex numbers.

You may simply do

package main

import (
    "fmt"
    "math"
)

func main() {
    x := 100.0
    root := math.Pow(x, 1.0/3.0)
    fmt.Println(root)
}
like image 30
Denys Séguret Avatar answered Nov 15 '22 08:11

Denys Séguret