42 lines
841 B
Go
42 lines
841 B
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
)
|
|
|
|
type ErrNegativeSqrt float64
|
|
|
|
func (e ErrNegativeSqrt) Error() string {
|
|
return fmt.Sprintf("cannot Sqrt negative number: %v", float64(e))
|
|
}
|
|
|
|
func Sqrt(x float64) (float64, error) {
|
|
if x < 0 {
|
|
return 0, ErrNegativeSqrt(x)
|
|
}
|
|
precision := 0.00001
|
|
old_z := 0.0
|
|
z := x
|
|
iter := 0
|
|
for (z - old_z) > precision {
|
|
iter += 1
|
|
old_z := z
|
|
z -= (z*z - x) / (2*z)
|
|
if old_z - z < 0 {
|
|
if ((old_z - z) * -1) < precision {
|
|
fmt.Println("Required precision has been reached after", iter, "iterations! Square root of", x , "is", z)
|
|
return z, nil
|
|
}
|
|
} else if (old_z - z) < precision {
|
|
fmt.Println("Required precision has been reached after", iter, "iterations! Square root of", x , "is", z)
|
|
return z, nil
|
|
}
|
|
}
|
|
return z, nil
|
|
}
|
|
|
|
func main() {
|
|
fmt.Println(Sqrt(2))
|
|
fmt.Println(Sqrt(-2))
|
|
}
|