Created
January 21, 2019 06:56
-
-
Save stevenferrer/d243e18a949dc2a21b496539f2b705a6 to your computer and use it in GitHub Desktop.
square root value approximation using newton's method
This file contains hidden or 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 { | |
// starting value | |
var z float64 = x / 2 | |
var cnt = 1 | |
// initial guess | |
var prevZ = z | |
z -= (z*z - x) / (2 * z) | |
fmt.Println("Initial guess: ", z) | |
for z <= x { | |
cnt++ | |
prevZ = z | |
z -= (z*z - x) / (2 * z) | |
fmt.Println("New guess: ", z) | |
diff := prevZ - z | |
// tolerance between new and previous guess | |
if diff < 0.0000001 { // acceptable error between guesses | |
fmt.Println("Count: ", cnt) | |
return z | |
} | |
} | |
return 0 | |
} | |
func main() { | |
var x float64 = 12334 | |
fmt.Println("Guess: ", Sqrt(x)) | |
fmt.Println("Answer: ", math.Sqrt(x)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment