Skip to content

Instantly share code, notes, and snippets.

@msteinert
Last active December 16, 2015 17:50
Show Gist options
  • Save msteinert/5473724 to your computer and use it in GitHub Desktop.
Save msteinert/5473724 to your computer and use it in GitHub Desktop.
A Tour of Go (http://tour.golang.org)
// http://tour.golang.org/#23
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
z, prev := 1.0, 0.0
for math.Abs(prev - z) > 0.0001 {
prev = z
z = z - (z * z - x) / (2 * z)
}
return z
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(math.Sqrt(2))
}
// http://tour.golang.org/#35
package main
import "code.google.com/p/go-tour/pic"
func Pic(dx, dy int) [][]uint8 {
pic := make([][]uint8, dy)
for x := range pic {
pic[x] = make([]uint8, dx)
for y := range pic[x] {
pic[x][y] = uint8((x + y) / 2)
}
}
return pic
}
func main() {
pic.Show(Pic)
}
// http://tour.golang.org/#40
package main
import (
"code.google.com/p/go-tour/wc"
"strings"
)
func WordCount(s string) map[string]int {
words := make(map[string]int)
for _, word := range strings.Fields(s) {
words[word]++
}
return words
}
func main() {
wc.Test(WordCount)
}
// http://tour.golang.org/#43
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
m, n, i := 0, 1, 0
return func () int {
val := 0
if (0 == i) {
val = 0
} else if (1 == i) {
val = 1
} else {
val = m + n
m = n
n = val
}
i++
return val
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
// http://tour.golang.org/#47
package main
import (
"fmt"
"math"
"math/cmplx"
)
func Cbrt(x complex128) complex128 {
z, prev := 1.0, 0.0
for math.Abs(prev - z) > 0.0001 {
prev = z
z = z - (z * z * z - real(x)) / (3 * z * z)
}
return complex(z, imag(x))
}
func main() {
fmt.Println(Cbrt(2))
fmt.Println(cmplx.Pow(2, 0.3333333))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment