I'm trying to do a "1-liner" for fun purposes and for some reason i can't make the code work properly. Note: that's C, not C++, however the issue persists in both.
The "unfolded" version:
#include <stdio.h>
#include <math.h>
int main() {
double iter = 1;
double res = 0;
double elem = 0;
double fib_c = 1;
double fib_p = 1;
double power = 4;
double fact = 1;
while (iter < 15) {
fib_c += fib_p; //fibonacci current
fib_p = fib_c - fib_p; //fibonacci previous
fact *= iter; //factorial
power *= 4; //power of 4
elem = (fib_c * power * sqrt(iter+1)) / fact; //element of series
res += elem; //series
printf("----\nelem = %2.3f\nres = %2.3f\n", elem, res);
iter++;
}
return 0;
}
It's a series (i don't know the mathematical term for it in english) and here the elem
ent goes up from 45 to 1264 and then goes back down to 47.
Here's the "wrapped" version i'm trying to make work:
#include <stdio.h>
#include <math.h>
int main() {
double iter = 1;
double res = 0;
double elem = 0;
double fib_c = 1;
double fib_p = 1;
double power = 4;
double fact = 1;
while (iter < 15) {
res += (elem = (fib_c += ((fib_p = fib_c - fib_p)) * (power*=4) * sqrt(iter+1)) / (fact*=iter));
printf("----\nelem = %2.3f\nres = %2.3f\n", elem, res);
iter++;
}
return 0;
}
Here the elem
ent goes beyond integer in less than 5 iterations. So obviously, something is wrong. But what?
By the way, if i print out each value (fib_c
, power
, fact
) each iteration, i will see the correct values (current fibonacci number, power of 4, ongoing factorial, accordingly). So i made a guess that there is something weird happening "behind the scenes" and i don't know how to manage it.
Any ideas?