Last active
August 29, 2015 14:13
-
-
Save gccpacman/a197bdcbb70e1c8524b2 to your computer and use it in GitHub Desktop.
A tour to go Exercise
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
/* | |
https://tour.golang.org/flowcontrol/8 | |
http://go-tour-zh.appspot.com/flowcontrol/8 | |
*/ | |
/* Exercise: Loops and Functions #43 */ | |
/* Exercise: Loops and Functions #43 */ | |
package main | |
import ( | |
"fmt" | |
"math" | |
) | |
func Abs(x float64) float64 { | |
if x < 0 { | |
x = -x | |
} | |
return x | |
} | |
func Sqrt(x float64) (float64, int) { | |
z := float64(1) | |
tmp := float64(0) | |
times := int(0) | |
for { | |
times++ | |
z = z - (z*z-x)/(2*z) | |
if Abs(z-tmp) < 1e-15 { | |
//fmt.Printf("loop %d times\n", times) | |
break | |
} | |
tmp = z | |
} | |
return z, times | |
} | |
func main() { | |
for i := float64(1); i < 10; i++ { | |
attempt, times := Sqrt(i) | |
expected := math.Sqrt(i) | |
fmt.Printf("sqrt %g times %d --- attempt= %g (expected = %g) error = %g\n", i, times, attempt, expected, Abs(attempt-expected)) | |
} | |
} | |
/* console outprint */ | |
/* | |
sqrt 1 times 2 --- attempt= 1 (expected = 1) error = 0 | |
sqrt 2 times 6 --- attempt= 1.414213562373095 (expected = 1.4142135623730951) error = 2.220446049250313e-16 | |
sqrt 3 times 6 --- attempt= 1.7320508075688774 (expected = 1.7320508075688772) error = 2.220446049250313e-16 | |
sqrt 4 times 7 --- attempt= 2 (expected = 2) error = 0 | |
sqrt 5 times 7 --- attempt= 2.23606797749979 (expected = 2.23606797749979) error = 0 | |
sqrt 6 times 7 --- attempt= 2.449489742783178 (expected = 2.449489742783178) error = 0 | |
sqrt 7 times 7 --- attempt= 2.6457513110645907 (expected = 2.6457513110645907) error = 0 | |
sqrt 8 times 7 --- attempt= 2.82842712474619 (expected = 2.8284271247461903) error = 4.440892098500626e-16 | |
sqrt 9 times 7 --- attempt= 3 (expected = 3) error = 0 | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment