Created
December 28, 2013 22:42
-
-
Save tarsisazevedo/8165159 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" | |
) | |
type ErrNegativeSqrt struct { | |
number float64 | |
} | |
func (e ErrNegativeSqrt) Error() string { | |
return fmt.Sprintf("can't square root of negative number: %.f", e.number) | |
} | |
func Sqrt(x float64) (float64, error) { | |
if x < 0 { | |
return x, ErrNegativeSqrt{x} | |
} | |
z := 1.0 | |
old_z := 0.0 | |
delta := 0.2 | |
for { | |
old_z = z | |
z = z - ((math.Pow(z, 2) - x) / (2 * z)) | |
delta_newton := math.Abs(z - math.Sqrt(x)) | |
if delta_newton <= delta || old_z == z { | |
return z, nil | |
} | |
} | |
} | |
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