Created
July 13, 2017 09:24
-
-
Save Marmiz/dc9fafbf1ffe3400280ffd65fd2ea5c2 to your computer and use it in GitHub Desktop.
Exercise made during A Tour of Go.
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
/* | |
* Exercise: Loops and Functions | |
* As a way to play with functions and loops, implement the square root function using Newton's method. | |
* To begin with, repeat the calculation 10 times and see how close you get to the answer for various values (1, 2, 3, ...). | |
* Next, change the loop condition to stop once the value has stopped changing (or only changes by a very small amount). | |
* See if that's more or fewer than 10 iterations. How close are you to the math.Sqrt? | |
*/ | |
package main | |
import ( | |
"fmt" | |
"math" | |
) | |
func Sqrt(x float64) float64 { | |
z := 1.0 | |
s := 0.0 | |
for i:= 0; i < 10; i++ { | |
z -= (z*z - x) / (2*z) | |
if math.Abs(s - z) < 1e-15 { | |
fmt.Printf("Nuber of iteration %v \n", i) | |
break | |
} | |
s = z | |
} | |
return z | |
} | |
func main() { | |
val := 164.0 | |
fmt.Println("Newton", Sqrt(val)) | |
fmt.Println("Native", math.Sqrt(val)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment