Last active
August 29, 2015 14:04
-
-
Save ksomemo/fad8151574f24e8f2ac0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1.3351578377717581 | |
1.4142135623730951 | |
loop:4980, diff:0.01000, z:1.419186346344104 | |
1.419186346344104 | |
Program exited. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math" | |
) | |
func Sqrt(x float64) float64 { | |
z := 1.0 | |
for i := 0; i < 10; i++ { | |
z = z - (z*z-x)/2*z | |
} | |
return z | |
} | |
func Sqrt2(x float64) float64 { | |
z := 1.0 | |
bef := z | |
lim := 0.01 | |
for i := 0; i < 10000; i++ { | |
z = z - (z*z-x)/2*z | |
// ifステートメント中の局所変数 | |
if diff := math.Abs(bef - z); diff < lim { | |
fmt.Printf("loop:%v, diff:%.05f, z:%v \n", i, diff, z) | |
return z | |
} else { | |
bef = z | |
} | |
} | |
return z | |
} | |
func main() { | |
fmt.Println(Sqrt(2)) | |
fmt.Println(math.Sqrt(2)) | |
fmt.Println(Sqrt2(2)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment