McLaurin Series Expansion

Jul 7, 2020 at 7:20pm
I'm trying to write a code that will calculate cosine using the Mclaurin series expansion : 1 - x^2/2! + x^4/4! - x^6/6! + ... - x^n/n!

My biggest problem right now is getting the alternating addition and subtraction to work.

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
  #include <iostream>
#include <cstdlib>
#include <cmath>
#include <iomanip>
using namespace std;

// Define prototypes
int factorial(int);
int sum(double, int);

int main()
{
    // Initialize variables
    double x;
    int n;

    cout << "\nThis program calculates the value of cosine using the McLaurin Series Expansion.\n";
    cout << "Please enter a value for x that is in the range (-3.14, 3.14).\n";
    cout << "> ";
    cin >> x;
    cout << "Please enter the number of terms.\n";
    cout << "> ";
    cin >> n;

    factorial(n);

    cout << sum(x, n);

    return 0;
}

// Factorial function
int factorial(int n)
{
    cout << fixed << showpoint << setprecision(3);

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

// Sum function
int sum(double x, int n)
{

    cout << fixed << showpoint << setprecision(3);

    for (int i = 0; i == n; i++)
    {
        if (i % 2 == 0)
        {
            return 1 - pow(x, (2 * n)) / factorial(2 * n);
        }
        else if (i % 2 != 0)
        {
            return pow(x, (2 * n)) / factorial(2 * n);
        }
    }
}
Jul 7, 2020 at 8:01pm
You start with term = 1, sum = term

On the 1st loop you multiply term by -x*x/(1*2) and you add it to sum.

On the 2nd loop you multiply term by -x*x/(3*4) and you add it to sum.

On the 3rd loop you multiply term by -x*x/(5*6) and you add it to sum.

...

On the rth loop you multiply term by -x*x/((2r-1)*(2r) and you add it to sum.

Spot the pattern?



You should NEVER evaluate the sign term by using pow() here - it is pointless.
You should NEVER evaluate factorial as a function here: it is inefficient, pointless, and will probably blow up.
Jul 7, 2020 at 8:25pm
Your factorial and sum functions has some issues. You make similar mistakes in both of them
(1) You are always returning during the first iteration -- you have a return statement in all branches of each for loop iteration.
(2) Your ending condition for your for loopis i == n. You probably want "i < n" or similar.

Also, your sum function should be returning a double, since I assume you don't want whole numbers to be the only possible answers.
Last edited on Jul 7, 2020 at 8:26pm
Topic archived. No new replies allowed.