I'm trying to calculate
Using the following code.
#define PI 3.14
double ans;
double input1;
void toRad() {
input1 = input1 * PI / 180.0;
}
void sine(void) {
toRad();
ans = input1;
int i = 1;
for (; i < 15; i++) {
if (i % 2 == 0)
ans = ans + (ans * input1 * input1) / 2 * i * (2 * i + 1);
else
ans = ans - (ans * input1 * input1) / 2 * i * (2 * i + 1);
}
printf("%lf", ans);
}
I used iterative operations instead of pow
and factorial functions to get more precise values and more iterations.
But, for some reason, I got different outputs like -4000000E
. What can be the problem of this code?
you have made a small mistake in writing the logic.check yourself until i=4.
if (i % 2 == 0)
ans = ans + (ans * input1 * input1) / 2 * i * (2 * i + 1);
else
ans = ans - (ans * input1 * input1) / 2 * i * (2 * i + 1);
instead of this you should create a factorial function so that it can be replaced by
if (i % 2 == 0)
ans = ans + (ans * input1 * input1) / factorial(2 * i + 1);
else
ans = ans - (ans * input1 * input1) / factorial(2 * i + 1);