Pagina's

2011/08/06

Inverse Fibonacci, invFib(Fib(n))=n

// Detecting when a number is a Fibonacci number, and which one if so.
// It's based on Binet's formula:
// Fn = (((1 + 5^0.5)/2)^n - ((1 - 5^0.5)/2)^n) / 5^0.5
// For larger n:
// Fn ~ (1 + 5^0.5)/2)^n  / 5^0.5
// For small numbers , <= F33 , a binary search will be used,
// for larger numbers the code below was used to get error value's.

    private static void error()
    {
        double c4 = Math.Log(Math.Sqrt(5));
        double c5 = Math.Log(Math.Sqrt(5) + 1) - Math.Log(2);
        Xint[] F = { 0, 1 };
        double e0 = 0;
        for (int n = 1; n < int.MaxValue - 1; n++)
        {
            F = new Xint[] { F[1], F[1] + F[0] };
            double m = (Xint.Log(F[0]) + c4) / c5;
            double e1 = Math.Abs(n - m);
            if ((n > 33) & (e1 > e0))
            {
                Console.WriteLine(n + "  " + e0);
                e0 = e1;
            }
        }
    }

// Below is a graph of log10(e) against log10(n),
// it's quite linear.

No comments:

Post a Comment