Skip to content

Instantly share code, notes, and snippets.

@johnta0
Created August 25, 2018 04:53
Show Gist options
  • Save johnta0/4ef64e115e76b627ed5c78797c3a258c to your computer and use it in GitHub Desktop.
Save johnta0/4ef64e115e76b627ed5c78797c3a258c to your computer and use it in GitHub Desktop.
// ニュートン法で平方根を求める関数を実装する
// z -= (z*z - x) / (2*z)
package main
import (
"fmt"
)
func Sqrt(x float64) float64 {
z := 1.0
for z*z < x {
z += 1
}
for i := 0; i < 10; i++ {
f := z - (z*z - x) / (2*z)
if (f*f - x) < (z*z - x) {
z = f
}
if (z*z - x) / (2*z) < z*z - x {
}
}
return z
}
func main() {
fmt.Println(Sqrt(2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment