updated sqrt code to return an error when asked to Sqrt a negative number
This commit is contained in:
parent
bea638aa28
commit
aaba46344f
|
@ -7,7 +7,17 @@ import (
|
||||||
|
|
||||||
const min_threshold = 1e-200
|
const min_threshold = 1e-200
|
||||||
|
|
||||||
func Sqrt(x float64, threshold float64) (z float64, iterations int) {
|
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
|
||||||
|
}
|
||||||
z = x
|
z = x
|
||||||
old_z := z
|
old_z := z
|
||||||
for {
|
for {
|
||||||
|
@ -25,7 +35,10 @@ func main() {
|
||||||
threshold := 1.0
|
threshold := 1.0
|
||||||
right_answer := math.Sqrt(2)
|
right_answer := math.Sqrt(2)
|
||||||
for threshold > min_threshold {
|
for threshold > min_threshold {
|
||||||
answer, iterations := Sqrt(2, threshold)
|
answer, iterations, err := Sqrt(2, threshold)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
fmt.Printf("%0.4g %0.4g %0.20f %0.20f %0.2d\n",
|
fmt.Printf("%0.4g %0.4g %0.20f %0.20f %0.2d\n",
|
||||||
threshold, right_answer-answer, right_answer, answer,
|
threshold, right_answer-answer, right_answer, answer,
|
||||||
iterations)
|
iterations)
|
||||||
|
|
Loading…
Reference in New Issue