Created
April 10, 2017 10:57
-
-
Save zainfathoni/1a76009c08b6340fc9d1f96fce47c7ab to your computer and use it in GitHub Desktop.
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 | |
import ( | |
"fmt" | |
"math" | |
) | |
const DELTA = 0.00000000001 | |
const INITIAL_Z = 100.0 | |
func Sqrt(x float64) (z float64, err error) { | |
if x < 0 { | |
return z, ErrNegativeSqrt(x) | |
} | |
z = INITIAL_Z | |
step := func() float64 { | |
return z - (z*z - x) / (2 * z) | |
} | |
for zz := step(); math.Abs(zz - z) > DELTA | |
{ | |
z = zz | |
zz = step() | |
} | |
return | |
} | |
type ErrNegativeSqrt float64 | |
func (e ErrNegativeSqrt) Error() string { | |
return fmt.Sprint("cannot Sqrt negative number: ", | |
float64(e)) | |
} | |
func main() { | |
fmt.Println(Sqrt(2)) | |
fmt.Println(Sqrt(-2)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment