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)
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) < etheny's precision ise.That means that even if you make your loop do that one more iteration you'll still have less (much less!) than
eprecision whenxapproaches.50.To fix this once for all you should change your
whileto something like: