Skip to content

Instantly share code, notes, and snippets.

@ryanfrance
Last active May 23, 2024 16:29
Show Gist options
  • Save ryanfrance/e60d4a2c743c6581de8e5d5a0d1f6b91 to your computer and use it in GitHub Desktop.
Save ryanfrance/e60d4a2c743c6581de8e5d5a0d1f6b91 to your computer and use it in GitHub Desktop.
Newton's Method
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
z := 3.0
threshold := 1e-10 // Define a small threshold value
var prevZ float64 // Variable to store the previous estimate
for {
prevZ = z
z -= (z*z - x) / (2*z)
fmt.Println(z)
// Check if the change in z is smaller than the threshold
if math.Abs(z-prevZ) < threshold {
break
}
}
return z
}
func main() {
x := 2.0
fmt.Println(Sqrt(x), math.Sqrt(x))
}
@ryanfrance
Copy link
Author

ryanfrance commented May 22, 2024

Details of the algorithm: the z² − x above is how far away z² is from where it needs to be (x), and the division by 2z is the derivative of z², to scale how much we adjust z by how quickly z² is changing. This general approach is called Newton's method. It works well for many functions but especially well for square root.

z in the case of line 9, defined in sqrt function is the first guess and can be changed to amend the first result set.

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