function

Why s=-1.#IND ?

#include <iostream>
#include <math.h>
using namespace std;

float fact(int k)
{if (k<0) return 0;
if (k==0) return 1;
return k*fact(k-1);
}


main()
{
float s,h,y,x,i;
h=(1-0.1)/40;
x=h; i=1; s=0;
do
{
s=s+pow(-1,i+1)*(pow(x,2*i+1)*(fact(2*i+1)));
y=sin(x);
cout<<"y"<<i<<"("<<"sin("<<x<<"))="<<y<<endl;
i++;
x+=h;

}
while (i<=40);
std::cout<<"s="<<s<<endl;
}

How can I solve that ?
I presume you meant
/ fact(2*i+1)
and not
* fact(2*i+1)
if you want a nominal sine series. However, this is a dire method and isn't going to produce anything meaningful in your case, as the different terms are being worked out at different values of x.


First of all, PLEASE USE CODE TAGS. Your code is basically unreadable.

It should be
int main()
A more proactive compiler would prevent your code from running.


The biggest problem of all is that you fall into the trap of so many in trying to sum a power series by working out each term from scratch according to the formula written down on paper.
For example,
pow(-1,i+1)
is ridiculous. Just multiply the previous term by -1.
Similarly, working out afresh pow(x,2*i+1) is silly. Just introduce another factor x * x to the previous term.
Worst of all is using a factorial function: (a) factorials grow excessively fast; and (b) you would end up repeating a whole shed-load of multiplies that you had already done on previous terms. Just divide the previous term by the appropriate new factors.

For the sine series, just
(a) start with i=0, term=x, sum=term.
(b) loop in i, multiplying the previous term by -x*x/(2*i)/(2*i+1.0). Add this to the running sum.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

double Sine( double x )
{
   const double tolerance = 1.0e-30;
   double term = x, sum = term;                   // first term
   double xsq = x * x;                            // convenience
   for ( int i = 1; abs( term ) > tolerance; i++ )
   {
      term *= -xsq / ( 2 * i ) / ( 2 * i + 1);    // next term as multiple of previous
      sum += term;                                // add to sum
   }
   return sum;
}


int main()
{
   const double PI = 4.0 * atan( 1.0 );
   cout << fixed << setprecision( 6 );
   for ( int deg = 0; deg <= 90; deg += 10 )
   {
       double rad = deg * PI / 180.0;
       cout << deg << '\t' << Sine( rad ) << '\t' << sin( rad ) << '\n';
   }
}

Last edited on
Registered users can post here. Sign in or register to post.