
November 8th, 2012, 04:28 AM
#1
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;
}
I have to submit it this weekend. So please help me what am i doing wrong??

November 8th, 2012, 04:30 AM
#2
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, 05:05 AM
#3
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....
Victor Nijegorodov

November 8th, 2012, 05:56 AM
#4
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).
Last edited by Philip Nicoletti; November 8th, 2012 at 08:06 AM.

November 8th, 2012, 06:36 AM
#5
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, 01:41 PM
#6
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, 03:30 PM
#7
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 10e6), and stop iterating
when the term that you calculate is less than or equal to the tolerance.

November 9th, 2012, 04:00 AM
#8
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, 09:21 AM
#9
Re: Write a C++ program to compute Sin(x)
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:
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, 01:44 PM
#10
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;
}
Last edited by 2kaud; February 16th, 2018 at 04:54 AM.
Reason: Added code tags

February 15th, 2018, 01:50 PM
#11
Re: Write a C++ program to compute Sin(x)
Originally Posted by prans
//Use this one is somewhat similar
...
Please, read the post#3.
And note that you should have done it BEFORE posting your reply!
Victor Nijegorodov

February 16th, 2018, 04:57 AM
#12
Re: Write a C++ program to compute Sin(x)
As Victor reiterates 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.  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.
Last edited by 2kaud; February 16th, 2018 at 04:39 PM.
All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only  not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums  and not via private messages!
C++17 Compiler: Microsoft VS2017 (15.8.4)

February 16th, 2018, 08:10 AM
#13
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
Last edited by 2kaud; February 19th, 2018 at 04:42 AM.
Reason: Changed as per comments in post #14
All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only  not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums  and not via private messages!
C++17 Compiler: Microsoft VS2017 (15.8.4)

February 16th, 2018, 04:35 PM
#14
Re: Write a C++ program to compute Sin(x)
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 branchfree.
Last edited by wolle; February 17th, 2018 at 05:12 AM.

February 16th, 2018, 04:46 PM
#15
Re: Write a C++ program to compute Sin(x)
yeah  I missed the rad * rad !
All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only  not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums  and not via private messages!
C++17 Compiler: Microsoft VS2017 (15.8.4)
Tags for this Thread
Posting Permissions
 You may not post new threads
 You may not post replies
 You may not post attachments
 You may not edit your posts

Forum Rules

Click Here to Expand Forum to Full Width
OnDemand Webinars (sponsored)
