P
P
parkito2014-05-21 00:04:04
Programming
parkito, 2014-05-21 00:04:04

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;
 
        
 }

But the values ​​obtained are far from ideal.
8938264423f84fe3bd6f3dfd68de61a3.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
ManWithBear, 2014-05-21
@parkito

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);

UPD3. Regarding optimization, I meant something like this:
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);
}

P
parkito, 2014-05-22
@parkito

@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 question

Ask a Question

731 491 924 answers to any question