Created
July 4, 2012 19:55
-
-
Save blakesmith/3049248 to your computer and use it in GitHub Desktop.
Go Tour: Exercise: Loops and Functions - My solution
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 newtAppx(x float64, appx float64) float64 { | |
return appx - ((math.Pow(appx, 2.0) - x) / (2 * appx)) | |
} | |
func Sqrt(x float64) float64 { | |
guess := 1.0 | |
appx := newtAppx(x, guess) | |
for { | |
nextAppx := newtAppx(x, appx) | |
delta := math.Abs(math.Abs(nextAppx) - math.Abs(appx)) | |
if delta <= 0.0001 { | |
break | |
} else { | |
appx = nextAppx | |
} | |
} | |
return appx | |
} | |
func guessSqrt(x float64) { | |
fmt.Println("Guess:", Sqrt(x), " Actual: ", math.Sqrt(x)) | |
} | |
func main() { | |
guessSqrt(2) | |
guessSqrt(54) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment