Advertisement
artem_d

Newton's method Sqrt

Nov 14th, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.36 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "math"
  6. )
  7.  
  8. func Sqrt(x float64) float64 {
  9.     z := 1.0
  10.     prevZ := z * 2
  11.     i := 0
  12.    
  13.     for ; math.Abs(prevZ - z) > 0.00001; i++ {
  14.         prevZ = z
  15.         z -= (z*z - x) / (2*z)
  16.     }
  17.    
  18.     fmt.Printf("i: %v\n", i)
  19.     return z
  20. }
  21.  
  22. func main() {
  23.     fmt.Printf("Sqrt(8.5): %v\n", Sqrt(8.5))
  24.     fmt.Printf("math.Sqrt(8.5): %v\n", math.Sqrt(8.5))
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement