Last active
August 21, 2019 18:39
-
-
Save sighmin/9173219 to your computer and use it in GitHub Desktop.
Go tour sqrt VS newton's method: http://tour.golang.org
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 Newt(x float64) float64 { | |
if x == 0 { return 0 } | |
z := 1.0 | |
for i := 0; i < int(x); i++ { | |
z = z - ((math.Pow(z, 2) - x) / (2 * z)) | |
} | |
return z | |
} | |
func Sqrt(x float64) float64 { | |
return math.Sqrt(x) | |
} | |
func main() { | |
times := 15 | |
for i := 0; i < times; i++ { | |
sqrt := Sqrt(float64(i)) | |
newt := Newt(float64(i)) | |
fmt.Println(i, "squared:") | |
fmt.Println(" Sqrt:", sqrt) | |
fmt.Println(" Newt:", newt) | |
fmt.Println(" Difference:", math.Abs(sqrt-newt)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If I may, you should replace
math.Pow(z, 2)
withz*z
because math.Pow in this case is 100 times slower than the simple mult operation.This test:
returns this result: