Feb 10, 2019 at 11:46pm UTC
Why isn't my program outputting the correct sin value?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
double accuracy=1,n,sinx,x1;
cout << "Enter value of n" << endl;
cin >> n;
n = n * (3.142 / 180.0);
sinx = n;
int i = 1;
do
{
x1 = n;
x1 = -x1 * n * n / (2 * i * (2 * i + 1));
sinx = sinx + x1;
i = i + 1;
} while (abs(accuracy)<=+1e-15);
cout << setprecision(5)<< fixed << showpoint<< sinx;
return 0;
}
Last edited on Feb 10, 2019 at 11:50pm UTC
Feb 11, 2019 at 12:13am UTC
accuracy never changes. And you presumably want to keep the loop going while it's > your limit. As it is, since it equals 1, which is not <= your (somewhat excessive!) limit, the loop exits immediately.
What formula are you using? Do you have a link?
Last edited on Feb 11, 2019 at 12:14am UTC
Feb 11, 2019 at 1:22am UTC
Also, if pi is only 3dp, don't expect your answer to be any better than 3dp either. And you only have setprecision(5), that also makes the limit excessive.
Feb 11, 2019 at 6:08am UTC
x - x^3/3! + x^5/5! - x^7/7!+ ...
- Use a more accurate value of pi.
- Set x1 to n BEFORE the loop, not on line 17. It is the first term of the series.
- If anything one would expect >=
on line 21.
- You should be looking at abs(x1) on line 21; possibly you meant
while (abs(x1)>=accuracy);
, with accuracy
previously set to 1e-15.
- To improve convergence it would be a good idea to subtract integer multiples of 2.pi before evaluating the power series.
- The whole thing would be better in a function, where it could be reused.
- The code would be easier to read and debug if you used better names for variables.
Last edited on Feb 11, 2019 at 8:33am UTC