Source file tour/solutions/loops.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  const delta = 1e-6
    15  
    16  func Sqrt(x float64) float64 {
    17  	z := x
    18  	n := 0.0
    19  	for math.Abs(n-z) > delta {
    20  		n, z = z, z-(z*z-x)/(2*z)
    21  	}
    22  	return z
    23  }
    24  
    25  func main() {
    26  	const x = 2
    27  	mine, theirs := Sqrt(x), math.Sqrt(x)
    28  	fmt.Println(mine, theirs, mine-theirs)
    29  }
    30  

View as plain text