# My nice little sine function, that I want to improve.

This topic is 5465 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

#include <iostream>
#include <math.h>

#define PIENOTCAKE 3.1415926535897932384626433832795

unsigned int fractorial(unsigned int number)
{
unsigned int holder = number;
unsigned int i = number;
while (i>0)
{
if (i == 1)
{
break;
}
i--;
holder *=i;
}
return holder;
}
long double getsigma(long double n, long double x)
{
//long double retvalue;
//retvalue = ((pow(-1, n))/fractorial(2*n + 1))*pow(x,2*n + 1);
return ((pow(-1, n))/fractorial(2*n + 1))*pow(x,2*n + 1);
}
int main(int argc, char *argv[])
{
int i = 1;
long double totaler;

totaler = getsigma(0,PIENOTCAKE/3);

while (i<15)
{
totaler += getsigma(i,PIENOTCAKE/3);
i++;
}
std::cout << "Sine of PI/3: "<<totaler<<std::endl;
system("pause");
return 0;
}


In case you havn't guessed it outputs the sine of PI/3 radians. I want to improve the accuracy currently it outputs 0.866025. I want more. If anyone can tell me how to get it or point me towards some methods. Please post any suggestions you may have on how to improve it.

##### Share on other sites
Use a series which converges faster. :/

##### Share on other sites
For speed, do the factorial using a precalculated lookup table instead of as a function. Also pow(-1, n) simply returns 1 or -1 so why not use this as the numerator:
(n&1 ? -1.0 : 1.0);

Anyway, I assume that you're running out of accuracy because the factorial begins to overflow an unsigned int. Have you tried using an __int64 ?
You could probably find some number class that supports HUGE numbers if you serach the net. I remember one called Bigint so you could google for that.

Happy learning!

Edit: Had the minus sign above in the wrong place.

[Edited by - iMalc on October 1, 2004 3:03:17 PM]

##### Share on other sites
The standard math header for c++ is <cmath>. In c it's <math.h>

It's factorial not fractorial. Maybe you're being funny but it comes across as not knowing your terms.

Instead of using #define which is not part of the c++ language itself, use const double to define a constant floating point value. Also you've got more accuracy than the double can hold.

#include <iostream>
#include <cmath>
const double PI = 3.1415926535897932;

I know it doesn't have anything to do with the method, but you did ask for any suggestions on how to improve it.

##### Share on other sites
I banged it out in about 30 minutes and was not focued on proper codeing style or spelling.

Thanks for all the help guys and I will work on my function.

And yes you are right it is factorial.

• ### Game Developer Survey

We are looking for qualified game developers to participate in a 10-minute online survey. Qualified participants will be offered a \$15 incentive for your time and insights. Click here to start!

• 18
• 13
• 14
• 43
• 63