15,668,517 members
See more:
I just want to write my own sinus function to realise how does it work.

What I have tried:

I've tried to write this using C++. And I found Taylor series.

C++
```long double sinus(double x)
{
long double result = 0.0;
for (int i = 0; i < 100; i++)
{
result += (pow(-1, i - 1)*pow(x, 2 * i - 1)) / Factorial(2 * i - 1);
}
return result;
}```

It is my function and it returns wrong results(Factorial function works correctly).
Posted
Updated 22-Jan-21 23:59pm
v2
Christian Graus 23-Jan-21 2:44am
Do you mean sine? If your result is wrong, your algorithm is wrong
KarstenK 23-Jan-21 4:49am
yes you can, but using the built in functions are bullet proof and long used, so use them and implement your own features.

## Solution 1

CPallini 23-Jan-21 12:36pm
5.

## Solution 2

The Taylor series for `sin(x)` is simple:
`sin(x) = pow(x, 1) - pow(x, 3) / 3! + pow(x, 5) / 5! - ...`
But your implementation does two things: starts with -1 instead of 1, and makes it look a lot more complex than it needs to be. If you don't believe me, work out each term in a short series manually (4 or 5 terms should do) and use the debugger to look at the equivalent terms your code is generating!

Here's a simple implementation in C#:
C#
```static double sin(double x)
{
double result = 0.0;
double sign = 1.0;
for (double power = 1.0; power <= 20.0; power += 2, sign = -sign)
{
result += sign * (Math.Pow(x, power) / factorial(power));
}
return result;
}
static double factorial(double n)
{
double result = 1.0;
while (n > 1.0)
{
result *= n;
n -= 1.0;
}
return result;
}
```
Which gives a result accurate to at least 5 decimal places despite using a much, much shorter series that you do!

You may also need to remember when testing that the Taylor series works in Radians, not Degrees!