1

CONTEXT

Among many intuitive solutions online, I've trying hard to understand this one implementation which was posted on r/golang.

Just to enrich the context, here's the problem statement in the golang tutorial:

As a way to play with functions and loops, let's implement a square root function: given a number x, we want to find the number z for which z² is most nearly x.

Here's the link to the post and here's the code from that post which I've slightly changed to understand it better:

package main

import (
    "fmt"
)

func Sqrt(x, z float64) float64 {

    z -= ((z*z - x) / (2*z))
    
    for z*z > x {
        z -= ((z*z - x) / (2*z))
    }
    return z
}

func main() {
    fmt.Println(Sqrt(100, 1))
}

DOUBT

How is it that for any given value of z and x, z^2 always ends up a greater value than x in the first iteration (that is before the beginning of the for loop)?

I have this doubt since I wonder if there's a way whereby both z^2 is less than x and the returned z is an incorrect root to x.

I'm mostly convinced that z^2 cannot be less than x in the first iteration since I couldn't find any combination of z and x proving otherwise, in so far as I could try. I would greatly appreciate an explanation as to why z^2 is always greater than x on the first iteration, if indeed that is true.

1 Answers1

0

this is because z -= ((z * z - x) / (2*z)) is equal to

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

because in first place value of z is always way less than x so z * z - x will be negative

and we have z - (negative value ) so this will be positive for example a-(-b) = a+b

but as z starts to grow the value z*z - x will become less and less

Mohammad Ansari
  • 1,076
  • 1
  • 11
  • 22
  • Thanks but I am trying to understand your answer better. What is the Newton Method Expression doing to z that makes z^2 always greater than x? For e.g., given x = 2 and can z be anything that would make z something like 0.40 after the first Newton Method implementation? If no, why not? – Vishak Arudhra Mar 12 '23 at 19:02
  • z ^ 2 somewhere must be less than x beucase in other way we will have infinit loop in for z*z > x – Mohammad Ansari Mar 12 '23 at 19:11
  • we will have this operation when z ^ 2 is less than x and when it will be happen ? just write mathematical expression after first iterations the value of z will be less and less until z ^ 2 > x will be false then we will return z – Mohammad Ansari Mar 12 '23 at 19:16