Skip to content

Instantly share code, notes, and snippets.

@oskimura
Last active March 29, 2022 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oskimura/67297f255e74a0f542bf84f273863026 to your computer and use it in GitHub Desktop.
Save oskimura/67297f255e74a0f542bf84f273863026 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
)
func Sqrt1(x float64) float64 {
//z := 1.0
z := float64(1)
for i := 0; i < 10; i++ {
z -= (z*z - x) / (2 * z)
}
return z
}
func abs(x float64) float64 {
if x < 0 {
return x * -1
} else {
return x
}
}
func Sqrt(x float64) float64 {
//z := 1.0
z := float64(1)
tmp := x
for {
//tmp := z
z -= (z*z - x) / (2 * z)
if abs(tmp-z) < 0.00000005 {
break
}
tmp = z
}
return z
}
func main() {
fmt.Println(Sqrt(16.0))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment