# Thread: cosine series with out using math.h

1. ## cosine series with out using math.h

I want to write a pogram which will calculate cosine series.
But I am not get the value like cos() function of math.h
Could you tell me why it is happening and any error in my code or any step mistake ?????

Code:
```float cos1(float x)
{
int i,fact=1;
float sum,term;
sum=1.0;
term=1.0;
for(i=1;i<5;i++)
{
term=term*x*x;
term=term*(-1);
fact=factorial(2*i);
sum=sum+(term/fact);
}
return(sum);
}

int factorial(int x)
{
int fact;
if(x==1)
return(1);
else
fact=x*factorial(x-1);
return(fact);
}

also in the place of for loop i am using  do while loop but result is same

float cos1(float x)
{
int i,fact=1;
float sum,term;
sum=1.0;
term=1.0;
i=1;
do
{
term=term*x*x;
term=term*(-1);
fact=factorial(2*i);
sum=sum+(term/fact);
i++;
}
while(term>0.00001)
return(sum);
}```

2. I copied and pasted your code and compiled it and it appears to work fine. It gives the same values as my calculator.

What kind of values does it give you?

3. And just what exactly does that have to do with C#?

4. Moved to C

5. Code:
```                        term=term*x*x;
term=term*(-1);```
can be written simpler as:
Code:
`term *= -x * x;`
and it's likely that the compiler generates better code this way too - multiplying by -1 is an expensive way to negate a number, when you can do "x = -x" if you want to negate it - and if the compiler doesn't have specific code to identify the "multiply x by -1 is the same as -x", then it will do a much worse job of it.

You can also calculate the factorial iteratively within the loop itself - just multiply by i * 2-1 and i * 2 on to a starting value of 1.

--
Mats