-
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??
-
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!
-
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....
-
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).
-
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.
-
Re: Write a C++ program to compute Sin(x)
How many times should I make the loop go on if not 1000??
-
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.
-
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)
-
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
-
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;
}
-
Re: Write a C++ program to compute Sin(x)
Quote:
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!
-
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.
-
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
-
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.
-
Re: Write a C++ program to compute Sin(x)
:thumb: yeah - I missed the -rad * rad !
-
Re: Write a C++ program to compute Sin(x)
I've modified the code in #13 somewhat to give it a more functional touch. It's part of a learning project I have started to try and soften up my strictly object oriented code with more functional elements.
Code:
long double Sine3(const double ang, const unsigned int N) {
constexpr long double PI = 3.14159265358979323846;
auto sinmap = [PI] (long double x) { // maps x to an angle wth same sin() value inside [-PI/2 .. PI/2]
auto m = std::fmod(x, PI*2); // x is mapped on [-2PI .. 2PI]
m = (m > PI) ? m - PI*2 : (m < -PI) ? m + PI*2 : m; // then on [-PI .. PI]
return (m > PI/2) ? PI - m : (m < -PI/2) ? -PI - m : m; // finally on [-PI/2 .. PI/2]
};
const auto RAD = sinmap(ang * PI/180); // convert ang to radians and map inside [-PI/2 .. PI/2]
// recursively generates the terms of the Maclaurin sin() series and adds them up
using ResFun = std::function<long double (long double, unsigned long long int, long double, unsigned int)>;
ResFun resfun = [&resfun, RAD, N] (long double res, unsigned long long int dem, long double num, unsigned int nn) {
const auto r = res + num/dem; // add term
const auto n = nn + 2; // next
return (n >= 2*N) ? r : resfun(r, dem*n*(n-1), num*(-RAD*RAD), n); // exit or make tail recursive call
};
return resfun(0.0, 1U, RAD, 1);
}
The most important change is that the iterative loop of the original has been replaced by recursion. Using recursion instead of iteration is a hallmark of the functional style. Since I've used tail recursion a good optimizing compiler should be able to turn it into iteration so the performance should be on par with the original iterative loop. What bothers me is that I don't see very many advantages with recursion, at least not in this case. Too me it looks more like a complication, verbose and convoluted.
-
Re: Write a C++ program to compute Sin(x)
Quote:
Too me it looks more like a complication, verbose and convoluted.
Yeah. I've looked a little into functional programming with c++ and so far I'm left underwhelmed at the potential additional complexity required - for what seems to me at the moment for extremely little gain. There are first-class functions (basically having a function type - which has been possible since early c days - and which I've used extensively over the years), pure functions (which is really good practice anyhow - and much better now that return values are not copied!) and immutable functions (which often seem to require tortuous ways to get around - such as recursion). I get the reasons for first-class and pure functions (which I've been doing but calling it good practice not functional programming!) but I'm still struggling to understand why immutable functions.
I would be interested in any guru who has a real-word case where immutable function(s) offer any benefit over other methods.
-
Re: Write a C++ program to compute Sin(x)
Code:
auto sinmap = [PI] (long double x) { // maps x to an angle wth same sin() value inside [-PI/2 .. PI/2]
auto m = std::fmod(x, PI*2); // x is mapped on [-2PI .. 2PI]
m = (m > PI) ? m - PI*2 : (m < -PI) ? m + PI*2 : m; // then on [-PI .. PI]
return (m > PI/2) ? PI - m : (m < -PI/2) ? -PI - m : m; // finally on [-PI/2 .. PI/2]
};
as sinmap is mutable, what about
Code:
auto sinmap = [PI] (const long double x) { // maps x to an angle wth same sin() value inside [-PI/2 .. PI/2]
const auto m = std::fmod(x, PI*2); // x is mapped on [-2PI .. 2PI]
const auto m1 = (m > PI) ? m - PI*2 : (m < -PI) ? m + PI*2 : m; // then on [-PI .. PI]
return (m1 > PI/2) ? PI - m1 : (m1 < -PI/2) ? -PI - m1 : m1; // finally on [-PI/2 .. PI/2]
};
Then isn't sine3() then immutable? - but why??
-
Re: Write a C++ program to compute Sin(x)
Quote:
Originally Posted by
2kaud
as sinmap is mutable, what about
You're right. That's what sinmap() should look like according to the functional paradigm. (I did it in resfun() but not in sinmap() for some inscrutable reason.)
In the lingo of a book I'm reading it's called assignment-less programming. This is an assignment,
auto m = .....;
whereas this is not, it's an evaluation of an expression making m and the right-hand side expression forever the same,
const auto m = .....;
According to the author, writing assignment-less code is as important in functional programming as it is not to use goto in structured programming. I'm not entirely convinced but hopefully it becomes obvious further down the road.
-
Re: Write a C++ program to compute Sin(x)
Quote:
of a book I'm reading
Which one? What's your view on it?
Quote:
writing assignment-less code is as important in functional programming as it is not to use goto in structured programming
Yes, that's what I've come across as well. But what I'm not seeing is a good explanation for c++ specifically as to why. Much of what I've seen is 'this is how the xyx functional language requires it to be done'. Well for a 'pure functional' language that's fine. You learn how things are done in specific languages. For c++, I've seen this is how you can implement 'functional' programming. However what benefits does this style of programming bring to c++??????? At the moment, like you, all I'm seeing is complexity and potential performance issues.
-
Re: Write a C++ program to compute Sin(x)
Quote:
Originally Posted by
2kaud
Which one? What's your view on it?
The book is called Functional Programming by MacLennan. There are two reviews at Amazon and especially the one by Rahman is on the spot. I couldn't find a preview of the book anywhere so I settled for a cheap used copy not to buy a pig in a poke. The book was published in 1989 and is a typical CS textbook but with a more accessible style than most. The reference programming paradigm is structured programming. OO is not mentioned.
I'm not planning to study the book, just browse it to build an understanding of FP without the hype and dogma often found in contemporary texts. For example I've learned that although a function may be recursively defined that doesn't mean it has to be implemented using recursion to count as FP. Needless recursion should be avoided in the name of efficiency. This nugget of information alone is worth the cost of the book to me, and there is more of the same.
I wouldn't say the book is essential but I'm glad to have it as reference. I like the tone of the author and I can extract general knowledge without having to dwell too much on technical detail. I would love this author to come back and compare and contrast FP with OO from today's perspective.
Quote:
However what benefits does this style of programming bring to c++??????? At the moment, like you, all I'm seeing is complexity and potential performance issues.
I'm eagerly awaiting the release of Functional Programming in C++ by Cukic which I hope will show how and why FP may be useful to C++ programmers.
In a non-dedicated functional language such as C++ I think immutability becomes a key concept. It means the const keyword could be an important (and so far overlooked) tool to accomplish more functional code. Who writes: Functional C++ the Const Way? :)
-
Re: Write a C++ program to compute Sin(x)
Code:
#include <iostream>
#include <cmath>
using namespace std;
int Sinp(int x, int n)
{
int y = 0;
int i = 1;
int fSum = 0;
int fFactorial = -1;
while (i <= n * 2)
{
for (y = 1; y <= i; y = y + 1)
{
fFactorial = -fFactorial * y;
}
fSum = fSum + pow(x,i) / fFactorial;
i = i + 2;
}
return fSum;
}
int main(void)
{
int n = 0;
int x = 0;
cout << " Please enter the value of x. " << endl;
cin >> x;
cout << " Please enter the number of terms. " << endl;
cin >> n;
cout << Sinp(x,n) << endl;
return 1;
}
-
Re: Write a C++ program to compute Sin(x)
[When posting code, please use code tags so that the code is readable and formatted. Go Advanced, select the formatted code and click '#']
Cheers!
... and this adds what to this thread discussion? It's not efficient and its not the best c++ code. What is this supposed to add to the code in post #13 and post #16?? :confused:
It also doesn't compute the value correctly. The series summation for sine() is based upon the value being in radians - not degrees. So only whole integer radians can be entered - and even then the answer is incorrect. The sine(1) for 1 radian is 0.84147. But for this program the answer for 6 terms is 0 and for 10 terms is -2147483648. :thumbd: