2012-08-02 13:39:21 -07:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"math"
|
|
|
|
)
|
|
|
|
|
|
|
|
const min_threshold = 1e-200
|
|
|
|
|
2012-08-27 21:52:57 -07:00
|
|
|
type ErrNegativeSqrt float64
|
|
|
|
|
|
|
|
func (e ErrNegativeSqrt) Error() string {
|
|
|
|
return fmt.Sprintf("cannot Sqrt negative number: %v", float64(e))
|
|
|
|
}
|
|
|
|
|
|
|
|
func Sqrt(x float64, threshold float64) (z float64, iterations int, err error) {
|
|
|
|
if x < 0 {
|
|
|
|
err = ErrNegativeSqrt(x)
|
|
|
|
return
|
|
|
|
}
|
2012-08-02 13:39:21 -07:00
|
|
|
z = x
|
|
|
|
old_z := z
|
|
|
|
for {
|
|
|
|
z = z - (z*z-x)/(2*x)
|
|
|
|
if math.Abs(z-old_z) < threshold {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
old_z = z
|
|
|
|
iterations++
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
threshold := 1.0
|
|
|
|
right_answer := math.Sqrt(2)
|
|
|
|
for threshold > min_threshold {
|
2012-08-27 21:52:57 -07:00
|
|
|
answer, iterations, err := Sqrt(2, threshold)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
2012-08-02 13:39:21 -07:00
|
|
|
fmt.Printf("%0.4g %0.4g %0.20f %0.20f %0.2d\n",
|
|
|
|
threshold, right_answer-answer, right_answer, answer,
|
|
|
|
iterations)
|
|
|
|
threshold = threshold / 10.0
|
|
|
|
}
|
|
|
|
}
|