A crappy implementation of Newton's method for finding square root
This commit is contained in:
parent
92cd405b2e
commit
5edefe38d2
25
gotime/src/exercise-sqrt.go
Normal file
25
gotime/src/exercise-sqrt.go
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
)
|
||||||
|
|
||||||
|
// using Newton's method
|
||||||
|
func Sqrt(x float64) float64 {
|
||||||
|
z := x - (x * 0.1)
|
||||||
|
for i := 0 ; i < 1000 ; i++ {
|
||||||
|
newZ := z - (((z * z) - x) / 2 * z)
|
||||||
|
diff := math.Abs(newZ) - math.Abs(z)
|
||||||
|
if math.Abs(diff) < 0.01 {
|
||||||
|
return newZ
|
||||||
|
}
|
||||||
|
z = newZ
|
||||||
|
}
|
||||||
|
return z
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
fmt.Printf("stdlib -> %f\n", math.Sqrt(2))
|
||||||
|
fmt.Printf("newton -> %f\n", Sqrt(2))
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user