Hi, I want to make this forum on how to calculate the sine and cosine in c++ without the STL. I'm sorry if my grammar is not accurate. Well let's get started:
There are several methods to calculate sine and cosine and any other transcendent function.
The Taylor series, polynomial approximations and the CORDIC algorithm "for sine and cosine" are some of these methods.
There are occasions where we have to calculate the same Angle for sine and cosine functions for those cases we can create a single function.
The next function receives 3 parameters the first is the same radian for the cosine and sine and the last two are two variables by reference to store these values. I must clarify that this function has only been tested in video games has not been used for another purpose. This function uses a polynomial approximation.
void sameRadian(const float& rad, float& c, float& s)
{
union{int i; float f;} u;
u.i = int(rad * 0.31830988f + 0.5f);
c = (u.i % 2)? 3.14159265f * u.i - rad - 1.570796f : rad + 1.570796f - 3.14159265f * u.i;
u.i = int(rad * 0.31830988f);
s = (u.i % 2)? 3.14159265f * u.i - rad : rad - 3.14159265f * u.i;
//Calculando La Funcion Coseno
if(c < 0.0f)
{
u.f = (1.273239f + c * 0.405284f) * c;
c = (u.f + 1.0f) * u.f * -0.225f + u.f;
}
else
{
u.f = (1.273239f - c * 0.405284f) * c;
c = (u.f - 1.0f) * u.f * 0.225f + u.f;
}
//Calculando La Funcion Seno
if(s < 0.0f)
{
u.f = (1.273239f + s * 0.405284f) * s;
s = (u.f + 1.0f) * u.f * -0.225f + u.f;
}
else
{
u.f = (1.273239f - s * 0.405284f) * s;
s = (u.f - 1.0f) * u.f * 0.225f + u.f;
}
}
There are several constants and they were placed directly for speed reasons.
Here are the two separate functions.
float cosf2(const float& rad)
{
union{int i; float f;} u;
u.i = int(rad * 0.31830988f + 0.5f);
u.f = (u.i % 2)? 3.14159265f * u.i - rad - 1.570796f : rad + 1.570796f - 3.14159265f * u.i;
//Calculando La Funcion Coseno
if(u.f < 0.0f)
{
u.f = (u.f * 0.405284f + 1.273239f) * u.f;
return (u.f + 1.0f) * u.f * -0.225f + u.f;
}
else
{
u.f = (1.273239f - u.f * 0.405284f) * u.f;
return (u.f - 1.0f) * u.f * 0.225f + u.f;
}
}
float sinf2(const float& rad)
{
union{int i; float f;} u;
u.i = int(rad * 0.31830988f);
u.f = (u.i % 2)? 3.14159265f * u.i - rad : rad - 3.14159265f * u.i;
//Calculando La Funcion Seno
if(u.f < 0.0f)
{
u.f = (1.273239f + u.f * 0.405284f) * u.f;
return (u.f + 1.0f) * u.f * -0.225f + u.f;
}
else
{
u.f = (1.273239f - u.f * 0.405284f) * u.f;
return (u.f - 1.0f) * u.f * 0.225f + u.f;
}
}
well thanks to you for reading my forum.