Created
October 26, 2018 09:01
-
-
Save saaresto/488946c4b461d3a4a24d5360a62ab9c3 to your computer and use it in GitHub Desktop.
Calculate square root using Newton's law (https://tour.golang.org/flowcontrol/8)
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" | |
| ) | |
| const DELTA = 0.000000000000000000000000000001 | |
| func sqrt(x float64) (z float64) { | |
| z = x | |
| for tempZ := decrease(z, x); z-tempZ > DELTA; tempZ = decrease(tempZ, x) { | |
| z = tempZ | |
| } | |
| return | |
| } | |
| func decrease(z float64, x float64) float64 { | |
| return z - (z*z-x)/(2*z) | |
| } | |
| func main() { | |
| fmt.Println(sqrt(2)) | |
| fmt.Println(math.Sqrt(2)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment