Answer the question
In order to leave comments, you need to log in
Taylor expansion of cosec in C++?
Please help me solve the problem. You need to write a program that calculates the value of cosec with some error (epsilon) using the expansion in a Taylor series.
My version
double cosec_func(double X, double epsilon)
{double n=0,sum=0;
while(abs(f(n,sum)-f(n+1,sum))<epsilon)
{
sum=f(n,sum);
n++;
}
return (1/X)+f(n,sum);
}
double fact(double x)
{
if (x<=1) return 1;
else return x*fact(x-1);
}
double f(double n, double sum)
{
sum += ( 2*(pow(2,2*n+1)-1) ) /( fact(2*n+2));
return sum;
}
Answer the question
In order to leave comments, you need to log in
I advise you to almost completely rewrite the code, optimizing it well. For example, it makes no sense to find 2^(2n+1) every time, knowing the value of 2^(2n-1). The same goes for factorial.
As a result, finding the cosine will fit in 1 cycle, and to determine whether the required accuracy has been achieved, it will not be necessary to call two rather expensive functions twice.
UPD. And in this condition:
there should be a sign greater than
UPD2. for double and float it is better to use a function
double fabs (double x);
float fabs (float x);
long double fabs (long double x);
double sin(double x, double EPS) {
double result = x;
double delta = x;
for (int n=1; fabs(delta)>EPS; n++) {
delta *= x/(2*n)*x/(2*n+1);
delta *= -1;
result+=delta;
}
return result;
}
double cosec(double x, double EPS) {
return 1.0f/sin(x, EPS);
}
@ManWithBear
Here's what happened:
double func(double X, double epsilon)
{
double r = 0, r1=0;
r+=pow(X,1)/fact(1);
r1=r + pow(-1,2.0)*pow(X,3)/fact(3);
for(double n=0;fabs(r-r1)>epsilon;n++)
{
r+=pow(-1,n)*pow(X,2*n+1)/fact(2*n+1);
r1=r + pow(-1,n+1)*pow(X,2*n+1+1)/fact(2*n+1+1);
}
return 1/r;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question