Last active
November 21, 2015 23:04
-
-
Save schors/b9e58af00728eb31610b to your computer and use it in GitHub Desktop.
Gotour exercise solution. Loops and Functions
This file contains 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" | |
) | |
// only explicit declaration outside function body | |
// объявить вне функций можно только явно | |
var d float64 = 1.0e-15 | |
// my SQRT function | |
// моя функция вычисления квадратного корня | |
func Sqrt(x float64) (int,float64) { | |
// initial value for raw | |
// начальное значение для ряда | |
z := 1.0 | |
// need "i" outside loop | |
// "i" нужен и после цикла | |
i := 0 | |
for ;;i++ { | |
// formula | |
// формула | |
z1 := z - ((z*z - x)/(2*z)) | |
// can be solved in different ways, for example by "abs" function | |
// you need to calculate the modulus of the difference between the current and previous calculations | |
// можно сделать разными способами, например через функцию "abs" | |
// нужно вычислить модуль разницы между текущим и предыдущим вычислением | |
if z1 > z && z1 - z < d { | |
break | |
} else if z1 < z && z - z1 < d { | |
break | |
} else if z1 == z { | |
break | |
} | |
z = z1 | |
} | |
// возвратить количество циклов и вычисленное значение | |
return i,z | |
} | |
func main() { | |
for i := 1.0; i < 10; i++ { | |
j,v:=Sqrt(i) | |
fmt.Println("value = ", i, "my Sqrt = ", v ," (",j,")", " math.Sqrt = ", math.Sqrt(i)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment