Dear community,
I ran into the following issue when started playing with go. Had the 
following small program to calculate Fibonacci numbers using the closed 
form:

package "fib"

import "math"

var sqrt_5 = math.Sqrt(5.0)
var psi = -1.0/math.Phi

// had to add this to solve accuracy issue
func round(x float64) uint64 {
    return uint64(math.Floor(x + 0.5))
}

// find the nth fibonacci number based on Binet's formula
// see here: 
https://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression
func fibonacci(n uint) uint64 {
    float_n := float64(n)
    return round((math.Pow(math.Phi, float_n) - math.Pow(psi, float_n))/
sqrt_5)
}


When I first tried without doing the "rounding" I did not get whole numbers 
as the output (similar program in C++ gave whole numbers without rounding).
Following test is failing without the call to "round()":

package "fib"

import "testing"

var results = map[uint]uint64 {
    0: 0,
    2: 1,
    10: 55,
    14: 377,
    20: 6765,
    29: 514229,
    33: 3524578,
    59: 956722026041,
}

func Test_fibonacci(t *testing.T) {
    for arg, expected := range results {
        actual := fibonacci(arg)
        if actual != expected {
            t.Error("Expected", expected, "got", actual)
        }
    }
}



Are there known accuracy issues with floating points in go?

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to