Write a program that takes as input two numbers n (integer) and x (double), and prints arctan(x) evaluated by taking n terms of the Taylor series (using x0 =0):
arctan(x) = x - x 3 /3 + x 5 /5 - x 7 /7 …
To care of numerical accuracy and rounding off we have created a print(x) function. Please use this to print your final answer. Suppose your answer is in a variable called ans, then print it to screen using “print(ans);” and NOT “cout << ans;”.
Note: by the statement of the problem, the resulting value of the arctan should be printed using the "print (x)" function, but since its implementation is not provided in question, I wrote my own implementation of this function.
#include <iostream>
void print(double value)
{
std::cout << "arctan = " << value << "\n";
}
int main()
{
std::cout << "Please enter a integer (0 <= n) and double (-1 <= x <= 1) numbers: ";
int n;
double x;
std::cin >> n >> x;
if(!std::cin || n < 0 || x < -1 || x > 1)
{
std::cout << "Bad input\n";
return 1;
}
int sign = 1;
double powX = 1;
int divider = 1;
double ans = 0;
for(int i=0; i<n; ++i)
{
ans += sign * x * powX / divider;
sign = -sign;
powX *= x * x;
divider += 2;
}
print(ans);
return 0;
}
Comments
Leave a comment