def lourenco_eq_dist_mp(mgamma, m, sigma, Ne, Ne_scal, scal_fac=1): s = mgamma / 2. / Ne_scal * scal_fac #s = mgamma prob = mp.power(2, (1 - m) / 2.) * mp.power(Ne, 0.5) * mp.power( mp.fabs(s), (m - 1) / 2.) * (1 + 1 / (Ne * mp.power(sigma, 2.))) * mp.exp( -Ne * s) / (mp.power(mp.pi, 0.5) * mp.power(sigma, m) * mp.gamma(m / 2.)) * mp.besselk( (m - 1) / 2., Ne * mp.fabs(s) * mp.power(1 + 1 / (Ne * mp.power(sigma, 2.)), 0.5)) return float(prob / 2 / Ne_scal * scal_fac)
def check_zero(expression, verbose=False): # Setting precision precision = 30 # 30 sig digits mp.dps = precision free_symbols_dict = dict() # Setting each variable in free_symbols_set to a random number in [0, 1) according to the hashed string # representation of each variable. for var in expression.free_symbols: # Make sure M_PI is set to its correct value, pi if str(var) == "M_PI": free_symbols_dict[var] = mp.mpf(pi) # Then make sure M_SQRT1_2 is set to its correct value, 1/sqrt(2) elif str(var) == "M_SQRT1_2": free_symbols_dict[var] = mp.mpf(1.0/sqrt(2.0)) # All other free variables are set to random numbers else: # Take the variable [var], turn it into a string, encode the string, hash the string using the md5 # algorithm, turn the hash into a hex number, turn the hex number into an int, set the random seed to # that int. This ensures each variable gets a unique but consistent value. random.seed(int(hashlib.md5(str(var).encode()).hexdigest(), 16)) # Store the random value in free_symbols_dict as a mpf free_symbols_dict[var] = mp.mpf(random.random()) # Warning: might slow Travis CI too much: logging.debug(' ...Setting '+str(var)+' to the random value: '+str(free_symbols_dict[var])) # Using SymPy's cse algorithm to optimize our value substitution replaced, reduced = cse_postprocess(sp.cse(expression, order='none')) # Warning: might slow Travis CI too much: logging.debug(' var = '+str(var)+' |||| replaced = '+str(replaced)) # Calculate our result_value result_value = calculate_value(free_symbols_dict, replaced, reduced) # Check if result_value is near-zero, and double checking if it should be zero if mp.fabs(result_value) != mp.mpf('0.0') and mp.fabs(result_value) < 10 ** ((-2.0/3)*precision): if verbose: print("Found |result| (" + str(mp.fabs(result_value)) + ") close to zero. " "Checking if indeed it should be zero.") new_result_value = calculate_value(free_symbols_dict, replaced, reduced, precision_factor=2) if mp.fabs(new_result_value) < 10 ** (-(4.0/3) * precision): if verbose: print("After re-evaluating with twice the digits of precision, |result| dropped to " + str(new_result_value) + ". Setting value to zero") result_value = mp.mpf('0.0') # Store result_value in calculated_dict if result_value == mp.mpf('0.0'): return True return False
def takagi_fact(a): A = mp.matrix(a) sing_vs, Q = symmetric_svd(A) phase_mat = mp.diag( [mp.exp(-1j * mp.arg(sing_v) / 2.0) for sing_v in sing_vs]) vs = [mp.fabs(sing_v) for sing_v in sing_vs] Qp = Q * phase_mat return vs, Qp
def MPDBsc(M): Xk = M.copy() Yk = mp.eye(M.cols) dA = mp.det(M)**(mp.mpf('1.0')/2) for i in range(1,30): uk = mp.fabs(mp.det(Xk)/dA)**(-1.0/i) Xk1 = (uk*Xk + (uk**(-1))*(Yk**(-1)))/2 Yk1 = (uk*Yk + (uk**(-1))*(Xk**(-1)))/2 Xk = Xk1 Yk = Yk1 return Xk
def run(qtype, FW, R, alpha=0, beta=0): X, W = mp.gauss_quadrature(n, qtype, alpha=alpha, beta=beta) a = 0 for i in xrange(len(X)): a += W[i] * F(X[i]) b = mp.quad(lambda x: FW(x) * F(x), R) c = mp.fabs(a - b) if verbose: print(qtype, c, a, b) assert c < 1e-5
def run(qtype, FW, R, alpha = 0, beta = 0): X, W = mp.gauss_quadrature(n, qtype, alpha = alpha, beta = beta) a = 0 for i in xrange(len(X)): a += W[i] * F(X[i]) b = mp.quad(lambda x: FW(x) * F(x), R) c = mp.fabs(a - b) if verbose: print(qtype, c, a, b) assert c < 1e-5
def iterations_to_escape_ap(c, max_iterations=100): """ Calculate the number of iterations to escape the mandelbrot set. Uses arbitrary precision for calculations. Returns an (interpolated) mpmath floating point value. If no escape, returns a value greater than max_iterations. """ iterations = 0 z = mp.mpc(0) while mp.mag(z) < ESCAPE_MAGNITUDE: iterations += 1 if iterations > max_iterations: break z = z * z + c inner_log = mp.log(mp.fabs(z) / ESCAPE_MAGNITUDE) if inner_log.real > 0: adjustment = 1 - mp.log(inner_log, b=2) else: adjustment = 0 return float(iterations + adjustment)
def plot_RgMmn_g22_g33_g12_g23(n, k, Rmin, Rmax, klim=10, Taylor_tol=1e-4, Rnum=50): Rlist = np.linspace(Rmin, Rmax, Rnum) absg11list = np.zeros_like(Rlist) g22list = np.zeros_like(Rlist) g33list = np.zeros_like(Rlist) g12list = np.zeros_like(Rlist) g23list = np.zeros_like(Rlist) rholist = np.zeros_like(Rlist) for i in range(Rnum): print(i) R = Rlist[i] rholist[i] = mp_rho_M(n, k * R) Gmat = speedup_Green_Taylor_Arnoldi_RgMmn_oneshot( n, k, R, 3, klim, Taylor_tol) #vecnum=3 for the elements we need absg11list[i] = mp.fabs(Gmat[0, 0]) g22list[i] = mp.re(Gmat[1, 1]) #note the indexing off-by-one g33list[i] = mp.re(Gmat[2, 2]) g12list[i] = mp.re(Gmat[0, 1]) g23list[i] = mp.re(Gmat[1, 2]) normalRlist = Rlist * k / (2 * np.pi) #R/lambda list plt.figure() plt.plot(normalRlist, g22list, '-r', label='$G_{22}$') plt.plot(normalRlist, g12list, '--r', label='$G_{12}$') plt.plot(normalRlist, g33list, '-b', label='$G_{33}$') plt.plot(normalRlist, g23list, '--b', label='$G_{23}$') plt.plot(normalRlist, absg11list, '-k', label='$|G_{11}|$') plt.plot(normalRlist, rholist, '--k', label='$\\rho_M$') plt.xlabel('$R/\lambda$', **axisfont) plt.title( 'Green Function matrix elements \n for Arnoldi family radial number n=' + str(n), **axisfont) plt.legend() plt.show()
def _eigenvals_eigenvects_mpmath(M): norm2 = lambda v: mp.sqrt(sum(i**2 for i in v)) v1 = None prec = max([x._prec for x in M.atoms(Float)]) eps = 2**-prec while prec < DEFAULT_MAXPREC: with workprec(prec): A = mp.matrix(M.evalf(n=prec_to_dps(prec))) E, ER = mp.eig(A) v2 = norm2([i for e in E for i in (mp.re(e), mp.im(e))]) if v1 is not None and mp.fabs(v1 - v2) < eps: return E, ER v1 = v2 prec *= 2 # we get here because the next step would have taken us # past MAXPREC or because we never took a step; in case # of the latter, we refuse to send back a solution since # it would not have been verified; we also resist taking # a small step to arrive exactly at MAXPREC since then # the two calculations might be artificially close. raise PrecisionExhausted
Zc = mp.matrix(f.size, 1) A = np.ndarray(f.size) R = np.ndarray(f.size) I = np.ndarray(f.size) Gr = np.ndarray(f.size) Gi = np.ndarray(f.size) for n in range(f.size): Zap[n] = ZapA[n]*( i0(gammac[n]*a) / i1(gammac[n]*a) ) Zbp[n] = ZbpA[n] * ((i0(gammac[n]*b) * k1(gammac[n]*c) + k0(gammac[n]*b)*i1(gammac[n]*c)) / ( i1(gammac[n]*c)*k1(gammac[n]*b) - i1(gammac[n]*b)*k1(gammac[n]*c) ) ) ZL[n] = 1j*omega[n]*Lp YC[n] = 1j*omega[n]*Cp Zp[n] = Zap[n] + Zbp[n] + ZL[n] Yp[n] = YC[n] # + G[n] Zc[n] = mp.sqrt(Zp[n]/Yp[n]) A[n] = mp.fabs(Zc[n]) R[n] = mp.re(Zc[n]) I[n] = mp.im(Zc[n]) Gr[n] = mp.re(mp.sqrt(Zp[n]*Yp[n])) Gi[n] = mp.im(mp.sqrt(Zp[n]*Yp[n])) fig = plt.figure() plt.plot(f/10**6, A, label='Magnitude', color='red') plt.xlabel('Frequency [MHz]') plt.ylabel('Magnitude of Z$_{c}$ [$\Omega$]') plt.legend() plt.xlim([-0.3,100]) #plt.show() fig2 = plt.figure() plt.plot(f/10**6, R, label='Real Part', color='red') plt.xlabel('Frequency [MHz]')
def Abs(a): return mp.fabs(a)
def run_posit_2op_exhaustive(self, op_str=None, nbits_range=None, es_range=None): op = None mpop = None if op_str == '+': op = PCPosit.__add__ mpop = mp.mpf.__add__ elif op_str == '-': op = PCPosit.__sub__ mpop = mp.mpf.__sub__ elif op_str == '*': op = PCPosit.__mul__ mpop = mp.mpf.__mul__ elif op_str == '/': op = PCPosit.__truediv__ mpop = mp.mpf.__truediv__ else: raise NotImplementedError("op={}".format(op_str)) if nbits_range is None: nbits_range = self.nbits_range if es_range is None: es_range = self.es_range for nbits in nbits_range: mask = bitops.create_mask(nbits) cinf_bits = 1 << (nbits - 1) is_special = lambda bits: bits == 0 or bits == cinf_bits is_normal = lambda bits: not is_special(bits) for es in es_range: for abits in range(2**nbits): for bbits in range(2**nbits): a = PCPosit(abits, nbits=nbits, es=es, mode='bits') b = PCPosit(bbits, nbits=nbits, es=es, mode='bits') c = op(a, b) cbits = coder.encode_posit_binary(c.rep) test_info = { 'nbits': nbits, 'es': es, 'a': str(a), 'b': str(b), 'c': str(c), 'abits': abits, 'bbits': bbits, 'cbits': cbits, 'arep': a.rep, 'brep': b.rep, 'crep': c.rep, } if is_normal(abits) and is_normal( bbits) and cbits == 0: self.assertTrue(op_str in ['+', '-']) if op_str == '+': self.assertEqual(abits, -bbits & mask) else: # '-' self.assertEqual(abits, bbits) elif is_normal(abits) and is_normal(bbits): self.assertNotEqual(cbits, 0) self.assertNotEqual(cbits, cinf_bits) amp = mp.mpf( eval(coder.positrep_to_rational_str(a.rep))) bmp = mp.mpf( eval(coder.positrep_to_rational_str(b.rep))) c2mp = mpop(amp, bmp) c0bits = (cbits - 1) & mask while c0bits == 0 or c0bits == cinf_bits: c0bits = (c0bits - 1) & mask c1bits = (cbits + 1) & mask while c1bits == 0 or c1bits == cinf_bits: c1bits = (c1bits + 1) & mask c0 = PCPosit(c0bits, nbits=nbits, es=es, mode='bits') c1 = PCPosit(c1bits, nbits=nbits, es=es, mode='bits') test_info['c0'] = str(c0) test_info['c1'] = str(c1) test_info['c0bits'] = c0bits test_info['c1bits'] = c1bits test_info['c0rep'] = c0.rep test_info['c1rep'] = c1.rep rcmp = mp.mpf( eval(coder.positrep_to_rational_str(c.rep))) cratiodiffmp = mp.fabs(mp.log( rcmp / c2mp)) if c2mp != 0 else mp.fabs(rcmp - c2mp) cabsdiffmp = mp.fabs(rcmp - c2mp) c0mp = mp.mpf( eval(coder.positrep_to_rational_str(c0.rep))) c0ratiodiffmp = mp.fabs(mp.log( c0mp / c2mp)) if c2mp != 0 else mp.fabs(c0mp - c2mp) c0absdiffmp = mp.fabs(c0mp - c2mp) self.assertTrue( cratiodiffmp <= c0ratiodiffmp or cabsdiffmp <= c0absdiffmp, test_info) c1mp = mp.mpf( eval(coder.positrep_to_rational_str(c1.rep))) c1ratiodiffmp = mp.fabs(mp.log( c1mp / c2mp)) if c2mp != 0 else mp.fabs(c1mp - c2mp) c1absdiffmp = mp.fabs(c1mp - c2mp) self.assertTrue( cratiodiffmp <= c1ratiodiffmp or cabsdiffmp <= c1absdiffmp, test_info) elif abits == cinf_bits: self.assertTrue(op_str in ['+', '-', '*', '/']) self.assertEqual(cbits, cinf_bits) elif abits != cinf_bits and bbits == cinf_bits: self.assertTrue(op_str in ['+', '-', '*', '/']) if op_str == '/': self.assertEqual(cbits, 0) else: self.assertEqual(cbits, cinf_bits) elif abits == 0 and bbits == 0: self.assertTrue(op_str in ['+', '-', '*', '/']) if op_str == '/': self.assertEqual(cbits, cinf_bits) else: self.assertEqual(cbits, 0) elif is_normal(abits) and bbits == 0: if op_str == '+' or op_str == '-': self.assertEqual(cbits, abits) elif op_str == '*': self.assertEqual(cbits, 0) elif op_str == '/': self.assertEqual(cbits, cinf_bits) else: self.assertTrue(False) elif abits == 0 and is_normal(bbits): self.assertTrue(op_str in ['+', '-', '*', '/']) if op_str == '+': self.assertEqual(cbits, bbits) elif op_str == '-': self.assertEqual(cbits, -bbits & mask) else: self.assertEqual(cbits, 0) else: self.assertTrue(False)
def S_Kummer(beta0, kc, L, order, qmax): """Compute even and odd coefficents at an order number""" K = 2 * pi / L beta_n = lambda n: beta0 + n * K gamma_n = lambda n: -1j * np.sqrt(kc ** 2 - beta_n(n) ** 2 + 0j) theta_n = lambda n: np.arcsin(beta_n(n) / kc - 1j * np.sign(n) * np.spacing(1)) if order == 0: qs = np.hstack([np.arange(-qmax, 0), np.arange(1, qmax + 1)]) S0sum = 1 / gamma_n(qs) - 1 / (K * np.abs(qs)) \ - (kc ** 2 + 2 * beta0 ** 2) / (2 * K ** 3 * np.abs(qs) ** 3) S0sum = np.sum(S0sum) S0 = -1 - (2j / pi) * (np.euler_gamma + np.log(kc / (2 * K))) \ - 2j / (gamma_n(0) * L) \ - 2j * (kc ** 2 + 2 * beta0 ** 2) * zeta(3) / (K ** 3 * L) \ - (2j / L) * S0sum return S0 qs = np.arange(1, qmax + 1) oeven = 2 * order oodd = 2 * order - 1 # Even sum with wavenumber terms, large terms excluded SEsum0 = np.exp(-1j * oeven * theta_n(qs)) / gamma_n(qs) \ + np.exp(1j * oeven * theta_n(-qs)) / gamma_n(-qs) SEsum0 = SEsum0.sum() SEsum0 += np.exp(-1j * oeven * theta_n(0)) / gamma_n(0) SEsum0 *= -2j / L # Odd sum with wavenumber terms, large terms excluded SOsum0 = np.exp(-1j * oodd * theta_n(qs)) / gamma_n(qs) \ - np.exp(1j * oodd * theta_n(-qs)) / gamma_n(-qs) SOsum0 = SOsum0.sum() SOsum0 += np.exp(-1j * oodd * theta_n(0)) / gamma_n(0) SOsum0 *= 2j / L # Even sum with factorial terms ms = np.arange(1., order + 1) b = np.array([float(mp.bernpoly(2 * m, beta0 / K)) for m in ms]) SEsumF = (-1) ** ms * 2 ** (2 * ms) * factorial(order + ms - 1) \ * (K / kc) ** (2 * ms) * b \ / (factorial(2 * ms) * factorial(order - ms)) SEsumF = np.sum(SEsumF) SEsumF *= 1j / pi # Odd sum with factorial terms ms = np.arange(0, order) b = np.array([float(mp.bernpoly(2 * m + 1, beta0 / K)) for m in ms]) SOsumF = (-1) ** ms * 2 ** (2 * ms) * factorial(order + ms - 1) \ * (K / kc) ** (2 * ms + 1) * b \ / (factorial(2 * ms + 1) * factorial(order - ms - 1)) SOsumF = np.sum(SOsumF) SOsumF *= -2 / pi # extended precision calculations for large sum terms t1 = (1 / pi) * (kc / (2 * K)) ** oeven t2 = (beta0 * L * order / pi ** 2) * (kc / (2 * K)) ** oodd # assume we need ~15 digits of precision at a magnitude of 1 dps = np.max([int(np.ceil(np.log10(np.abs(t1)))) + 15, int(np.ceil(np.log10(np.abs(t2)))) + 15, 15]) mp.dps = dps arg_ = mp.mpf(kc / (2 * K)) SEinf = -(-1) ** order * arg_ ** (2 * order) \ * mp.zeta(2 * order + 1) / mp.pi SOinf = (-1) ** order * beta0 * L * order * arg_ ** (2 * order - 1) \ * mp.zeta(2 * order + 1) / mp.pi ** 2 for i, m in enumerate(mp.arange(1, qmax + 1)): even_term = ((-1) ** order / (m * mp.pi)) * (arg_ / m) ** (2 * order) odd_term = ((-1) ** order * beta0 * L * order / (m ** 2 * mp.pi ** 2)) \ * (arg_ / m) ** (2 * order - 1) SEinf += even_term SOinf -= odd_term # break condition, where we should be OK moving back to double precision if mp.fabs(even_term) < 1 and mp.fabs(odd_term) < 1: break mp.dps = 15 SEinf = complex(SEinf) SOinf = complex(SOinf) if i + 1 < qmax: ms = np.arange(i + 2, qmax) even_terms = ((-1) ** order / (ms * pi)) \ * (kc / (2 * K * ms)) ** (2 * order) odd_terms = ((-1) ** order * beta0 * L * order / (ms ** 2 * pi ** 2)) \ * (kc / (2 * K * ms)) ** (2 * order - 1) SEinf += even_terms.sum() SEinf *= 2j SOinf -= odd_terms.sum() SOinf *= 2 SEven = SEsum0 + SEinf + 1j / (pi * order) + SEsumF SOdd = SOsum0 + SOinf + SOsumF return SOdd, SEven
# Set the dps option mp.dps = 256 # Convert stuff to mpmath inc = mp.mpf(args.spacing) eps = mp.power(10, -args.eps) cutoffs = [None] * (args.max_n+1) cutoff_diffs = [None] * (args.max_n+1) x = mp.mpf(0) maxdiff = eps * 2.0 # force loop to run while maxdiff > eps: x = x + inc F_real = BoysValue(args.max_n, x) F_long = BoysValue_Asymptotic(args.max_n, x) diff = [ mp.fabs(F_real[i] - F_long[i]) for i in range(0, len(F_real)) ] maxdiff = max(diff) for idx,val in enumerate(diff): if not cutoffs[idx] and diff[idx] < eps: cutoffs[idx] = x cutoff_diffs[idx] = val for idx,val in enumerate(cutoffs): print("{:4} {}".format(idx, mp.nstr(val)))
def run_posit_2op_exhaustive(self, op_str=None, nbits_range=None, es_range=None): op = None mpop = None if op_str == '+': op = PCPosit.__add__ mpop = mp.mpf.__add__ elif op_str == '-': op = PCPosit.__sub__ mpop = mp.mpf.__sub__ elif op_str == '*': op = PCPosit.__mul__ mpop = mp.mpf.__mul__ elif op_str == '/': op = PCPosit.__truediv__ mpop = mp.mpf.__truediv__ else: raise NotImplementedError("op={}".format(op_str)) for nbits in nbits_range: mask = bitops.create_mask(nbits) for es in es_range: for abits in range(2**nbits): for bbits in range(2**nbits): a = PCPosit(abits, nbits=nbits, es=es, mode='bits') b = PCPosit(bbits, nbits=nbits, es=es, mode='bits') c = op(a, b) if a.rep['t'] == 'n' and b.rep['t'] == 'n': amp = mp.mpf( eval(coder.positrep_to_rational_str(a.rep))) bmp = mp.mpf( eval(coder.positrep_to_rational_str(b.rep))) c2mp = mpop(amp, bmp) c0 = PCPosit((bbits - 1) & mask, nbits=nbits, es=es, mode='bits') c1 = PCPosit((bbits + 1) & mask, nbits=nbits, es=es, mode='bits') cbits = coder.encode_posit_binary(c.rep) roundedc = coder.decode_posit_binary(cbits, nbits=nbits, es=es) rcmp = mp.mpf( eval(coder.positrep_to_rational_str(roundedc))) cratiodiffmp = mp.fabs(mp.log( rcmp / c2mp)) if c2mp != 0 else mp.fabs(rcmp - c2mp) cabsdiffmp = mp.fabs(rcmp - c2mp) if c0.rep['t'] != 'c': c0mp = mp.mpf( eval(coder.positrep_to_rational_str( c0.rep))) c0ratiodiffmp = mp.fabs(mp.log( c0mp / c2mp)) if c2mp != 0 else mp.fabs(c0mp - c2mp) c0absdiffmp = mp.fabs(c0mp - c2mp) self.assertTrue(cratiodiffmp <= c0ratiodiffmp or cabsdiffmp <= c0absdiffmp) if c1.rep['t'] != 'c': c1mp = mp.mpf( eval(coder.positrep_to_rational_str( c1.rep))) c1ratiodiffmp = mp.fabs(mp.log( c1mp / c2mp)) if c2mp != 0 else mp.fabs(c1mp - c2mp) c1absdiffmp = mp.fabs(c1mp - c2mp) self.assertTrue(cratiodiffmp <= c1ratiodiffmp or cabsdiffmp <= c1absdiffmp)