r/ProgrammerHumor • • Oct 13 '26

Meme howProgrammingHasChanged

Post image
676 Upvotes

108 comments sorted by

View all comments

Show parent comment

14

u/martmists Oct 14 '26

I was about to point out the direct formula but you beat me to it. Though it should be noted yours doesn't work for negative integers, for that you'd want something like this:

def fib(n):
    sq = math.sqrt(5)
    phi = (1 + sq) / 2
    return (phi**n - (1 - phi)**n) / sq

Your solution works for non-negative inputs because (1-phi)n is always less than 0.5 for n >= 0, but this no longer holds for n < 0

4

u/PlantainMassive6744 Oct 14 '26

Love it. This is now my favorite answer to the question of how to compute the fib sequence

2

u/IronicRobotics Oct 14 '26 edited Oct 14 '26

Yes, but the recursive formulas were also only for positive integers. (Also, with the rounding, I can force a final integer solution and get rid of the float error up to n=70. Though I suspect rounding this formula here also works.)

Otherwise we also could have gone with a generating equation and cover the whole complex plane!