Is it possible to do a while loop in C++ until a decimal reaches a certain precision? I want to do a long calculation for arctan and then pi and I want the loop to run until pi is calculated to the 10th decimal place using the formula pi=4(arctan (1.0)). I’m manually calculating arctan using the taylor series formula. I know there are built in functions for these calculations but this is a homework assignment so I have to do it this way. I’m not looking for the solution to the problem, just whether or not a loop using precision is possible. Thanks!
Edit:
I’m still stuck with this! I can’t come up with a proper argument for the while loop, even after going over everybody’s hints. Really need help. Here’s the code I have come up with:
#include <iomanip>
#include <cstdlib>
#include <iostream>
#include <cmath>
using namespace std;
int main(void)
{
int i;
long double result;
long double pi;
int y=3;
int loopcount=0;
long double precision;
cout<<"Start\n";
result=1-(pow(1,y)/y);
do
{
y=y+2;
result=result+(pow(1,y)/y);
y=y+2;
result=result-(pow(1,y)/y);
pi=4*(result);
precision=(pi*(pow(10,11))/10);
loopcount++;
}
while(//This is the problem!);
cout<<"Final Arctan is:"<<endl;
cout<<setprecision(20)<<result<<endl;
cout<<"Final Pi is:"<<endl;
cout<<setprecision(9)<<pi1<<endl;
cout<<"Times looped:"<<endl;
cout<<loopcount<<endl;
return 0;
}
As far as I remember, you can figure out the precision by checking the improvement over the previous iterations. If the 10th decimal place gets stable, break the loop.
to get the kth decimal digit of
n, multiply it by 10 to the power ofkand get the least significant digit. For example, to get the 2nd decimal digit 7 out of 3.47, multiply by 100 to get 347 and get the 7 by347 % 10.