0

Im having trouble with the function taylor2 not returning a value if i input anything over 2. If I enter 0-2 it outputs the correct value but anything over 2 and I just get a flashing underscore with no data returned.

void taylor2(double x)
 {
     double total = 1;
     int i = 0;
     int count = 1;
     double temp = 1;

     do
     {

     {
         if (i % 2 == 1)
         {
             temp = (pow(x, i * 2 + 2) / factorial(i * 2 + 2));
             total += temp;
         }
         else {
             temp = (pow(x, i * 2 + 2) / factorial(i * 2 + 2));
             total -= temp;
         }
     }

     count++;
     i++;


     } while (fabs(temp) >= .0001);

     cout << "The last recoreded temporary value was: "<<temp << endl;
     cout << "The computed value for cosine is :  "<< total << endl;
     cout << "It took " <<count << " values to calculate the value of the function to .0001 places"<< endl;
     cout << endl; 
 }

1 Answers1

0

I suspect that factorial is returning an int. If int is 32 bit (very common), then factorial will overflow once the argument reaches 13 (i = 5 in your case). Signed integer overflow is undefined behaviour in C++.

You could use a std::uint64_t (an unsigned 64 bit integer). This will allow you to evaluate a few larger factorials.

For more reference, see Calculating large factorials in C++

Better still, use a recurrence relation between your Taylor terms.

Community
  • 1
  • 1
Bathsheba
  • 231,907
  • 34
  • 361
  • 483