[Go语言]我的第一个Go语言程序
2016-07-19 18:38
489 查看
Exercise: Loops and Functions
As a simple way to play with functions and loops, implement the square root function using Newton's method.In this case, Newton's method is to approximate
Sqrt(x)by picking a starting point z and
then repeating:
To begin with, just repeat that calculation 10 times and see how close you get to the answer for various values (1, 2, 3, ...).
Next, change the loop condition to stop once the value has stopped changing (or only changes by a very small delta). See if that's more or fewer iterations. How close are you to the math.Sqrt?
package main import ( "fmt" "math" ) var delta = 0.00001 func Sqrt(x float64) float64 { z := 1.0 var z1 float64 z1 = z - (z * z - x) / (2 * z) for math.Abs(z1 - z) > delta { z = z1 z1 = z - (z * z - x) / (2 * z) } return z1; } func main() { fmt.Println(Sqrt(2)) fmt.Println(math.Sqrt(2)) }
相关文章推荐
- SQLSERVER 中GO的作用详解
- 在Go语言程序中使用gojson来解析JSON格式文件
- 举例详解Go语言中os库的常用函数用法
- Go语言中函数的参数传递与调用的基本方法
- 深入解析Go语言的io.ioutil标准库使用
- GO语言的IO方法实例小结
- Go语言的os包中常用函数初步归纳
- Go语言中数组的基本用法演示
- GO语言类型转换和类型断言实例分析
- 深入解析Go语言编程中的递归使用
- 初步解读Golang中的接口相关编写方法
- Go语言实现的最简单数独解法
- 详解Golang编程中的常量与变量
- Go实现比较时间大小
- 深入剖析Go语言编程中switch语句的使用
- 简单讲解Go程序中使用MySQL的方法
- Go语言的Windows下环境配置以及简单的程序结构讲解
- 在Go程序中实现服务器重启的方法
- Go语言流程控制之goto语句与无限循环
- 在Mac OS上安装Go语言编译器的方法