Last active
          December 21, 2016 16:28 
        
      - 
      
- 
        Save Ovid/897965be87038f71a1c48fe0cd086fad to your computer and use it in GitHub Desktop. 
    Newton's methods for calculating the square root in golang
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | package main | |
| // newton's method for calculating square roots | |
| import ( | |
| "fmt" | |
| "math" | |
| ) | |
| func Sqrt(x float64) float64 { | |
| if x == 0 { | |
| return 0 | |
| } | |
| z := float64(1) | |
| var prev float64 | |
| for math.Abs(z-prev) > .000000001 { | |
| prev = z | |
| z = z - (z*z-x)/(2*z) | |
| } | |
| return z | |
| } | |
| func main() { | |
| for i := float64(0); i <= 9; i++ { | |
| fmt.Println("sqrt of", i, "is", Sqrt(i), "versus", math.Sqrt(i)) | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment