Last active
March 7, 2016 06:28
-
-
Save plasticbrain/ef4e1951449359e3b1bc to your computer and use it in GitHub Desktop.
Go: Newton's method of approximating square roots
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" | |
) | |
const DELTA = 0.00000001 | |
func Sqrt(x float64) float64 { | |
guess := float64(1) | |
for { | |
guess = guess - (guess*guess - x)/(2*guess) | |
if math.Abs(x-guess*guess) <= DELTA { | |
break | |
} | |
} | |
return guess | |
} | |
// Alternative method | |
// I like this one better, and I feel like it's more effecient since it removes the superflous if statement. | |
func SqrtAlt(x float64) float64 { | |
guess, d := float64(1), float64(1) | |
for d > DELTA { | |
guess = guess - (guess*guess - x)/(2*guess) | |
d = math.Abs(x-guess*guess) | |
} | |
return guess | |
} | |
func main() { | |
fmt.Println(Sqrt(500)) | |
fmt.Println(SqrtAlt(500)) | |
fmt.Println(math.Sqrt(500)) | |
} | |
/* | |
Output: | |
22.360679774997898 | |
22.360679774997898 | |
22.360679774997898 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment