# Write a C++ program to compute Sin(x)

Show 50 post(s) from this thread on one page
Page 1 of 2 12 Last
• November 8th, 2012, 03:28 AM
weirdom3
Write a C++ program to compute Sin(x)
Hi. I'm having problem writing this program as my assignment. I've spent hours on this but still i can't get the right answer.

Here is the question:
Write a C++ program to compute Sin(x) where

x x^3 x^5 x^7 x^9 x^n
sin (x) = ----- ─ ---- + ---- ─ ---- + ----- ─ …………. ------
1! 3! 5! 7! 9! n!

Your program should accept two values from the user (the angle x and the value of n) and then should compute and print the value of sin(x).

To make the program, do following tasks.

• Write two functions, i.e. function to calculate factorial and function to calculate power having following prototypes.
double Factorial (int n); //Factorial function prototype
double Power(double x, int y); //Power function prototype
• Use these functions in your main function to compute the series.

Till now, I've written the following program but I am not able to get the right answer.

#include <iostream>
using namespace std;

double fact (int f); //declaration of factorial function

double power(double x, int y); //declaration of power function

int main()
{
int x=0; //value of x in the series
float sum_pos = 0;
float sum_neg=0;
float t_sum=0;

cout << "Enter the value of x: " << endl;
cin >> x;

for (int i=1; i<=1000; i+=4)
{
sum_pos = sum_pos + (power (x,i) / fact (i));
}

for (int i=3; i<=1000; i+=4)
{
sum_neg = sum_neg + (power (x,i) / fact (i));
}

t_sum = sum_pos - sum_neg;

cout << "Sin of " << x << " = " << t_sum << endl;

return 0;
}

//Function for Factorial
double fact (int x)
{
double f=1;

if (x==0)
{
return f;
}

else
for (int i=1; i<=x; i++)
{
f=f*i;
}

return f;
}

//Function for Power
double power (double x, int y)
{
int p=1;

for (int i=1; i<=y; i++)
p=p*x;

return p;
}

• November 8th, 2012, 03:30 AM
weirdom3
Re: Write a C++ program to compute Sin(x)
the series is:

x x^3 x^5 x^7 x^9 x^n
sin (x) = ----- ─ ---- + ---- ─ ---- + ----- ─ …………. ------
1! 3! 5! 7! 9! n!
• November 8th, 2012, 04:05 AM
VictorN
Re: Write a C++ program to compute Sin(x)
You have to use Code tags to properly format the posted code and formulas.
See Announcement: Before you post....
• November 8th, 2012, 04:56 AM
Philip Nicoletti
Re: Write a C++ program to compute Sin(x)
1) you have "x" declared as int instead of double in main()
and the "p" variable declared as int instead of double in power()

2) You should use "double" instead of "float"

3) fyi : "x" is in radians, not degrees

4) There is no need to go all the way to "i=1000" ..., write a small program
that just prints out fact(i), you will see a problem.

5) The equation that you are using is best suited for x values near zero.
You can use trig identities to make the value of "x" smaller before
calculating the sin (example : sin(x + 2*pi) = sin(x)... So there is no need
to use any value greater than 2*pi. And actually, that range can be reduced
significantly using other trig identities).
• November 8th, 2012, 05:36 AM
OReubens
Re: Write a C++ program to compute Sin(x)
Also note that the above formula calculates sin(x) where x is in radians, not in degrees.
if you are trying to manually check if a certain value matches what you get on a calculator, then you need to set your calculator to radians.

a 30° angle would be Pi/6 radians so your function should be returning sin( pi/6 ) or sin( 0.5235987755983 ) as being (more or less) equal to 0.5

But as philip posted above, your real problem is in trying to make your program "too good". You're causing a problem by making the loop go to 1000.
• November 8th, 2012, 12:41 PM
weirdom3
Re: Write a C++ program to compute Sin(x)
How many times should I make the loop go on if not 1000??
• November 8th, 2012, 02:30 PM
Philip Nicoletti
Re: Write a C++ program to compute Sin(x)
What type of course is this for ? If a numerical analysis course, the
error for truncated a Taylo series should be given in the text book.

At any rate ... you ahve an alternating series that is monotomically
decreasing, the absolute value of the error when stopping the series
at a certain term is less than or equal to the first dropped term.

In pratical terms, choose a tolerance (say 10e-6), and stop iterating
when the term that you calculate is less than or equal to the tolerance.
• November 9th, 2012, 03:00 AM
OReubens
Re: Write a C++ program to compute Sin(x)
Computers deal with numerical types that have operational constraints.

A double for instance has an upper bound of the largest number it can contain. This upper bound has a define DBL_MAX which is 1.797E+308. If you are making calculations and any (intermediate) value you calculate exceeds the operational constraints you get overflow (or underflow, or one of several other undesired effects). Once this happens, all bets are off concerning the end result, you could get results that make absolutely no sense at all.

Dealing with floating point numbers correctly posses additional problems. Floating point values are NOT accurate values, they are approximations. Each value has a slight error to it. Depending on how you deal with the numbers you can continuously accumulate more error into your intermediate results (or worse, scale/multiply it). This too can throw your results off whack.

For taylor series specifically there are ways to calculate how much iterations you need to achieve the desired precision. And when dealing with floating point, there are ways to reduce error accumulation. And there are ways to figure out if floating point error would exceed the desired precision meaning calculation isn't possible with the current algorithm or the used floating point type.

