/ golang

Golang Examples

  1. fibonacci generator
package main

import "fmt"

func fibonacci() func() int {
	m := 1
	l := 0
	r := 0
	return func() int {
		m += l
		l, r = r, m
		return m
	}
}

func main() {
	f := fibonacci()
	for i := 0; i < 15; i++ {
		fmt.Println(f())
	}
}

  1. Newton-Raphson method(Sqrt method)
package main

import (
	"fmt"
	"math"
)

func sqrt(x float64, precision float64) float64 {
	ret := x
	for math.Abs(math.Pow(ret, 2)-x) > precision {
		ret -= (math.Pow(ret, 2) - x) / (float64(2) * ret)
	}
	return ret
}

func main() {
	fmt.Println(sqrt(25, 0.00001))
}