Series calculation precision

198 Views Asked by At

I need to find the sum of the first N elements of the series to satisfy some precision e (10^-3, for example):

y = -(2x + (2x)^2/2 + (2x)^3/3 + ...)

The exact sum of y is log(1 - 2*x).

I wrote a program in python, but the difference W between sum and log turns out to be non-zero in case of set precision (the last significant digit is 1 or 2 in some samples).

from math import log

def y_func(x, e):
   y = 0
   nom = 2*x
   den = 1
   a = nom / den
   while abs(a) > e:
      y -= a
      den += 1
      nom *= 2*x
      a = nom / den
   return y

def main(p):
    print(('{:{width}}'*4).format('X','Y','Z','W',width = 14))
    prec = 10**-p
    x = -.25
    xk = .35
    h = .05
    while x <= xk:
       Y = y_func(x, prec)
       Z = log(1-2*x)
       W = Y - Z
       print(('{:<{width}.{prec}f}'*4).format(x, Y, Z, W, \
                                      prec = p, width = 14))
       x += h


if __name__ == "__main__":
    main(3)
2

There are 2 best solutions below

1
On BEST ANSWER

Well said @NPE, unfortunately this still doesn't fix the problem.

I wanted to call your attention to the fact that such series does not converge fast enough to allow you to say that if abs(a) < e then y's precision is e.

That means that even if you make your loop do that one more iteration you'll still have less (much less!) than e precision when x approaches .50.

To fix this once for all you should change your while to something like:

while abs(y - log(1-2*x)) >= e: # > or >= depending on what you need
    # y = ...
1
On

You're stopping one iteration too early: you stop as soon as nom / den goes below the threshold, but before you've subtracted it from y.

In other words, you need to restructure your while loop.