Skip to content

Instantly share code, notes, and snippets.

@sighmin
Last active August 21, 2019 18:39
Show Gist options
  • Save sighmin/9173219 to your computer and use it in GitHub Desktop.
Save sighmin/9173219 to your computer and use it in GitHub Desktop.
Go tour sqrt VS newton's method: http://tour.golang.org
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))
}
}
@lhauspie
Copy link

If I may, you should replace math.Pow(z, 2) with z*z because math.Pow in this case is 100 times slower than the simple mult operation.

This test:

func BenchmarkMathPow(b *testing.B) {
	var f float64
	for i := 0; i < b.N; i++ {
		f = math.Pow(123456, 2)
	}
	s := fmt.Sprint(f)
	s = fmt.Sprint(s)
}

func BenchmarkSquared(b *testing.B) {
	var f float64
	for i := 0; i < b.N; i++ {
		f = 123456 * 123456
	}
	s := fmt.Sprint(f)
	s = fmt.Sprint(s)
}

returns this result:

goos: linux
goarch: amd64
pkg: github.com/lhauspie/some-tests/perf
BenchmarkMathPow-8   	50000000	         30.9 ns/op	       0 B/op	       0 allocs/op
BenchmarkSquared-8   	2000000000	         0.29 ns/op	       0 B/op	       0 allocs/op
ok  	github.com/lhauspie/some-tests/perf	2.678s
Success: Benchmarks passed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment