Hey everyone,
To preface, I have very little programming knowledge and I'm only just beginning with the very basics.
I'm supposed to be using the fibonacci sequence to estimate the golden ratio. So, I managed to create a function (which I believe works as I've tested it) and everything seems to be fine... EXCEPT I can't get the a & b variable to update at the end of my while loop. I've copied all my code below. I really can't figure out what's wrong (though I'm sure it's something super obvious) and I would really appreciate any help.
THanks
--> formatting is a little weird for comments after I copied the code her... sorry
Code:
#include <math.h>
int fibonacci(int N) { //N is the term of the Fibonacci sequence starting at the 0th term
int i = 0; //loop index
if (N == 0 || N == 1) {
return 1;
}
int previousN = 1; //last integer in fibonacci sequence preceeding new value
int previousPreviousN = 1; //last integer preceeding the previousN in fibonacci sequence
int newValue = 0; //current value of fibonnaci sequence at term N
for (i = 0; i < (N-1); i++) {
newValue = previousN + previousPreviousN;
previousPreviousN = previousN;
previousN = newValue;
}
return newValue;
}
int main(void) {
constdouble truePhi = (1 + sqrt(5))/2; //the true value of phi used in error calculations
int i = 0; // loop index
int a = 2; // a = n+1 term of Fibonacci
int b = 1; // b = n term of Fibonacci
double previousApprox = 1.0; // previous approximation of phi
double newApprox = 0.0; // new approximation of phi
double relError; // relative error between the computed approximation and the true value of phi
while (fabs(previousApprox - newApprox) >= 0.001) {
printf("%d ", i);
printf("Phi approximation = %lf ", newApprox);
relError = fabs((newApprox-truePhi)/truePhi);
printf("Error = %lf\n", relError);
previousApprox = newApprox;
newApprox = fibonacci(a)/fibonacci(b);
a++;
b++;
i++;
}
return0;
}