Thursday, August 10, 2006

source code for fibonacci numbers

to confirm if the values are precise,I write this program to compare the results between two different methods.
one is fibonacciOriginalDefiniton(n) following the original definition using recurrece formulas;
another is fibonacciGoldenRatio(n) following the direct and easy way to compute the value directly;

#include "iostream"
#include "math.h"
using namespace std;
int fibonacciOriginalDefinition(int n)
{
__if ( n == 0 || n == 1 ) return n;
__return fibonacciOriginalDefinition(n-1)+fibonacciOriginalDefinition(n-2);
}

float fibonacciGoldenRatio(int n)
{
__int i;
__float x1,x2,y1,y2;
__x1 = y1 = (1+sqrt(5))/2;
__x2 = y2 = (1-sqrt(5))/2;
__for ( i = 0; i < n-1; i++ ) {
____x1 *= y1;
____x2 *= y2;
__}
__return (x1-x2)/sqrt(5);
}

int main(void)
{
__freopen("data.txt","r",stdin);
__freopen("res.txt","w",stdout);
__int n;
__while ( cin >> n ) {
____cout << fibonacciOriginalDefinition(n) << "\t" << fibonacciGoldenRatio(n) << endl;
__}
__return 0;
}

comparison:
sample input:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
sample output to comparison:
org________goldenRatio
0__________0
1__________1
1__________1
2__________2
3__________3
5__________5
8__________8
13_________13
21_________21
34_________34
55_________55
89_________89
144________144
233________233
377________377
610________610
987________987
1597_______1597
2584_______2584
4181_______4181
6765_______6765

from the sample output, we can easily find out they're not different,though,their data type one is integer one is float;
so,the problem is solved,that is,the advanced method works.

0 Comments:

Post a Comment

<< Home