4
\$\begingroup\$

Just looking for some feedback on my solution for Tour of Go Exercise 24 - Loops and Functions. Is there anything that looks like a wrong way to do things in go? anything I could have done better?

package main
import (
 "fmt"
 "math"
)
func Approx(x float64, z float64) float64 {
 return z - (((z * z) - x) / (2 * z))
}
func Sqrt(x float64) float64 {
 previous := 0.0
 delta := 1.0
 z := x
 for delta > 0.005 {
 z = Approx(x, z)
 if previous > 0.0 {
 delta = previous - z
 }
 previous = z
 }
 return z
}
func main() {
 for i := 1; i < 11; i++ {
 value := float64(i)
 fmt.Println("Calculating Sqrt for ", value)
 real := math.Sqrt(value)
 approx := Sqrt(value)
 fmt.Println("Real ", real)
 fmt.Println("Approx ", approx)
 }
}
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Nov 9, 2013 at 14:06
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

One tiny thing: If you drop one set of parentheses:

return z - ((z * z - x) / (2 * z))

and then run go fmt, it will change it to

return z - ((z*z - x) / (2 * z))

The expressions around the * are close to the * and the expressions around the - are spaced out. In other words, go fmt implies the correct precedence.

Also, using line breaks to separate "sections" of a function is good, but there's no need to add an extra linebreak at the very beginning of a function or just before a }.

answered Nov 17, 2013 at 17:30
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.