-
Problem with formula
Hello, I have a maths assignment and i would like some help putting these formula in code, and how I would implement these in a loop function. The x is given.
An = (-x/n)*An-1 - 1/n*(n-1) * An-2
if x = 3
A(0) = 2
A(1) =0
A(2) = (-3/2)*0 - 1/2*(1)* 0 = -1
This is basically the results for the first 3, I need a loop to continuously do this for any number put for x
Any suggestions ?
-
You need to retain the last two values (at least).
The first two values are 2 and 0 (apparently).
So initialize a couple of variables with those values and print them:
Code:
double a = 2, b = 0;
printf("% f\n% f\n", a, b);
Then start your loop at 2, calculate the new value, print it, and then shift the two saved values over:
Code:
for (int n = 2; n < 100; n++) {
double c = -x / n * b - 1.0 / n * (n - 1) * a;
printf("% f\n", c);
a = b;
b = c;
}
Alternatively, you could store all calculated values in an array.
Code:
double a[100] = {2, 0};
for (int n = 2; n < 100; n++)
a[n] = -x / n * a[n-1] - 1.0 / n * (n - 1) * a[n-2];
for (int n = 0; n < 100; n++)
printf("% f\n", a[n]);