Answer to Question #163929 in C++ for Rishabh

Question #163929

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;”.


1
Expert's answer
2021-02-15T14:16:31-0500

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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment