Source file tour/solutions/errors.go

     1  //go:build OMIT
     2  
     3  // Copyright 2012 The Go Authors.  All rights reserved.
     4  // Use of this source code is governed by a BSD-style
     5  // license that can be found in the LICENSE file.
     6  
     7  package main
     8  
     9  import (
    10  	"fmt"
    11  	"math"
    12  )
    13  
    14  type ErrNegativeSqrt float64
    15  
    16  func (e ErrNegativeSqrt) Error() string {
    17  	return fmt.Sprintf("Sqrt: negative number %g", e)
    18  }
    19  
    20  const delta = 1e-10
    21  
    22  func Sqrt(f float64) (float64, error) {
    23  	if f < 0 {
    24  		return 0, ErrNegativeSqrt(f)
    25  	}
    26  	z := f
    27  	for {
    28  		n := z - (z*z-f)/(2*z)
    29  		if math.Abs(n-z) < delta {
    30  			break
    31  		}
    32  		z = n
    33  	}
    34  	return z, nil
    35  }
    36  
    37  func main() {
    38  	fmt.Println(Sqrt(2))
    39  	fmt.Println(Sqrt(-2))
    40  }
    41  

View as plain text