Compute cos( P/4) The last line of the derivation of the Maclaurin series for co
ID: 641353 • Letter: C
Question
Compute cos(P/4)
The last line of the derivation of the Maclaurin series for cosine above shows how to compute cosine to full machine precision using a sum.
You may use a macro for PI:
# define PI 3.14159265358979323846 /* pi */
You will need to use a double values to hold your various sum and product variables. Output approximations using 4,6,8 and 10 terms of the series. Also display the absolute and relative errors in each approximation. Assuming a variable named approximation holds your approximation and a variable cosx hold the actual value, the computations would be: absolute_error = fabs(cosx-approximation) and relative_error = fabs(cosx-approximation)/cosx. Note that the abs() function in C uses an int argument and returns an int result, which is not sufficiently precise for our problem, so you must use fabs(). The correct value of cos(P/4) can be determined to full double precision using the circular function cos(P/4) defined in the #include <cmath> file
Explanation / Answer
The series is given as summation ((-1)k x2k) / 2k!
taking x = p/2,
in c we use a loop to calculate the value for the above expression for 4,6,8,10 terms using a for loop where k will take the value 1-4, 1-6,1-8,1-10.
we can calculate the error using the given functions and compare them.
# include
#include
# define PI 3.14159265358979323846
int j,k;
float summa, x=PI/2;
double cosx-approximation, relative_error;
main()
{
{ kfact = 1;
for(k=1;k<4;k++)
{ kfact = kfact *k;
summk = summk+ (pow(-1,k) * pow(x,2k)) / 2*kfact);
}
absolute_error = fabs(summk);
relative_error = fabs(summk)/ cosx;
printf("summation for 4 terms")
printf ( "%f %f %f", summk, absolute_error, relative error);
for(k=1;k<6;k++)
{ kfact = kfact *k;
summk = summk+ (pow(-1,k) * pow(x,2k)) / 2*kfact);
}
absolute_error = fabs(summk);
relative_error = fabs(summk)/ cosx;
printf("summation for 6 terms")
printf ( "%f %f %f", summk, absolute_error, relative error);
for(k=1;k<8;k++)
{ kfact = kfact *k;
summk = summk+ (pow(-1,k) * pow(x,2k)) / 2*kfact);
}
absolute_error = fabs(summk);
relative_error = fabs(summk)/ cosx;
printf("summation for 8 terms")
printf ( "%f %f %f", summk, absolute_error, relative error);
for(k=1;k<10;k++)
{ kfact = kfact *k;
summk = summk+ (pow(-1,k) * pow(x,2k)) / 2*kfact);
}
absolute_error = fabs(summk);
relative_error = fabs(summk)/ cosx;
printf("summation for 10 terms")
printf ( "%f %f %f", summk, absolute_error, relative error);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.