Search code examples
c++c++11mathtaylor-series

representing negative outputs dynamically in Taylor series expansion --> C++


I am learning to code, so please forgive me for asking such a rudimentary question (gotta start somewhere, right?) I have written the following C++ program which approximates an e^x series expansion (Taylor series).

The problem I have is with the output. One of the sample outputs I need to have is as follows:

Sample Run 5:

This program approximates e^x using an n-term series expansion. Enter the number of terms to be used in the approximation of e^x-> 8 Enter the exponent(x)-> -0.25

e^-0.25000 = 1.00000 - 0.25000 + 0.03125 - 0.00260 + 0.00016 - 0.00001 + 0.00000 - 0.00000 = 0.77880

But my code creates the following output instead:

e^-0.25000 = 1.00000 + -0.25000 + 0.03125 + -0.00260 + 0.00016 + -0.00001 + 0.00000 + -0.00000 = 0.77880

Essentially, I am unsure how to represent these negative values dynamically, in order to match the desired output. At present, they are all represented by " + " string literals in my code, in between the recursive term that repeats.

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int numTerms, i;
long double x, numer, denom, prevDenom, term, sum;

int main ()
{
    cout << "This program approximates e^x using an n-term series expansion." << endl;
    cout << "Enter the number of terms to be used in the approximation of e^x-> ";
    cin >> numTerms;
    cout << "Enter the exponent(x)-> ";
    cin >> x;
    cout << endl;

        if (numTerms <= 0)
            cout << numer << " is an invalid number of terms." << endl;
        else if (numTerms == 1)
        {
            sum = 1.00000;
            cout << "e^" << fixed << setprecision(5) << x << " = " << sum << " = " << sum << endl;
        }
        else
        {
            cout << "e^" << fixed << setprecision(5) << x <<" = " << 1.00000;
            sum += 1.00000;
            prevDenom = 1;
            for (i = 1; i < numTerms; i++)
            {
                numer = pow(x,(i));
                denom = (prevDenom) * (i);

                term = numer / denom;

                sum += term;
                prevDenom = denom;
                cout << " + " << term;
            }
            cout << " = " << fixed << setprecision(5) << sum << endl;
        }
}

Thanks in advance!


Solution

  • You could replace:

    cout << " + " << term;
    

    with:

    if (term >= 0)
        cout << " + " << term;
    else
        cout << " - " << (-term);
    

    So when a term is negative you print the minus sign yourself with the extra space you need and then you print the positive part of your term.