I want to calculate the sinus of user inputs using my own functions based on this equation:
sin(x) = sum_(i=0)^n (-1)^i * (x^(2 i + 1)/((2 i + 1)!))
I have this code and to my understandings I do exactly the same as what's written in the equation:
#include <stdio.h>
#include <math.h>
int faculty(int factor)
{
int result = 1;
if (factor > 0)
{
for (int i = 1; i <= factor; i++)
{
result = result * i;
}
}
else
{
result = 1;
}
return result;
}
double my_sin(double x, int n)
{
double my_sin = 0;
for (int j = 0; j < n ; j++)
{
double i = (double)j;
double faculty_j = (double)faculty(2*j+1);
my_sin = my_sin + (pow((-1.0), i) * (pow(x, (double)(2.0 * i + 1.0)) / faculty_j));
}
return my_sin;
}
int main()
{
int n = 0;
double x = 0;
printf("x=");
scanf("%lf", &x);
printf("n=");
scanf("%i", &n);
printf("sin(%i)=", (int)x);
printf("%lf\n", my_sin(x, n));
return 0;
}
However for example when I use x = 8
and n = 5
I get sin(8)=149
as a result. I tried debugging the code for some time now but I have no idea where the problem might be or how to find out what the problem is.
Updated code:
#include <stdio.h>
long int factorial(int factor)
{
long int result = 1;
if (factor > 0)
{
for (int i = 1; i <= factor; i++)
{
result = result * i;
}
}
else
{
result = 1;
}
return result;
}
double my_pow(double a, double b)
{
if (b == 0)
{
return 1;
}
double result = a;
double increment = a;
double i, j;
for (i = 1; i < b; i++)
{
for (j = 1; j < a; j++)
{
result += increment;
}
increment = result;
}
return result;
}
double my_sin(double x, int n)
{
double my_sin = 0;
for (int j = 0; j < n ; j++)
{
double i = (double)j;
double faculty_j = (double)factorial(2*i+1);
my_sin = my_sin + (my_pow((-1.0), i) * (my_pow(x, 2.0 * i + 1.0) / faculty_j));
}
return my_sin;
}
int main()
{
int n = 0;
double x = 0;
printf("x=");
scanf_s("%lf", &x);
printf("n=");
scanf_s("%i", &n);
printf("sin(%i)=", (int)x);
printf("%lf\n", my_sin(x, n));
return 0;
}