JeffCoderr - 1 year ago 81

C++ Question

I cannot use the c++ functions

`sin()`

`cos()`

`sin()`

`cos()`

`math.h`

I have so far came up with these, but they seem to not be functioning correctly?

`float sin(float deg) {`

bool neg = false;

while (deg >= 360) deg = deg - 360;

while (deg < 0) deg = deg + 360;

if (deg > 180) {

deg = deg - 180;

neg = true;

}

float ret = (float)(4*deg*(180-deg))/(40500-(deg*(180-deg)));

if (neg)return ret*-1;

return ret;

}

float cos(float AnglesDeg)

{

float AnglesRad = DegreesToRadians(AnglesDeg);

float Rad = (float)(PI/2.0f)-AnglesRad;

float ang = RadiansToDegrees(Rad);

return sin(ang);

}

Answer Source

You can use Taylor Series to implement this by yourself. The code is straight forward:

```
float sine(int deg) {
deg %= 360; // make it less than 360
float rad = deg * PI / 180;
float sin = 0;
int i;
for(i = 0; i < TERMS; i++) { // That's Taylor series!!
sin += power(-1, i) * power(rad, 2 * i + 1) / fact(2 * i + 1);
}
return sin;
}
float cosine(int deg) {
deg %= 360; // make it less than 360
float rad = deg * PI / 180;
float cos = 0;
int i;
for(i = 0; i < TERMS; i++) { // That's also Taylor series!!
cos += power(-1, i) * power(rad, 2 * i) / fact(2 * i);
}
return cos;
}
```

As you said you don't have math.h, I made a simple power function for this algorithm. Also you need a function to calculate factorial nubmers. Here they are:

```
float power(float base, int exp) {
if(exp < 0) {
if(base == 0)
return -0; // Error!!
return 1 / (base * power(base, (-exp) - 1));
}
if(exp == 0)
return 1;
if(exp == 1)
return base;
return base * power(base, exp - 1);
}
int fact(int n) {
return n <= 0 ? 1 : n * fact(n-1);
}
```

PI and TERMS were just preprocessor directives (`#define`

's) I used, being PI 3.14159 (in my case I used a 50 digits precision pi, what is completely unnecessary) and TERMS being 7.