I am trying to write a program to use with a research paper about the Taylor series. Basically, I have written this huge paper about the Taylor series and now I would like to demonstrate it's usage through a C++ program. I have managed to figure out to algorithm to calculate the function including error checking, however I keep getting a -inf output rather than the number.
#include <iostream>
#include <cmath>
#include <iomanip>
usingnamespace std;
int main()
{
/***********Variable Declarations************/
longdouble count = 0; //Keeps track of the count in the loop
longdouble totalValue = 0; //The summation of each polynomial evaluated
bool reciprocal = false; //Flag to use if greater than 2
longdouble precision; //The the highest order of polynomial to use.
longdouble x; //Value to evaluate to ln for.
/************End Declarations****************/
/***************Get User Input***************/
cout << "Precision=";
cin >> precision;
cout << "x=";
cin >> x;
/***************End User Input***************/
//Get actual value using log(x) found in <cmath>
cout << "The log(x) C++ function value is:" << log(x) << endl;
if (x > 2.0) //Use the rule -ln(1/x) == ln(x) to keep accuracy
{
x = 1 / x; //Change to using 1/x rather than x
reciprocal = true; //Flag as true (sign change is later)
}
while (count < precision)
{
totalValue += pow(-1, count + 1) * (pow((x-1),count)/count);
count++;
}
if (reciprocal == true)
totalValue * -1; //If reciprocal was used multiply by -1 to change sign
cout << "The Result is:" << setprecision(5) << totalValue << endl;
return 1;
}
Precision=10
x=3
The log(x) C++ function value is:1.09861
The Result is:-inf
I would really like any ideas on how this could be fixed to display it working. The setprecision didn't help at all. Somehow the log(x) function works and I would be happy just to look at the actual implementation file of that, but I have been unable to locate it.
You seem to be expanding around the point 0. However log is not defined at zero. This causes (pow((x-1),count)/count) to be -inf when count=0. Your problem isn't programming, it's maths. Expand around a different point to fix the problem.