Jump to content
  • Advertisement
Sign in to follow this  
sheep19

Ultra fast fibonacci function in C++! :)

This topic is 2697 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I have created a fibonacci generation function, which is not recursive!!

Here it is:


double fibonacci(unsigned n)
{
return 0.447213595 * pow(1.61803399, (double)n) - 0.447213595 * pow(-0.618033989, (double)n);
}

Share this post


Link to post
Share on other sites
Advertisement
Hi, you may want to double the significant digits in your constants in order to fully utilise double precision! As it is, it will probably break when your result is somewhere in the tens of millions range (at best).

Share this post


Link to post
Share on other sites

Hi, I have created a fibonacci generation function, which is not recursive!!


You mean, you've implemented a fairly well-known mathematical formula. As noted, you are going to have problems with precision errors at some point. Also, recursion is not needed for the Fibonacci numbers, anyway: you just generate them sequentially from the beginning. This is perhaps one of the classic examples of how "dynamic programming" techniques can improve the runtime complexity of algorithms.

Share this post


Link to post
Share on other sites
For generating really large Fibonacci numbers, you can even go one step further. Write the linear recurrence in matrix form (this is the same matrix you would use to derive the formula that the OP used), and then use repeated squaring to get the desired power of the matrix. Then you just read the result out of the matrix. Asymptotically, this is only really faster if you use one of the fast integer multiplication algorithms, e.g. via gmplib.

Share this post


Link to post
Share on other sites
Prefect's solution and the OP's solution are the same in some sense. If you write the recurrence in matrix form, and you diagonalize the matrix to speed up exponentiation, you'll get the OP's formula.

A = P*D*P^-1
A^n = P*D*P^-1*P*D*P^-1*...*P*D*P^-1 = P*D^n*P-1

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!