hey guys, the question asks to
Scan the angle in degrees using x=PI*x_deg/180 and calculate Y=sin^2(x).
Calculate sin^2(x) approximately by using n terms (n>0) the Taylor series
sin(x)=Sum[(-1)^k x^(2k+1)/(2k+1)!] (k goes from 0 to n-1)
Scan an integer value of n. Evaluate (2k+1)! by an embedded for-loo statement. Use two do/while statements to continue the calculations for different n and different x_deg.
Calculate the error between the Y value and the approximate value (y) obtained from the Taylor series with n terms. When calculating this error, use if/else statement: if x_deg is not equal to 0., 180, and 360 degrees, print the Relative Error in percents is 100*(y-Y)/Y; else print the Absolute Error is y-Y.
This is what i have so far.
>>>the problem is that i get the wrong taylor approximation and thus wrong percent error. I think the problem may be with my embedded for-loop/factorial method but i have tried for hours and cant seem to find the porblem.
Scan the angle in degrees using x=PI*x_deg/180 and calculate Y=sin^2(x).
Calculate sin^2(x) approximately by using n terms (n>0) the Taylor series
sin(x)=Sum[(-1)^k x^(2k+1)/(2k+1)!] (k goes from 0 to n-1)
Scan an integer value of n. Evaluate (2k+1)! by an embedded for-loo statement. Use two do/while statements to continue the calculations for different n and different x_deg.
Calculate the error between the Y value and the approximate value (y) obtained from the Taylor series with n terms. When calculating this error, use if/else statement: if x_deg is not equal to 0., 180, and 360 degrees, print the Relative Error in percents is 100*(y-Y)/Y; else print the Absolute Error is y-Y.
This is what i have so far.
Code:
#include<stdio.h>
#include<math.h>
#define PI 4*atan(1.0)
main()
{
double x_deg, x, Y, y1, y2, n_fact;
int ask1, ask2, n_term, k, i;
do
{
printf("\nEnter x_deg: ");
scanf("%lf", &x_deg);
x = x_deg * (PI/180.);
Y = pow(sin(x), 2);
printf("True value of sin^2(x) = %g\n\n", Y);
printf("n_term approximation of sin^2(x)\n\n");
do
{
printf("Enter number of terms: \n");
scanf("%d", &n_term);
printf("%d term approximation\n", n_term);
y1 = 1.0;
for(k=n_term;k>0;k--)
{
n_fact = 1.0;
for(i=(2*k)+1;i>0;i--)
{
n_fact *= i;
}
y1 += (pow(-1,k)/(n_fact+1))*(pow(x,(2*k)+1));
y2 = pow(y1, 2);
}
printf("sin^2(x) = %g\n", y2);
printf("Relative Error = %g percent\n\n", 100*(y2-Y)/Y);
printf("Do you want a new n_term: y=1 or n=0\n");
scanf("%d", &ask2);
}
while(ask2!=0);
printf("Do you want a new x_deg: y=1 or n=0\n");
scanf("%d", &ask1);
} while(ask1!=0);
}
Comment