Wednesday, February 6, 2013

C++ Examples - Functions Loops

Question: Write a function to calculate sin(x) using the first N terms of the power expansion
         N          2k+1
        ∑       k--x------
sin(x) ≈     (− 1) (2k + 1 )!
         k=0

The idea of this task is to create a simple function making use of loops and eventually a break command to approximate sin(x) with a power series. Yet again I can’t emphasise enough how important it is when writing a program that you should always be thinking about the structure and how you are going to stage your calculations. For this particular example, those stages might be:-

  1. Include all libraries
  2. Declare all variables and assign with default values
  3. Create a loop for summing up values
  4. Demonstrate ability to calculate each part of expression on each loop
  5. Check results against other solutions
  6. Move code into a function

Give the only libraries you should need are the input/output and mathematical functions your initial program should look like:

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
  return 0;
}

Compile and run and check your program outputs a blank terminal.

Now add in the variables in the problem, the most obvious variables required are the integers N and k required for counting in the loop, and we obviously need to store x but also need to keep track of the factorial, both of these last 2 variables are double because we are doing calculations with them. Note that even though factorial is always an integer we must use a double to make use of the larger maximum and minimum values that can be stored.

int main()
{
  // counting variables
  int N=10,k=0;
  // real variables
  double x=0.5,factorial=1.;
  
  return 0;
}

Note that we have chosen sensible starting values for the variables, compile, run and check your program outputs a blank terminal.

Next we add in the loop. Here we are going to start keeping track of the factorial term. By the definition of a factorial, we can find the value of the factorial at the current loop by multiplying the value from the last loop by k.

  // for k=1 up to k==n
  for(int k=1;k<=N;k++)
  {
    factorial = factorial * k;
    cout << k << "!=" << factorial << endl;
  }

This should output the values for k! between 1 and 10. By a similar argument we can get the value of the factorial (2k+1)! by multiplying the previous value by 2k and 2k+1. In the algorithm we may write

  // for k=1 up to k==n
  for(int k=1;k<=N;k++)
  {
    factorial = factorial * (2*k) * (2*k+1);
    cout << 2*k+1 << "!=" << factorial << endl;
  }

This should output the values for (2k+1)! between 3 and 21.

Next add in some code to get alternating plus and minus. The easiest way to do this is to have a variable that we multiply by minus at every step. You just need to be careful that it is minus on the odd loops and plus on the even ones. We might also print out the value of x to the power 2k+1 to check it gives a sensible value.

  double plusminus=1.;
  // for k=1 up to k==n
  for(int k=1;k<=N;k++)
  {
    factorial = factorial * (2*k) * (2*k+1);
    cout << 2*k+1 << "!=" << factorial << endl;
    plusminus=plusminus*-1.;
    cout << "+-=" << plusminus << endl;
    cout << "x^{2k+1}=" << pow(x,2*k+1) << endl;
  }

Compile and run the code and check that all the values give sensible results.

Now all that is left to do is to sum up all of those parts in the algorithm. To do this we use the dummy variable sum to keep track of the summation. Note that we must initialise the value of sum given k=0 since our loop only runs from k=1 up to N.

  // initialise values for k=0 separately
  double plusminus=1.,sum=x;
  // for k=1 up to k==n
  for(int k=1;k<=N;k++)
  {
    factorial = factorial * (2*k) * (2*k+1);
    plusminus=plusminus*-1.;    
    sum = sum + plusminus*pow(x,2*k+1)/factorial;
  }
  cout << " sin("<<x<<";"<<N<<")="<<sum<<endl;
  cout << " sin("<<x<<")="<<sin(x)<<endl;

At this stage you should test the accuracy of the solver using different values of x.

Now we are able to move this piece of code outside of the main function into it’s own function. Remember the value we want to return from the function is the sum variable. The definition of the function should look like

  double mySinFunction(double x,int N)
  {
    // paste algorithm in here
    return sum;
  }

Create this function above the main function and copy paste the code from the main function in. You should take out the declarations for x and N. Inside main you can now run the algorithm by simply calling the function as demonstrated here

  cout << mySinFunction(0.5,10) << endl;

The final program should look like:

#include <iostream>
#include <cmath>
using namespace std;

double mySinFunction(double x,int N)
{
  // counting variables
  int k=0;
  // real variables
  double factorial=1.;
  // initialise values for k=0 separately
  double plusminus=1.,sum=x;
  // for k=1 up to k==n
  for(int k=1;k<=N;k++)
  {
    factorial = factorial * (2*k) * (2*k+1);
    plusminus=plusminus*-1.;    
    sum = sum + plusminus*pow(x,2*k+1)/factorial;
  }
  return sum;
}

int main()
{
  int N=10;
  double x=0.5;
  cout << " sin("<<x<<";"<<N<<")=";
  cout << mySinFunction(x,N)<<endl;
  cout << " sin("<<x<<")="<<sin(x)<<endl;
  return 0;
}

No comments:

Post a Comment