Skip to content

Instantly share code, notes, and snippets.

@sugilog
Last active August 29, 2015 14:12
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 sugilog/47c17359fc4ed306cc6b to your computer and use it in GitHub Desktop.
Save sugilog/47c17359fc4ed306cc6b to your computer and use it in GitHub Desktop.
ニュートン法を使った平方根の計算
package main
import (
"fmt"
)
func Sqrt(x float64) float64 {
var z float64 = 1
for i := 0; i < 10; i++ {
z = z - ( ( z * z - x ) / ( 2 * z ) )
}
return z
}
func main() {
for x := 1; x <= 10; x++ {
fmt.Println(Sqrt(float64(x)))
}
}
package main
import (
"fmt"
)
func Sqrt(x float64) float64 {
var z float64 = 1
var threshold float64 = 0.001
for i := 0; i < 10; i++ {
result := z - ( ( z * z - x ) / ( 2 * z ) )
if ( ( result - z ) * ( result - z ) / z ) < threshold {
z = result
fmt.Print( "i: " )
fmt.Println( i + 1 )
break
} else {
z = result
}
}
return z
}
func main() {
for x := 1; x <= 10; x++ {
fmt.Println(Sqrt(float64(x)))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment