Function to Solve ln(x) using a Taylor Series

Dec 11, 2011 at 8:24am
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.

My code is as follows:
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
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

int main()
{
   /***********Variable Declarations************/
   long double count = 0;     //Keeps track of the count in the loop
   long double totalValue = 0; //The summation of each polynomial evaluated
   bool reciprocal = false;   //Flag to use if greater than 2
   long double precision;     //The the highest order of polynomial to use.
   long double 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;
}

This returns (user input in bold):

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.
Dec 11, 2011 at 8:44am
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.
Dec 11, 2011 at 10:27am
Thanks very much... Changing count to start at 1 rather than 0 seems to have fixed it.
Dec 12, 2011 at 5:05am
Great work
Dec 13, 2011 at 1:51am
Should line 39 be *=?

Jim
Dec 13, 2011 at 4:01pm
Good catch on that one Jim. I actually fixed it in my source code, but I haven't posted an updated version on here.
Topic archived. No new replies allowed.