I'm trying to work out the arctan of a number using the formula:
arctan(x) = x - x^3/3 + x^5/5 - x^7/7...
I have to calculate it to 20 decimal places. The answer should be 0.78539....
This is the code I have written, including some debugging statements. The problem is in the calculation I think but I just can't see it. Could someone point me in the right direction please?
EDIT : Can't use the atan function, has to be manually calculated using a double variable from user input.
#include <iomanip>
#include <cstdlib>
#include <iostream>
#include <cmath>
using namespace std;
int main(void)
{
double x;
int i;
int j;
int y=3;
cout<<"Please enter the number you wish to calculate the arctan of:"<<endl;
cin>>x;
//Calculate arctan of this number
cout<<x;
cout<<"\n";
cout<<y;
cout<<"\n";
cout<<"Start\n";
x=x-(pow(x,y)/y);
y=y+2;
cout << setprecision (20) << x;
cout<<"=x before loop\n";
cout<<y;
cout<<"=y before loop\n";
for(i=0;i<9;i++)
{
x=x+(pow(x,y)/y);
cout<<x;
cout<<"=x1 in loop\n";
y=y+2;
cout<<y;
cout<<"=y1 in loop\n";
x-(pow(x,y)/y);
cout<<x;
cout<<"=x2 in loop\n";
y=y+2;
cout<<y;
cout<<"=y2 in loop\n";
}
return 0;
}
Well, your x
is changing! You probably want to use a different variable to store the value computed so far and the argument to your function. That said, don't expect to precise outputs because all those computations involve rounding.
This line:
x-(pow(x,y)/y);
might have something to do with your problem.
I would strong advise you use the inbuilt atan function, it is more than likely been well optimised for you architecture, as well as being a standard function recognised by most C++ programmers.
#include <cmath>
#include <iostream>
int main()
{
double d;
std::cout << "enter number" << std::endl;
std::cin >> d;
std::cout << "atan of: " << d
<< " is " << std::atan(d)
<< std::endl;
return 0;
}
I agree with @Mystical. I don't think you're going to get 20 digits of precision out of a double. I think you need a long double (if that exists on your system) or, perhaps you need to implement your own big-num class...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.