# Finding the golden ratio using C Tweet

From C++ to PHP, debugging to webhosting; help and discussion about writing your latest program to running your website. NOT for help when your PC won't work.

Announcements Posted on
1. Finding the golden ratio using C
Hi guys.

I was writing a small program to calculate the golden ratio by comparing Fibonacci numbers. It appears to work perfectly when comparing, say, the 91st and 90th Fibonacci numbers, but suddenly unravels if you go much higher. For example:

fib(101) / fib(100) gives 0.3something, while

fib(201) / fib(200) gives a negative number!

Does anyone know what the problem is?

My code is shown below:

2. Re: Finding the golden ratio using C
Has to be a buffer overflow.

unsigned long longs are only 2^64 -1, and I can definitely imagine the 200th fib term exceeding that
3. Re: Finding the golden ratio using C

Mathematica:
Code:
```In[1]:= N@Log[2,Fibonacci[200]]
Out[1]= 137.687```
If you want to do this sort of thing, see e.g. GMP.
4. Re: Finding the golden ratio using C
Just had a play with this... if it's any consolation you'll probably run out of precision in the long double well before you overflow the long long int.

on my box it appears to have converged at fib(48)/ fib(47) within the number of digits a long float can represent
5. Re: Finding the golden ratio using C
Thanks guys!

I thought that might be the case, but I assumed that I would get some error message rather than it just spewing out nonsense.
6. Re: Finding the golden ratio using C
Lol, It's C; it doesn't care and will happily keep going.
7. Re: Finding the golden ratio using C
(Original post by estel)
Has to be a buffer overflow.

unsigned long longs are only 2^64 -1, and I can definitely imagine the 200th fib term exceeding that
That's not a buffer overflow. That's an integer overflow.
8. Re: Finding the golden ratio using C
(Original post by CJKay)
That's not a buffer overflow. That's an integer overflow.
You're quite right. The words fail me
Useful resources

## Groups associated with this forum:

View associated groups