package main

//Covers "Exercise: Loops and Functions" and "Exercise: Errors"

import (
	"fmt"
	"math"
)

type ErrNegativeSqrt float64

//This is for a later exercise
func (e ErrNegativeSqrt) Error() string {
	return fmt.Sprint("cannot Sqrt negative number: ", float64(e))
}

func Sqrt(x float64) (float64, error) {
	if x < 0 {
		return 0, ErrNegativeSqrt(x)
	}
	
	var y float64 = x / 2
	var z float64 =  0.5 * (y + x/y)
	var delta float64 = 0.000001
	
	for ; (z > y && z - y > delta) || (z <= y && y - z > delta); z = 0.5 * (y + x/y) {
		y=z
	}
	
	return z, nil
}

func main() {
	fmt.Println(Sqrt(2))
	fmt.Println(math.Sqrt(2))
	
	fmt.Println(Sqrt(4))
	fmt.Println(math.Sqrt(4))
	
	fmt.Println(Sqrt(3))
	fmt.Println(math.Sqrt(3))
	
        //Should give an error
	fmt.Println(Sqrt(-2))
}