Finding the closest fibonacci numbers

前端 未结 11 2448

I am trying to solve a bigger problem, and I think that an important part of the program is spent on inefficient computations.

I need to compute for a given number N, th

11条回答
  •  天命终不由人
    2021-02-02 14:23

    I think that an important part of the program is spent on inefficient computations.

    Have you profiled your code? As a general principle don't prematurely optimize; measure what parts are slowing it down. That way when you try optimizing, you can tell if the optimizations helped or hurt (often a sounds-good optimization will make it run worse; as say the compiler will not be able to do its optimizations or you aren't able to use your cpu's registers/cache as optimally).

    If this is what's slowing you down, I would do similar to Peng's great solution but pre-computing all the Fib numbers up to your largest value and store them into an array indexed by the corresponding expoential (n) from the closed-form (phi^**n - (1-phi)**n)/sqrt(5). His method will miscompute Fib numbers for large n with floating point arithmetic; unless you use arbitrary high-precision (which is slow). So your starting array is fib_array = [0,1,1,2,3,5,8,13,... ]. Then neglecting the small (1-phi)**n term, invert fib to find n (e.g., Peng's fib_inv), and take fib_array[n] as your first bound. If this bound is smaller (larger) than your value; you've found the lower (upper) bound, and so the other bound should be fib_array[n+1] (fib_array[n-1]).
    Or if you want to compute it use something from given a N that is better than Binet's formula. http://en.literateprograms.org/Fibonacci_numbers_%28Python%29

    Personally, I'd check to make sure that the second bound is on the opposite side of the term as the first bound (in rare cases where we shouldn't have neglected the (1-phi)**n term; you could possibly have do to another lookup seeing if the term is bounded by e.g., fib_array[n+1] and fib_array[n+2]). (This check may be redundant; but you'd have to prove that first, and the one extra comparison to be safe seems worth it in my book).

提交回复
热议问题