Lab 5
Part 1.
The sine function can be approximated by the following series:
sin( x ) = ∑(n on top, k=0 on bottom of sigma) ( − 1 )^k = x^2k+1 / (2k+1)!
= x − x^3 / 3! + x^5 / 5! − x^7 / 7! ...
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 cmathlibrary. 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.
This is what I have but i dont know what else to do or how to get it to run with the numbers provided in the example. I tried the example and I got close to the answer they got but i cant ever get it exactly. How do I solve this problem?
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
double x, n, answer;
unsigned int factorial, t;
int main()
{
cout << "Enter x:\n";
cin >> x;
cout << "Enter the number of iterations:\n";
cin >> n;
while (x != 7, n != 7)
{
cout << "enter x";
cin >> x;
answer += x - pow(x, n) / factorial;
cout << "answer is " << answer << endl;
}
unsigned int factorial, t;
factorial = 1;
for (t = 1; t <= n; ++t)
factorial = factorial*t;
cout << setprecision(16);
cout << "cmath is " << (pow(-1, n) * pow(x, n)) / factorial << endl;
You will never get the exact same values. It's an inherent problem with floating point numbers in general. Don't worry about it - as long as you are precise to a certain degree, you are fine. Do the first ten decimal places match? That should be more than enough.