Created
April 2, 2012 01:58
-
-
Save tetsuok/2279991 to your computer and use it in GitHub Desktop.
An answer of the exercise: Loops and Functions on a tour of Go
This file contains 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" | |
) | |
const Delta = 0.0001 | |
func isConverged(d float64) bool { | |
if d < 0.0 { | |
d = -d | |
} | |
if d < Delta { | |
return true | |
} | |
return false | |
} | |
func Sqrt(x float64) float64 { | |
z := 1.0 | |
tmp := 0.0 | |
for { | |
tmp = z - (z * z - x) / 2 * z | |
if d := tmp - z; isConverged(d) { | |
return tmp | |
} | |
z = tmp | |
} | |
return z | |
} | |
func main() { | |
attempt := Sqrt(2) | |
expected := math.Sqrt(2) | |
fmt.Printf("attempt = %g (expected = %g) error = %g\n", | |
attempt, expected, attempt - expected) | |
} |
package main
import (
"fmt"
)
func Sqrt(x float64) float64 {
z := float64(1)
for i := 1; i <= 10; i++ {
nextZ := z - (zz-x)/(2z)
if nextZ == z {
return z
} else {
z = nextZ
fmt.Println(z, i)
}
}
return z
}
func main() {
p := 2.0
fmt.Println(Sqrt(p))
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
func Sqrt(x float64) float64 {
var z, tmp float64 = 1.0, 0.
for ; math.Abs(z - tmp) >= 1e-8 ; z, tmp = z - (zz-x)/(2z), z {}
return z
}