Sign in to follow this  
monkey_32606

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

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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this