You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

26 lines
397 B

package main
import (
12 years ago
"fmt"
"math"
)
// using Newton's method
func Sqrt(x float64) float64 {
12 years ago
z := x - (x * 0.1)
for i := 0; i < 1000; i++ {
newZ := z - (((z * z) - x) / 2 * z)
diff := math.Abs(newZ) - math.Abs(z)
if math.Abs(diff) < 0.01 {
return newZ
}
z = newZ
}
return z
}
func main() {
12 years ago
fmt.Printf("stdlib -> %f\n", math.Sqrt(2))
fmt.Printf("newton -> %f\n", Sqrt(2))
}