In: Computer Science
Write an overloaded procedure using c++ for approximating the value of cos(x), called approx_cos. This procedure should work as follows:
A call such as approx_cos(double x, long N) should produce the Nth order Taylor approximation of the cosine function at the point x. You of course need the derive this Taylor expansion in order to implement it.
A call such as approx_cos(double x) should approximate the value of the cosine function evaluated at the point x, to at least eight digits of accuracy. The Taylor Remainder Theorem helps us understand how to mathematically obtain such a result.
Of course you should write a main() procedure that checks the validity of this procedure and compare it to the true value of cosine at several points (not just x=0).
#include <iostream> #include <cmath> using namespace std; double approx_cos(double x) { double lastResult = 0; double result = 1; double lastTerm = 1; int i=1; while(abs(result - lastResult) > pow(10, -6)) { lastResult = result; lastTerm = -1 * lastTerm * (x * x)/(2*i * (2*i - 1)); result += lastTerm; i++; } return result; } double cosine(double x, long n) { double result = 1; double lastTerm = 1; for(int i=1; i<=n; i++) { lastTerm = -1 * lastTerm * (x * x)/(2*i * (2*i - 1)); result += lastTerm; } return result; } int main() { cout << cos(M_PI/8.0) << endl; cout << cosine(M_PI/8.0, 100) << endl; cout << approx_cos(M_PI/8.0) << endl; }
************************************************** Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.