blob: e8de49e5e64fce3dd426bfbc64202a5ea7f0b0cd [file] [log] [blame]
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build ignore
package main
import (
"fmt"
"math"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("Sqrt: negative number %g", e)
}
const delta = 1e-10
func Sqrt(f float64) (float64, error) {
if f < 0 {
return 0, ErrNegativeSqrt(f)
}
z := f
for {
n := z - (z*z-f)/(2*z)
if math.Abs(n-z) < delta {
break
}
z = n
}
return z, nil
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}