0
I’ve been trying to calculate this sum, but I’m having trouble making the factorial work... someone can help me identify my mistake?
Where x is the angle in radians and N the number of terms of series minus 1.
#include <stdio.h>
#include <math.h>
int main()
{
double x, z = 0, fat = 1;
int n, i, j, fat2=0;
scanf("%lf%d", &x, &n);
j = 1;
for(i = 0; i < n; i++ )
{
//printf("\n%d :: %lf :: %d ", fat2, fat, i); // DEBUG
z = z + ( ( pow(-1 , i)*pow(x, (2*i)) ) / (fat) );
fat2 = 2*j;
fat = fat * (fat2 - i);
j++;
}
printf("\ncos(x) = %lf\n", z);
return 0;
}
Edit:
#include <stdio.h>
#include <math.h>
int main()
{
double x, z = 0.0;
int n, i, j;
scanf("%lf%d", &x, &n);
double fat[n], fat2[n];
fat[1] = 1.0;
for(j = 1; j < n; j++){
fat2[j] = 2.0 *i;
fat[j] = fat[j] * (fat2[j] - j);
printf("\n%lf\t%lf", fat[j], fat2[j]);
}
fat[0] = 1.0;
for(i = 0; i < n; i++ )
{
//printf("\n%d :: %lf :: %d ", fat2, fat, i); // DEBUG
z = z + ( ( pow(-1 , i)*pow(x, (2*i)) ) / (fat[i]) );
}
printf("\n\ncos(x) = %lf\n", z);
return 0;
}
Edit 2 [solved]:
#include <stdio.h>
#include <math.h>
/*long int fatorial(int n){
long int fat = n * (n - 1);
if(n == 0 || fat == 0)
fat = 1.0;
return fat;}*/
long fat(int n) {
if(n < 2)
return 1;
else
return n * fat(n-1); //return (n < 2) ? 1 : n * fat(n-1);
}
int main()
{
double x, z = 0.0;
int n, i, j;
scanf("%lf%d", &x, &n);
for(i = 0; i < n; i++ )
{
z = z + ( ( pow(-1.0 , i)*pow(x, (2.0*i)) ) / (fat(2*i)) );
//printf("\n\t%ld", fat(2*i)); //debug
}
printf("\n\ncos(x) = %lf\n", z );
return 0;
}
what’s the matter ?
– zentrunix
I need to return the sum value of the photo above, but when calculating the factor of (2 * n) wrong, because it has that concept of 0! is equal to 1... And then mess a little, I have tried to put an if for this condition but keeps giving wrong values to the following factors
– Luciano
(1) create a separate function to calculate factorial(n); create a separate table (array), and initialize in this table the values 0!, 2!, etc... (2) in each iteration of the command for you take the next element of this factorial table
– zentrunix
Do as @zentrunix told you, create a factorial function.
– FourZeroFive
I created an array... However only returns 0.0...
– Luciano
I don’t understand your calculation of fat[j], it seems to me that you are not calculating the factorial correctly. Use a function like: long fat(int n) { Return (n < 2) ? 1 : n * fat(n-1); } , and call with fat(2*i). After your program is correct but you think you can optimize then optimize.
– anonimo
Oops, I get it now... N had thought that way... I tried to function the factorial the way I put in parentheses in Edit 2... but returned 0.000000... Anyway, everyone, thank you so much for your help!
– Luciano