This question is a follow on from a previous question I asked. The answers I received suggested that I make use of the Go math.Big library. In this question I use the library but unfortunately to little effect.
I am trying to using the Binet formula to calculate fib(100). I am using Go's Big.Float but without success. I get accuracy to about 10 decimal places. Please advise.
I am trying to avoid loops/recursion as I think these approaches will not scale well. Hence my attempt to leverage Binet's formula
// currently produces inaccurate results as the input increases.
package main
import (
"fmt"
"math/big"
"math"
"strconv"
)
func fib(n int) float64 {
var sroot5 = new(big.Float).SetPrec(200).SetFloat64(2.236067977499789696409173668731276235440618359611525724270897)
var phi = new(big.Float).SetPrec(200).SetFloat64(1.61803398874989484820458683436563811772030917980576286213544862)
var minusPhi = new(big.Float).SetPrec(200).SetFloat64(-0.61803398874989484820458683436563811772030917980576)
var fltP float64;
fltP, _ = phi.Float64()
var fltN float64;
fltN, _ = minusPhi.Float64()
var denom float64
denom, _ = sroot5.Float64()
// Magic fib formula (Binet) is:
// (Phi ^ n - (-phi ^ n)) / sqrt(5)
z := (math.Pow(fltP, float64(n)) - math.Pow(fltN, float64(n))) / denom
return math.Ceil(z)
}
func main() {
fib(100)
fmt.Println(strconv.FormatFloat(fib(100), 'f', 0, 64))
fmt.Println("true answer of fib(100) should be -> 354224848179261915075")
}