|
| 1 | + |
| 2 | + |
| 3 | +from math import exp |
| 4 | +from math import expm1 |
| 5 | +import numpy |
| 6 | +import matplotlib.pyplot as plt |
| 7 | + |
| 8 | + |
| 9 | + |
| 10 | +class Bernoulli: |
| 11 | + def __init__(self, maxorder): |
| 12 | + self.maxorder = maxorder |
| 13 | + self.denominators = [1.0,] * maxorder |
| 14 | + for i in range(1, maxorder): |
| 15 | + self.denominators[i] = (i+1) * self.denominators[i-1] |
| 16 | + self.factors = [1.0/x for x in self.denominators] |
| 17 | + |
| 18 | + def calcbernoulli(self, x): |
| 19 | + xv = 1.0 |
| 20 | + y = 0.0 |
| 21 | + for i, v in enumerate(self.factors): |
| 22 | + y += v * xv |
| 23 | + xv *= x |
| 24 | + return 1.0 / y |
| 25 | + |
| 26 | + |
| 27 | +def bexpm(x): |
| 28 | + y = expm1(x) |
| 29 | + if y != x: |
| 30 | + return x/y |
| 31 | + return 1.0 |
| 32 | + |
| 33 | + |
| 34 | + |
| 35 | +def create_bernoulli(i): |
| 36 | + fx = Bernoulli(i) |
| 37 | + return lambda x : fx.calcbernoulli(x) |
| 38 | + |
| 39 | +def b1(x): |
| 40 | + return x / (exp(x) - 1.0) |
| 41 | + |
| 42 | +b2 = create_bernoulli(15) |
| 43 | + |
| 44 | +b3 = bexpm |
| 45 | + |
| 46 | + |
| 47 | +x = numpy.linspace(0., 1.0, 10001) |
| 48 | + |
| 49 | + |
| 50 | +y = [] |
| 51 | +#plt.title("comparison of 3 different Bernouilli Function implementations") |
| 52 | +fig, ax = plt.subplots(2,1) |
| 53 | + |
| 54 | + |
| 55 | + |
| 56 | +funcs = [b2, b1] |
| 57 | +for i in range(2, 20): |
| 58 | + funcs.append(create_bernoulli(i)) |
| 59 | + |
| 60 | +for f in funcs: |
| 61 | + y.append(numpy.array(list(map(f, x)))) |
| 62 | + ax[0].plot(x, y[-1]) |
| 63 | +#ax[0].legend([r'$B1= \frac{x}{\exp(x)-1)}$', r'$B2=\frac{1}{1+0.5*x}$', r'$B3=\frac{x}{\text{expm1}(x)}$' "\n" r' $x \ne \text{expm1}(x), \text{else} 1$'], loc="lower left", |
| 64 | +#fancybox=True, framealpha=0.5) |
| 65 | +pdiffs=[] |
| 66 | +for i in range(1,len(y)): |
| 67 | + pdiffs.append(abs(y[i]-y[0])/y[0]) |
| 68 | + ax[1].semilogy(x,pdiffs[-1]) |
| 69 | +#ax[1].legend(['$|B3-B1|/B3$', '$|B3-B2|/B3$']) |
| 70 | +plt.show() |
| 71 | + |
0 commit comments