Is there a more elegant implementation of the Newton Go method?

I go in for Go training materials and wonder if there is a more elegant way to calculate the square root using Newton's Exercise Method : loops and functions than this:

func Sqrt(x float64) float64 {
    count := 0
    var old_z, z float64 = 0, 1
    for ; math.Abs(z-old_z) > .001; count++ {
        old_z, z = z, z - (z*z - x) / 2*z
    }
    fmt.Printf("Ran %v iterations\n", count)
    return z
}

(Part of the specification is for providing the number of iterations.) Here is the complete complete program , including package expression, import, and core.

+4
source share
1 answer

Firstly, the algorithm is incorrect. Formula:

enter image description here

You modeled this with:

z - (z*z - x) / 2*z

But it should be:

z - (z*z - x)/2/z

or

z - (z*z - x)/(2*z)

( , 0.001! 4 , 1e-6 x = 2.)

z=1 ( , 2). z = x / 2, .

, , :

z, return "". , , "" , , , . if:

func Sqrt(x float64) (z float64) {
    z = x / 2
    for i, old := 1, 0.0; ; i++ {
        if old, z = z, z-(z*z-x)/2/z; math.Abs(old-z) < 1e-5 {
            fmt.Printf("Ran %v iterations\n", i)
            return
        }
    }
}

z = x / 2 for, ( z, ):

func Sqrt(x float64) float64 {
    for i, z, old := 1, x/2, 0.0; ; i++ {
        if old, z = z, z-(z*z-x)/2/z; math.Abs(old-z) < 1e-5 {
            fmt.Printf("Ran %v iterations\n", i)
            return z
        }
    }
}

: 1, "exit" for for.

+9
source

All Articles