def zeta_minmax_n(a, xmin, xmax, n): z = 0.0 if xmax == np.inf or xmax == None: z = mpm.zeta(a, float(xmin), n) else: z = mpm.zeta(a, float(xmin), n) - mpm.zeta(a, float(xmax + 1), n) return float(z)
def zeta_minmax(gamma, kmin, kmax): '''kmax == None means kmax == infty ''' if gamma <= 1.0: if isinstance(kmax, (list, np.ndarray)): kmax_max = np.max(kmax) x = (1.0 * np.arange(kmin, kmax_max + 1, 1))**(-gamma) Fx = np.cumsum(x) C = [] # C0 = mpm.zeta(gamma,kmin) for k_ in kmax: # C += [ float(C0-mpm.zeta(gamma,float(k_)))] C += [Fx[int(k_ - kmin)]] C = np.array(C) elif kmax == None: print('ERROR: Series does not converge!!!') C = 0 else: mpm.dps = 25 # C = (float(mpm.sumem(lambda k: k**(-gamma),[kmin,kmax]))) C = float( mpm.zeta(gamma, float(kmin)) - mpm.zeta(gamma, float(kmax))) else: if isinstance(kmax, (list, np.ndarray)): C = zeta(gamma, kmin) - zeta(gamma, kmax) elif kmax == None: C = zeta(gamma, kmin) else: C = zeta(gamma, kmin) - zeta(gamma, kmax) return C
def FullNeg(self, ppos, x): beta = self.be / (1. * self.B) if x > 0 and x < 1.: return (1. - ppos) * (2.**-self.al) * (beta**self.al) * ( -mpmath.zeta(self.al, x + beta / 2.) + mpmath.zeta(self.al, (2 + beta) / 2.)) / ((-1. + x) * x) return 0.
def FullNeg_manual(ppos, x): beta = be / (1. * B) if x > 0 and x < 1.: return (1. - ppos) * (2.**-al) * (beta**al) * ( -mpmath.zeta(al, x + beta / 2.) + mpmath.zeta(al, (2 + beta) / 2.)) / ( (-1. + x) * x) return 0.
def get_polygamma(self, e, mu): psi_1 = zeta( 2, 0.5 + self.beta / 2 / np.pi * (self.Gamma + 1j * (e - mu))) psi_2 = zeta( 3, 0.5 + self.beta / 2 / np.pi * (self.Gamma + 1j * (e - mu))) * (-2) psi_3 = zeta( 4, 0.5 + self.beta / 2 / np.pi * (self.Gamma + 1j * (e - mu))) * 6 return psi_1, psi_2, psi_3
def FullNeg_numba(ppos, x): beta = be / (1. * B) if x > 0 and x < 1.: return (1. - ppos) * (2.**-al) * ( beta**al) * (-mpmath.zeta(al, np.array(x) + beta / 2.) + mpmath.zeta(al, (2 + beta) / 2.)) / ((-1. + x) * x) else: return 0.
def plconst(alpha, xmin): """ Computes the normalization constant on the discrete power law; i.e., computes C so that C * sum from xmin to infinity of x^(-alpha) = 1 The formula below is obtained by noting that the sum above is equal to sum from xmin to infinity of x^(-aplha) = HurwitzZeta(alpha, xmin) where HurwitzZeta is defined by zeta(s,a) = sum from 0 to infinity of 1 / (a+k)^s (as defined in sympy docs). If one is disinclined to note this fact by deriving it, one is encouraged to look at it in Mathematica and blindly trust the result. Note: The standard notation for the zeta function above uses "a" as a parameter. This does not correspond to the alpha we pass to the function. (Our alpha is s in the notation above). Inputs: alpha array, shape=(1,) exponent on x, must be > 1 must be passed as array for op.minimize() xmin int, starting point for sum, must be >= 1 Outputs: C float, normalization constant """ total = mp.zeta(np.asscalar(alpha), 1) # op.minimize passes array lowertail = np.sum(np.asarray(range(1, xmin)**(-alpha))) result = total - lowertail C = 1. / (result) return float(C)
def log_likelihood(params, data, nonzero_only=False): """ Calculates the log-likelihood on the data. :param params: two elements list containing the exponent (gamma) and shift (x0). :param data: input data as a numpy array. :param nonzero_only: whether nonzero element should be considered only. This is used after determining the parameters and comparing to distributions that ignore zero values. :return: log-likelihood. """ if params[0] < co.EPSILON: if params[1] < co.EPSILON: return co.delta.log_likelihood([0], data) else: return co.uniform.log_likelihood(None, data) else: c = float(zeta(params[0], params[1])) if c < co.EPSILON: return co.delta.log_likelihood([0], data) else: if nonzero_only: _samples = data[np.where(data > 0)] else: _samples = data return -params[0]*np.sum(np.log(_samples+params[1])) - len(_samples)*ln(c)
def cal_zeta(start, end, step): #print(f'start={start}, end={end}, step={step}') size = int((end - start) / step) value = [] for i in range(size): value.append(mpmath.zeta(1 / 2 + (start + float(i) * step) * 1j)) return value
def gf_powerlaw(exponent: float) -> GF: '''Return the generating function of the powerlaw degree distribution with the given exponent. :param exponent: the exponent of the distribution :returns: the generating function''' return gf_from_series(lambda x: polylog(exponent, x) / zeta(exponent))
def get_new_subs(self,num,alfac,befac,B): al = self.al be = self.be N = self.N z1 = mpmath.zeta(al,1+be/(2.*B)) z2 = mpmath.zeta(al,0.5*(2.-1./N +be/B)) denom = (z1-z2) z1n = mpmath.zeta(al*alfac,1+be*befac/(2.*B)) z2n = mpmath.zeta(al*alfac,0.5*(2.-1./N +be*befac/B)) numerator = (2.**(-al*alfac+al)) * (B**(-al*alfac+al)) * (be**-al)* ((be*befac)**(al*alfac)) * (z1n-z2n) return int(round(num*numerator/denom))
def taylor_series_at_1(N): coeffs = [] with mpmath.workdps(100): coeffs.append(-mpmath.euler) for n in range(2, N + 1): coeffs.append((-1)**n*mpmath.zeta(n)/n) return coeffs
def calc_zeta(re, img_name): fig = plt.figure() axes = Axes3D(fig) axes.w_xaxis.set_major_formatter(OldScalarFormatter()) axes.w_yaxis.set_major_formatter(OldScalarFormatter()) axes.w_zaxis.set_major_formatter(OldScalarFormatter()) axes.set_xlabel('X (real)') axes.set_ylabel('Y (imag)') axes.set_zlabel('Z (Zeta Img)') xa, ya, za = [], [], [] for i in np.arange(0.1, 200.0, 0.1): z = mpmath.zeta(complex(re, i)) xa.append(z.real) ya.append(z.imag) za.append(i) axes.plot(xa, ya, za, label='Zeta Function re(s)=%.3f' % re) axes.legend() plt.grid(True) axes.set_xlim3d(-10.0, 12.0) axes.set_ylim3d(-10.0, 12.0) axes.set_zlim3d(0.1, 200) plt.savefig(img_name) print("Plot %s !" % img_name) plt.close()
def taylor_series_at_1(N): coeffs = [] with mpmath.workdps(100): coeffs.append(-mpmath.euler) for n in range(2, N + 1): coeffs.append((-1)**n * mpmath.zeta(n) / n) return coeffs
def get_zeta(w): """ Input: v: triplet of zeta input, real ind, imag ind """ M = np.zeros((nval, nval)) + 1j * np.zeros((nval, nval)) M[w[2], w[1]] = zeta(w[0]) return M
def pre_calculated_needed_zet_values_to_list(num_of_zeros, rou_list): print 'pre_calculated_needed_zet_values_to_list, num_of_zeros: ', num_of_zeros, ', ...' zet_2_pk_list =[] zet_deri_pk_list = [] for k in range(1, num_of_zeros + 1): rou_k = rou_list[k - 1] zet_2_pk = mp.zeta(2*rou_k) zet_deri_pk = mp.zeta(rou_k, 1, 1) zet_2_pk_list.append(zet_2_pk) zet_deri_pk_list.append(zet_deri_pk) print 'pre_calculated_needed_zet_values_to_list, num_of_zeros: ', num_of_zeros, ', DONE !' return zet_2_pk_list, zet_deri_pk_list
def test_zeta(n=50, tol=1e-16): np.random.seed(0) mp.mp.dps = 64 for i in range(n): s = cplx_rand(-5, 5, -5, 5) a = cplx_rand(-5, 5, -5, 5) z = cf.zeta(s, a, tol=tol) z_mp = mp.zeta(s, a) assert (abs(z - complex(z_mp))) / abs(complex(z_mp)) < tol
def old_cal_zeta(start, end, step): size = int((end - start) / step) print(size) value = np.zeros(size) print(np.arange(start, end, step).reshape(1, -1)) for index, x in enumerate(list(np.arange(start, end, step))): print(f'{index}') x = float(x[0]) value[index] = mpmath.zeta(1 / 2 + x * 1j) return value
def formula(self, x: np.ndarray, gamma: float = None) -> np.ndarray: """ Predicted number of types sampled in proportion x of corpus, as a proportion of total types. NOTE: Eqn (8) in https://arxiv.org/pdf/1412.4577.pdf """ gamma = gamma or self.gamma Li = self._vpolylog(gamma, 1 - x) A = 1 / float(zeta(gamma).real) y = 1 - A * Li return y
def hyper1(As, Bs, N, M): with mpmath.extraprec(mpmath.mp.prec): s = t = 1 for j in range(1, N): t *= fprod(a + j - 1 for a in As) / fprod(b + j - 1 for b in Bs) s += t if M > 0: s2 = 0 g = sum(As) - sum(Bs) for (j, c) in enumerate(gammaprod_series(As, Bs, M)): s2 += c * mpmath.zeta(-(g - j), N) s += s2 * mpmath.gammaprod(Bs, As) return s
def lx_from_zet_zeros(num_of_zeros, x, rou_list): lx_main_part = 1 + np.sqrt(x)/mp.zeta(1./2) # print 'x = ', x, ', lx_main_part = ', lx_main_part tmp_sum = 0 for k in range(1, num_of_zeros + 1): rou_k = rou_list[k - 1] x_pk = np.power(x, rou_k) zet_2_pk = mp.zeta(2*rou_k) # 1st derivate zet_deri_pk = mp.zeta(rou_k, 1, 1) term = x_pk*zet_2_pk/(rou_k*zet_deri_pk) tmp_sum += term # print ' 2*np.real(tmp_sum) = ', 2*np.real(tmp_sum), ', real = ', 2*tmp_sum.real lx = lx_main_part + 2*tmp_sum.real return lx
def pmf(params, domain=co.DEFAULT_PDF_MAX): """ Probability mass function. :param params: two elements list containing the exponent (gamma) and shift (x0). :param domain: domain size. :return: probability mass function. """ if params[0] < co.EPSILON: if params[1] < co.EPSILON: return co.delta.pmf([0], domain) else: return co.uniform.pmf(None, domain) else: c = float(zeta(params[0], params[1])) if c < co.EPSILON: return co.delta.pmf([0], domain) else: return np.power(np.arange(0, domain+1)+params[1], -params[0])/c
def zeta_function(s, a=1, derivative=0): """ Returns the value for hurwitz-zeta function at s Parameters ---------- s : int, float, complex denotes the value for which zeta function needs to be calculated a : int, float, complex, tuple denotes constant a in hurwitz zeta function default value is 1 can be rational also like p/q, input must be a tuple (p,q) for this case, also p and q must be integers derivative : int denotes the n'th derivative default value is 0 return : float, complex returns tha value of zeta function or its derivative """ return mp.zeta(s, a, derivative)
def samples(params, size=co.DEFAULT_SAMPLE_SIZE, domain=co.DEFAULT_SAMPLE_MAX): """ Returns samples with discrete shifted power-law. :param params: two elements list containing the exponent (gamma) and shift (x0). :param size: number of samples. :param domain: domain size. :return: numpy array of samples. """ if params[0] < co.EPSILON: if params[1] < co.EPSILON: return co.delta.samples([0], size) else: return co.uniform.samples(None, size) else: if float(zeta(params[0], params[1])) < co.EPSILON: return co.delta.samples([0], size) else: x = np.arange(0, co.DEFAULT_SAMPLE_MAX+1) return co.generate_discrete_samples(x, np.power(x+params[1], -params[0]), size)
def skewness(xi, mu=0, sigma=1): """ Skewness of the generalized extreme value distribution. """ _validate_sigma(sigma) xi = mpmath.mpf(xi) mu = mpmath.mpf(mu) sigma = mpmath.mpf(sigma) if xi == 0: return 12 * mpmath.sqrt(6) * mpmath.zeta(3) / mpmath.pi**3 elif 3 * xi < 1: g1 = mpmath.gamma(mpmath.mp.one - xi) g2 = mpmath.gamma(mpmath.mp.one - 2 * xi) g3 = mpmath.gamma(mpmath.mp.one - 3 * xi) num = g3 - 3 * g2 * g1 + 2 * g1**3 den = mpmath.power(g2 - g1**2, 1.5) return mpmath.sign(xi) * num / den else: return mpmath.inf
def _eval_(self, s, x): r""" TESTS:: sage: hurwitz_zeta(x, 1) zeta(x) sage: hurwitz_zeta(4, 3) 1/90*pi^4 - 17/16 sage: hurwitz_zeta(-4, x) -1/5*x^5 + 1/2*x^4 - 1/3*x^3 + 1/30*x sage: hurwitz_zeta(3, 0.5) 8.41439832211716 """ if x == 1: return zeta(s) if s in ZZ and s > 1: return ((-1)**s) * psi(s - 1, x) / factorial(s - 1) elif s in ZZ and s < 0: return -bernoulli_polynomial(x, -s + 1) / (-s + 1) else: return
def hyper1_auto(As, Bs, N, M): with mpmath.extraprec(mpmath.mp.prec): s = t = 1 good_ratio_hits = 0 for j in range(1, N): s_old = s t *= fprod(a + j - 1 for a in As) / fprod(b + j - 1 for b in Bs) s += t ratio = (s - s_old) / s if ratio < mpf(10**-18): good_ratio_hits += 1 if good_ratio_hits > 3: break print float(s) if M > 0: s2 = 0 g = sum(As) - sum(Bs) for (j, c) in enumerate(gammaprod_series(As, Bs, M)): s2 += c * mpmath.zeta(-(g - j), N) s += s2 * mpmath.gammaprod(Bs, As) return s
def hyper1_auto(As, Bs, N, M): with mpmath.extraprec(mpmath.mp.prec): s = t = 1 good_ratio_hits = 0 for j in range(1, N): s_old = s t *= fprod(a + j - 1 for a in As) / fprod(b + j - 1 for b in Bs) s += t ratio = (s - s_old) / s if ratio < mpf(10 ** -18): good_ratio_hits += 1 if good_ratio_hits > 3: break print float(s) if M > 0: s2 = 0 g = sum(As) - sum(Bs) for (j, c) in enumerate(gammaprod_series(As, Bs, M)): s2 += c * mpmath.zeta(-(g - j), N) s += s2 * mpmath.gammaprod(Bs, As) return s
def _eval_(self, s, x): r""" TESTS:: sage: hurwitz_zeta(x, 1) zeta(x) sage: hurwitz_zeta(4, 3) 1/90*pi^4 - 17/16 sage: hurwitz_zeta(-4, x) -1/5*x^5 + 1/2*x^4 - 1/3*x^3 + 1/30*x sage: hurwitz_zeta(3, 0.5) 8.41439832211716 """ if x == 1: return zeta(s) if s in ZZ and s > 1: return ((-1) ** s) * psi(s - 1, x) / factorial(s - 1) elif s in ZZ and s < 0: return -bernoulli_polynomial(x, -s + 1) / (-s + 1) else: return
def _eval_(self, s, x): r""" TESTS:: sage: hurwitz_zeta(x, 1) zeta(x) sage: hurwitz_zeta(4, 3) 1/90*pi^4 - 17/16 sage: hurwitz_zeta(-4, x) -1/5*x^5 + 1/2*x^4 - 1/3*x^3 + 1/30*x sage: hurwitz_zeta(3, 0.5) 8.41439832211716 """ co = get_coercion_model().canonical_coercion(s, x)[0] if is_inexact(co) and not isinstance(co, Expression): return self._evalf_(s, x, parent=parent(co)) if x == 1: return zeta(s) if s in ZZ and s > 1: return ((-1) ** s) * psi(s - 1, x) / factorial(s - 1) elif s in ZZ and s < 0: return -bernoulli_polynomial(x, -s + 1) / (-s + 1) else: return
def calc_zeta(re, img_name): X, Y, Z = [], [], [] fig = plt.figure() ax = fig.add_subplot(111) for i in np.arange(0.1, 50.0, 0.1): compl = zeta(complex(re, i)) X.append(compl.real) Y.append(compl.imag) Z.append(i) ax.grid(True) ax.plot(Z, X, label='Im(v)', lw=0.8) ax.plot(Z, Y, label='Re(v)', lw=0.8) ax.set_title("Riemann Zeta function - re(s)=%.3f" % re) ax.set_xlabel("Im(s)") ax.set_ylabel("Re(v) and Im(v)") leg = ax.legend(shadow=True) for t in leg.get_texts(): t.set_fontsize('small') for l in leg.get_lines(): l.set_linewidth(2.0) # Plot the zeroes of zeta for i in range(1, 11): zero = zetazero(i) ax.plot(zero.imag, [0.0], "ro") # Comment this line for autoscale ax.set_ylim(12, -12) plt.savefig(img_name) print("Plot %s !" % img_name) plt.close()
def _eval_(self, s, x): r""" TESTS:: sage: hurwitz_zeta(x, 1) zeta(x) sage: hurwitz_zeta(4, 3) 1/90*pi^4 - 17/16 sage: hurwitz_zeta(-4, x) -1/5*x^5 + 1/2*x^4 - 1/3*x^3 + 1/30*x sage: hurwitz_zeta(3, 0.5) 8.41439832211716 """ co = get_coercion_model().canonical_coercion(s, x)[0] if is_inexact(co) and not isinstance(co, Expression): return self._evalf_(s, x, parent=parent(co)) if x == 1: return zeta(s) if s in ZZ and s > 1: return ((-1)**s) * psi(s - 1, x) / factorial(s - 1) elif s in ZZ and s < 0: return -bernoulli_polynomial(x, -s + 1) / (-s + 1) else: return
def test_zeta_greater_than_56(): # For s >= 56, `zeta` just returns 1. Since `zeta` monotonically # decreases to 1, if we are exactly correct to double precision at # 56, then we should be exactly correct for all larger numbers. assert sc.zeta(56) == np.float64(mpmath.zeta(56))
def test_avoid_overflow_for_large_negative_arguments(): # If we computed ((s + g + 0.5) / 2πe)**(s + 0.5) naively in the # implementation of `zeta`, then we would overflow here. Check # that we instead avoid overflow. s = -260.00000000001 assert_allclose(sc.zeta(s), float(mpmath.zeta(s)), atol=0, rtol=5e-14)
def f105(x): # zetam1 return mpmath.zeta(x) - 1
def f104(x): # zeta return mpmath.zeta(x)
def fixNegB(self, ppos): return 0.745 * (1 - ppos) * (2**(-self.al)) * (self.B**(-self.al)) * ( self.be**self.al ) * (-mpmath.zeta(self.al, 1. + self.be / (2. * self.B)) + mpmath.zeta(self.al, 0.5 * (2 - 1. / (self.N * self.B) + self.be / self.B)))
def GamSfsNeg(self, x): beta = self.be / (1. * self.B) return (2.**-self.al) * (beta**self.al) * ( -mpmath.zeta(self.al, x + beta / 2.) + mpmath.zeta(self.al, (2 + beta) / 2.)) / ((-1. + x) * x)
from matplotlib import pyplot as plt from mpmath import zeta, zetazero import numpy as np import pylab # critical-line.py zeichnet den Real- und Imaginärteil der # Zetafunktion über t nach Einsetzen der komplexen Zahlen # s = (0.5 + i t). Dies zeigt das Verhalten der Funktion # entlang der kritischen Geraden. t = np.arange(-26,26,0.01) real = [] imag = [] for k in t: real.append(zeta(complex(0.5, k)).real) imag.append(zeta(complex(0.5, k)).imag) fig_size = plt.rcParams["figure.figsize"] fig_size[0] = 13 fig_size[1] = 6 plt.rcParams["figure.figsize"] = fig_size plt.axhline(0, color='black', linewidth=1) plt.axvline(0, color='black', linewidth=1) for k in [1,2]: zero = zetazero(k).imag plt.axvline(zero, color='grey', alpha=1, linewidth=1, linestyle='dashed') plt.axvline(zero*(-1), color='grey', alpha=1, linewidth=1, linestyle='dashed')