I'm trying to create a program that computes the values of cos using the Taylor Series
as long as the absolute value of a term is greater than 0.0001 and prints the
number of terms used in the series approximation. My code is the following and as of right now I am getting the wrong result. Please help me fix it! I've spent hours trying to figure it out and don't know what to do.
Enter the angle in radians: 3.14
There were 8 numbers of terms used in the series approximation.
The calculated cosine of 3.14 is 0.00499852
The C++ cosine of 3.14 is -0.999999
// Pre-processor Directives
#include<iostream> // Required for for use of cin, cout
#include<cmath> // Required for use of sin, cos, pow functions
#include <iomanip>
// using directives
using namespace std;
// PROGRAM STARTS HERE!
double factorial(double x);
double calculate(double ang);
// Declaration of the main function
int main()
{
// Declare variables
double angle;
double calccos;
double cosine;
// Ask for user input
cout << "Enter the angle in radians: ";
cin >> angle;
// Compute the value of cos using a function
calccos = calculate(angle);
// Compute the actual value of cos
cosine = cos(angle);
// Display the result
cout << "The calculated cosine of " << angle << " is " << calccos << endl;
cout << "The C++ cosine of " << angle << " is " << cosine << endl;
// Exit program.
system("PAUSE");
return 0;
}
// Calculate the factorial
double factorial(double x)
{
if (x <= 1)
{
return 1;
}
else
{
return (x * factorial(x-1));
}
}
double calculate(double ang)
{
// Declare the variables
double temp;
int count = 0;
double x;
// For Loop
for (int i=1; i<=100; i+=2)
{
// Test the values
if ( i==1 || fabs(x) >.0001)
{
if ( count % 2 == 0)
{
temp = temp + (pow(ang, i+1)/factorial(i));
}
if ( count % 2 == 1)
{
temp = temp - (pow(ang, i+1)/factorial(i));
}
count++;
x= pow(ang, i+1)/factorial(i);
}
}
// Display the number of terms in the series
cout << "There were " << count << " numbers of terms used in the series approximation. " << endl;
return temp;
}