Part 1. The sine function can be approximated by the following series: Using thi
ID: 643331 • Letter: P
Question
Part 1. The sine function can be approximated by the following series: Using this approximation, write a program that asks the user to enter x and n (the number of iterations). The program will use the above approximation to calculate the sine of x for the given number of iterations. Do NOT use any function libraries for this. After this, compare the answer to the value obtained by the cmath library. Output answers to as many decimal places as possible with double precision variables. Example Output: Enter the number of iterations: 5 Enter x: 1.99 Answer is: 0.91346070603290475 cmath: 0.91341336134122519 difference is: 0.00004734469167954 Press any key to continue . . . Part 2. Run the program with the following inputs: Number of iterations: 12 X: 12.0 What is the difference between the approximation and the cmath value? Repeat for 24 iterations. What conclusion can be drawn from the difference between n = 12 and n=24 (n is the number of iterations)? Attempt to calculate the sine of 150 radians. How can your code be modified so that large values of x can be calculated? (Hint: The sine function repeats every 2Pi radians so values below -Pi and above +Pi can be shifted close to zero) Make the code modification.Explanation / Answer
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int fact(int n){
int val = 1;
for(int i = 1; i <= n; ++i){
val *= i;
}
return val;
}
int main(){
int n;
double x;
cout << "Enter the number of iterations: ";
cin >> n;
cout << "Enter x: ";
cin >> x;
double sinx = 0;
for(int i = 0; i < n; ++i){
if((i + 1) % 2 == 1)
sinx += pow(x, 2 * i + 1) / fact(2 * i + 1);
else
sinx -= pow(x, 2 * i + 1) / fact(2 * i + 1);
}
cout << "Answer is " << setprecision(17) << sinx << endl;
cout << "cmath is " << setprecision(17) << sin(x) << endl;
cout << "difference is " << setprecision(17) << abs(sinx - sin(x)) << endl;
return 0;
}