Last active
May 23, 2024 16:29
-
-
Save ryanfrance/e60d4a2c743c6581de8e5d5a0d1f6b91 to your computer and use it in GitHub Desktop.
Newton's Method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.