I doubt all the above is relevant for you, if this is a simple course, then see if you have an iteration value in the text book. If that is not there, you will need to to find an iteration in such a way that none of the intermediates overflow. In short, find an i where power(i) and fact(i) never exceed 1.797E+308 (to avoid precision loss, you probably do NOT want to not the highest possible i that meets this requirement, but want an i that's a bit lower)
• November 9th, 2012, 08:21 AM
Peter_B
Re: Write a C++ program to compute Sin(x)
Quote:

Originally Posted by weirdom3
How many times should I make the loop go on if not 1000??

Rule 1: Always read the problem statement carefully. As you said in your first post:

Quote:

Originally Posted by weirdom3
Here is the question:
Write a C++ program to compute Sin(x) where

x x^3 x^5 x^7 x^9 x^n
sin (x) = ----- ─ ---- + ---- ─ ---- + ----- ─ …………. ------
1! 3! 5! 7! 9! n!

Your program should accept two values from the user (the angle x and the value of n) and then should compute and print the value of sin(x).

See the bits in red? You are only asking for x, not n
• February 15th, 2018, 12:44 PM
prans
Re: Write a C++ program to compute Sin(x)
Code:

```//Use this one is somewhat similar #include <iostream> #include<iomanip> using namespace std; double fact (int f); //declaration of factorial function double power(double x, int y); //declaration of power function int main() {     int n;     int x=0; //value of x in the series     float sum_pos = 0;     float sum_neg=0;     float t_sum=0;     cout << "Enter the value of x:and n: " << endl;     cin >> x>>n;     if (n != 0) {         for (int i = 1; i <= n + 2; i += 4)         {             sum_pos = sum_pos + (power (x, i) / fact (i));         }         for (int i = 3; i <= n + 2; i += 4)         {             sum_neg = sum_neg + (power (x, i) / fact (i));         }         t_sum = sum_pos - sum_neg;         cout <<fixed<<setprecision(2)<< t_sum << endl;     }     else     {         int k = 5;         for (int i = 1; i <= k + 5; i += 4)       {             sum_pos = sum_pos + (power (x, i) / fact (i));       }         for (int i = 3; i <= k + 2; i += 4)         {             sum_neg = sum_neg + (power (x, i) / fact (i));         }         t_sum = sum_pos - sum_neg;         cout <<fixed<<setprecision(2)<< t_sum << endl;     }      return 0; } //Function for Factorial double fact (int x) {     double f=1;     if (x == 0)     {         return f;     }     else         for (int i = 1; i <= x; i++)         {             f = f * i;         }     return f; } //Function for Power double power (double x, int y) {     int p=1;     for (int i = 1; i <= y; i++)         p = p * x;     return p; }```
• February 15th, 2018, 12:50 PM
VictorN
Re: Write a C++ program to compute Sin(x)
Quote:

Originally Posted by prans
//Use this one is somewhat similar
...

And note that you should have done it BEFORE posting your reply!
• February 16th, 2018, 03:57 AM
2kaud
Re: Write a C++ program to compute Sin(x)
As Victor re-iterates in his post #11, please use code tags when posting code so that the code is readable. Go Advanced, select the formatted code and click '#'.

Also note that this is one of the worst implementations of a Taylor (actually a Maclaurin) series I have come across. :thumbd: - even though this method is what was required in the OP post #1. For any readers of this thread, please don't calculate series like this.
• February 16th, 2018, 07:10 AM
2kaud
Re: Write a C++ program to compute Sin(x)
For a 'better' implementation consider

Code:

```#define _USE_MATH_DEFINES #include <iostream> #include <iomanip> #include <cmath> using namespace std; //ang is in degrees long double Sine(double ang, unsigned int n) {         bool neg = false;         ang = fmod(ang, 360.0);         if (ang < 0.0)                 ang = 360.0 + ang;         if (ang >= 180.0) {                 ang -= 180.0;                 neg = true;         }         if (ang > 90.0)                 ang = 180.0 - ang;         const long double rad = ang * M_PI / 180.0;         long double num = rad;         unsigned long long int dem = 1;         long double res = rad;         for (unsigned int nn = 3, nnmax = 2 * n; nn < nnmax; nn += 2) {                 dem *= nn * (nn - 1);                 num *= -rad * rad;                 res += num / dem;         }         return neg ? -res : res; } int main() {         double ang;         cout << "Enter angle (in degrees): ";         cin >> ang;         unsigned int n;         cout << "Enter number of terms: ";         cin >> n;         cout << setw(15) << setprecision(13) << Sine(ang, n) << endl; }```
For a test example, consider

Code:

```Enter angle (in degrees): 45 Enter number of terms: 10 0.7071067811865```
• February 16th, 2018, 03:35 PM
wolle
Re: Write a C++ program to compute Sin(x)
Quote:

Originally Posted by 2kaud
For a 'better' implementation consider

Original loop:

Code:

```        for (unsigned int nn = 1; nn < n; ++nn) {                 const unsigned int i =  nn * 2 + 1;                 dem *= i * (i - 1);                 num *= rad * rad;                 if (nn % 2)                         res -= num / dem;                 else                         res += num / dem;         }```

If speed is important the above loop can be changed like this,

Code:

```        for (unsigned int nn = 3; nn < 2*n; nn += 2) {                 dem *= nn * (nn - 1);                 num *= -rad*rad;                 res += num / dem;         }```
There are fewer operations and it's now branch-free.
• February 16th, 2018, 03:46 PM
2kaud
Re: Write a C++ program to compute Sin(x)