Taylor series C++

Jan 24, 2014 at 12:20am
Hey guys,

First time posting in a forum, I just can't seem to get my code to work.

Everything compiles and runs, but I am getting an "inf" where my answer should be and I can't see why.

The assignment was:
Create a program to prompt the user for an input number in radians (say, x) and output an approximation of sin(x). Sin(x) can be approximated use a series expansion of the form: http://i.stack.imgur.com/eF4rm.png

Your program should take x and compute the result from the first 4 terms of the
sin(x) series expansion.

Here's everything I have written so far, and I can't seem to see why the computer is telling me "inf" for the answer.

#include <iostream>
#include <cmath>

using namespace std;

// Declaration (function prototype for fact)
int fact(int);

int main()
{
  const int NUM_IT = 4;
  int r, f;
  double Result;
  
  // Prompt the user
  cout << "Enter x in radians: ";
  cin >> r;

  
  for(int j=1;j<=NUM_IT;j+=2){
  fact(j) == f;
  Result += pow(r,j)/(f);
  }

  cout << "The approximation of sin(x) at " << r << " radians is " << Result << endl; 
  
  // You're done
  return 0;
  
}

 int fact(int n)
 {
   int i;
   int result=1;
   for(i=1; i <= n; i++){
     result = result * i;
   }
   return result;
 }


Thanks!
Jan 24, 2014 at 12:29am
1
2
3
4
for(int j=1;j<=NUM_IT;j+=2){
  fact(j) == f;
  Result += pow(r,j)/(f);
}

I think you mean to say f = fact(j); instead of fact(j) == f; (which does nothing, by the way).
Jan 24, 2014 at 12:34am
Thanks! However, this didn't solve my problem. :/
Jan 24, 2014 at 12:39am
You also forgot to initialize Result, and that the signs on the terms alternate between positive and negative.

EDIT: Also:
for(int j=1;j<=NUM_IT;j+=2){

Since you increment j by 2 each time instead of 1, you won't actually get NUM_IT iterations -- in this case, since NUM_IT is 4, you'll actually only get up to the second term.
Last edited on Jan 24, 2014 at 12:44am
Jan 24, 2014 at 1:04am
As ldm mentioned you are not even following the formula.

It should be Result += pow( -1 , j ) * pow( r , j ) / f;

Pretty much basic patterns to go from negative to positive by switching the power from odd to even.

This will give u result - + - +...

You have to also initialize Result to the value you are finding the sin for (r).
So that should be Result = r; after getting the value of r via cin.

[edit]
the ( -1 , j ) will vary depending if you are using a for loop starting at 0 or 1. I would recommend for( int i = 0; i < NUM_IT; ++i ) which would result in having it i + 1 instead of j pow( -1 , i + 1 ) But it may look neater to have it the way you did
1
2
for( int i = 1; i <= NUM_IT; ++i );
pow( -1 , i );

Last edited on Jan 24, 2014 at 1:07am
Topic archived. No new replies allowed.