Skip to content

Instantly share code, notes, and snippets.

@issm
Created July 27, 2014 02:20
Show Gist options
  • Save issm/4001df41f1ffa864df0a to your computer and use it in GitHub Desktop.
Save issm/4001df41f1ffa864df0a to your computer and use it in GitHub Desktop.
[1] (1.0000000000000000, 1.0000000000000000): 0
[2] (1.4142135623730951, 1.4142135623730951): 0
[3] (1.7320508075688772, 1.7320508075688772): 0
[4] (2.0000000000000000, 2.0000000000000022): 2.220446049250313e-15
[5] (2.2360679774997898, 2.2360679774997898): 0
[6] (2.4494897427831779, 2.4494897427831779): 0
[7] (2.6457513110645907, 2.6457513110645907): 0
[8] (2.8284271247461903, 2.8284271247461903): 0
[9] (3.0000000000000000, 3.0000000000000000): 0
[10] (3.1622776601683795, 3.1622776601683795): 0
[11] (3.3166247903553998, 3.3166247903553998): 0
[12] (3.4641016151377544, 3.4641016151377548): 4.440892098500626e-16
[13] (3.6055512754639891, 3.6055512754639905): 1.3322676295501878e-15
[14] (3.7416573867739413, 3.7416573867739458): 4.440892098500626e-15
[15] (3.8729833462074170, 3.8729833462074170): 0
[16] (4.0000000000000000, 4.0000000000000000): 0
[17] (4.1231056256176606, 4.1231056256176606): 0
[18] (4.2426406871192848, 4.2426406871192857): 8.881784197001252e-16
[19] (4.3588989435406740, 4.3588989435406731): 8.881784197001252e-16
[20] (4.4721359549995796, 4.4721359549995796): 0
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
z, th := 1.0, 1e-14
for {
z0 := z - (math.Pow(z, 2) - x) / (2 * z)
if math.Abs(z - z0) <= th {
break
}
z = z0
}
return z
}
func main() {
for n := 1.0; n <= 20; n += 1.0 {
sq0, sq1 := math.Sqrt(n), Sqrt(n)
fmt.Printf("[%v] (%.16f, %.16f): %v\n", n, sq0, sq1, math.Abs(sq0 - sq1))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment