def test_airyai(self): # oscillating function, limit range assert_mpmath_equal(lambda z: sc.airy(z)[0], mpmath.airyai, [Arg(-1e8, 1e8)], rtol=1e-6) assert_mpmath_equal(lambda z: sc.airy(z)[0], mpmath.airyai, [Arg(-1e3, 1e3)])
def test_airybi_prime(self): # oscillating function, limit range assert_mpmath_equal(lambda z: sc.airy(z)[3], lambda z: mpmath.airybi(z, derivative=1), [Arg(-1e8, 1e8)], rtol=1e-6) assert_mpmath_equal(lambda z: sc.airy(z)[3], lambda z: mpmath.airybi(z, derivative=1), [Arg(-1e3, 1e3)])
def _evalf_(self, x, **kwargs): """ EXAMPLES:: sage: from sage.functions.airy import airy_ai_simple sage: airy_ai_simple(0.0) 0.355028053887817 sage: airy_ai_simple(1.0 * I) 0.331493305432141 - 0.317449858968444*I We can use several methods for numerical evaluation:: sage: airy_ai_simple(3).n(algorithm='mpmath') 0.00659113935746072 sage: airy_ai_simple(3).n(algorithm='mpmath', prec=100) 0.0065911393574607191442574484080 sage: airy_ai_simple(3).n(algorithm='scipy') # rel tol 1e-10 0.006591139357460719 sage: airy_ai_simple(I).n(algorithm='scipy') # rel tol 1e-10 0.33149330543214117 - 0.3174498589684438*I TESTS:: sage: parent(airy_ai_simple(3).n(algorithm='scipy')) Real Field with 53 bits of precision sage: airy_ai_simple(3).n(algorithm='scipy', prec=200) Traceback (most recent call last): ... NotImplementedError: airy_ai not implemented for precision > 53 """ algorithm = kwargs.get('algorithm', 'mpmath') or 'mpmath' parent = kwargs.get('parent') if algorithm == 'scipy': if hasattr(parent, 'prec') and parent.prec() > 53: raise NotImplementedError("%s not implemented for precision > 53"%self.name()) from sage.rings.all import RR, CC from sage.functions.other import real,imag from scipy.special import airy as airy if x in RR: y = airy(real(x))[0] if parent is None: return RR(y) else: y = airy(complex(real(x),imag(x)))[0] if parent is None: return CC(y) return parent(y) elif algorithm == 'mpmath': import mpmath from sage.libs.mpmath import utils as mpmath_utils return mpmath_utils.call(mpmath.airyai, x, parent=parent) else: raise ValueError("unknown algorithm '%s'" % algorithm)
def _evalf_(self, x, **kwargs): """ EXAMPLES:: sage: from sage.functions.airy import airy_bi_simple sage: airy_bi_simple(0.0) 0.614926627446001 sage: airy_bi_simple(1.0 * I) 0.648858208330395 + 0.344958634768048*I We can use several methods for numerical evaluation:: sage: airy_bi_simple(3).n(algorithm='mpmath') 14.0373289637302 sage: airy_bi_simple(3).n(algorithm='mpmath', prec=100) 14.037328963730232031740267314 sage: airy_bi_simple(3).n(algorithm='scipy') # rel tol 1e-10 14.037328963730136 sage: airy_bi_simple(I).n(algorithm='scipy') # rel tol 1e-10 0.648858208330395 + 0.34495863476804844*I TESTS:: sage: parent(airy_bi_simple(3).n(algorithm='scipy')) Real Field with 53 bits of precision sage: airy_bi_simple(3).n(algorithm='scipy', prec=200) Traceback (most recent call last): ... NotImplementedError: airy_bi not implemented for precision > 53 """ algorithm = kwargs.get('algorithm', 'mpmath') or 'mpmath' parent = kwargs.get('parent', None) if algorithm == 'scipy': if hasattr(parent, 'prec') and parent.prec() > 53: raise NotImplementedError("%s not implemented for precision > 53"%self.name()) from sage.rings.all import RR, CC from sage.functions.other import real,imag from scipy.special import airy as airy if x in RR: y = airy(real(x))[2] if parent is None: return RR(y) else: y = airy(complex(real(x),imag(x)))[2] if parent is None: return CC(y) return parent(y) elif algorithm == 'mpmath': import mpmath from sage.libs.mpmath import utils as mpmath_utils return mpmath_utils.call(mpmath.airybi, x, parent=parent) else: raise ValueError("unknown algorithm '%s'" % algorithm)
def _evalf_(self, x, **kwargs): """ EXAMPLES:: sage: airy_ai_prime(0.0) -0.258819403792807 We can use several methods for numerical evaluation:: sage: airy_ai_prime(4).n(algorithm='mpmath') -0.00195864095020418 sage: airy_ai_prime(4).n(algorithm='mpmath', prec=100) -0.0019586409502041789001381409184 sage: airy_ai_prime(4).n(algorithm='scipy') # rel tol 1e-10 -0.00195864095020418 sage: airy_ai_prime(I).n(algorithm='scipy') # rel tol 1e-10 -0.43249265984180707 + 0.09804785622924324*I TESTS:: sage: parent(airy_ai_prime(3).n(algorithm='scipy')) Real Field with 53 bits of precision sage: airy_ai_prime(3).n(algorithm='scipy', prec=200) Traceback (most recent call last): ... NotImplementedError: airy_ai_prime not implemented for precision > 53 """ algorithm = kwargs.get('algorithm', 'mpmath') or 'mpmath' parent = kwargs.get('parent', None) if algorithm == 'scipy': if hasattr(parent, 'prec') and parent.prec() > 53: raise NotImplementedError("%s not implemented for precision > 53"%self.name()) from sage.rings.all import RR, CC from sage.functions.other import real,imag from scipy.special import airy as airy if x in RR: y = airy(real(x))[1] if parent is None: return RR(y) else: y = airy(complex(real(x),imag(x)))[1] if parent is None: return CC(y) return parent(y) elif algorithm == 'mpmath': import mpmath from sage.libs.mpmath import utils as mpmath_utils return mpmath_utils.call(mpmath.airyai, x, derivative=1, parent=parent) else: raise ValueError("unknown algorithm '%s'" % algorithm)
def _evalf_(self, x, **kwargs): """ EXAMPLES:: sage: airy_bi_prime(0.0) 0.448288357353826 We can use several methods for numerical evaluation:: sage: airy_bi_prime(4).n(algorithm='mpmath') 161.926683504613 sage: airy_bi_prime(4).n(algorithm='mpmath', prec=100) 161.92668350461340184309492429 sage: airy_bi_prime(4).n(algorithm='scipy') # rel tol 1e-10 161.92668350461398 sage: airy_bi_prime(I).n(algorithm='scipy') # rel tol 1e-10 0.135026646710819 - 0.1288373867812549*I TESTS:: sage: parent(airy_bi_prime(3).n(algorithm='scipy')) Real Field with 53 bits of precision sage: airy_bi_prime(3).n(algorithm='scipy', prec=200) Traceback (most recent call last): ... NotImplementedError: airy_bi_prime not implemented for precision > 53 """ algorithm = kwargs.get('algorithm', 'mpmath') or 'mpmath' parent = kwargs.get('parent', None) if algorithm == 'scipy': if hasattr(parent, 'prec') and parent.prec() > 53: raise NotImplementedError("%s not implemented for precision > 53"%self.name()) from sage.rings.all import RR, CC from sage.functions.other import real,imag from scipy.special import airy as airy if x in RR: y = airy(real(x))[3] if parent is None: return RR(y) else: y = airy(complex(real(x),imag(x)))[3] if parent is None: return CC(y) return parent(y) elif algorithm == 'mpmath': import mpmath from sage.libs.mpmath import utils as mpmath_utils return mpmath_utils.call(mpmath.airybi, x, derivative=1, parent=parent) else: raise ValueError("unknown algorithm '%s'" % algorithm)
def get_wavefunction(self, index, dots_num=CALC_STEPS_NUM): if self.states == []: self.states = self.get_eigen_states() wf_obj = self.states[index] # {'energy':, tms: [mx mx mx], 'c':, 'd': } if VERBOSE: print "Getting wavefunction for state", index, "with energy", erg2eV(wf_obj['energy']) dot_step = sum([interval.width for interval in self.data]) / dots_num x, y = [], [] offset = 0 for i in range(len(self.data)): # Getting wavefunction coefficients for the i-th region if i == 0: c, d = wf_obj['c'], wf_obj['d'] elif i == len(self.data)-1: c, d = 1, 0 else: c, d = self.get_c_d( m2prod( *wf_obj['tms'][i:] )) # Local read coordinate for the i-th region xloc = np.arange(0, self.data[i].width, dot_step) # Reduced coordinate, the argument of Airy wavefunction, for the i-th region z = np.array( [self.data[i].get_z(wf_obj['energy'], dx) for dx in xloc] ) (Ai, Aid, Bi, Bid) = airy(z) # Moving i-th x to its place x = np.concatenate((x, xloc + offset)) offset += self.data[i].width y = np.concatenate((y, c*Ai + d*Bi)) if VERBOSE: print "Layer", str(i) + ": ", "c =", c, "\t", "d =", d y = self.normilized(dot_step, y) # return (x, y + erg2eV(wf_obj['energy'])) if self.direction == -1: x = x[::-1] return (x, y)
def get_transfer_matrix(self, index, energy): '''Returns Numpy matrix of the chosen energy level and interface index''' self.__process() # if VERBOSE: print "Getting transfer matrix for index", index, "and energy", erg2eV(energy) lr1 = self.data[index] lr2 = self.data[index+1] # print "Z_1_end:", lr1.get_z(energy, lr1.width), "Z_2_start:", lr2.get_z(energy, 0) old_settings = np.seterr(over='ignore') (a1, ad1, b1, bd1) = airy( lr1.get_z(energy, lr1.width) ) (a2, ad2, b2, bd2) = airy( lr2.get_z(energy, 0) ) # print "UNDER POWER", lr2.mass * lr2.angle / lr1.mass / lr1.angle msu = lr2.mass * lr2.angle / lr1.mass / lr1.angle ms = np.sign(msu) * np.power(np.abs(msu), 1./3) p = np.pi * (a2 * bd1 - ms * ad2 * b1) q = np.pi * (b2 * bd1 - ms * bd2 * b1) r = np.pi * (ms * ad2 * a1 - a2 * ad1) s = np.pi * (ms * bd2 * a1 - b2 * ad1) np.seterr(**old_settings) return np.matrix([[p, q], [r, s]])
def testAiryAnalyticalNegative(self, x0, intervalSize): """Tests Airy ODE y'' = xy against analytical solution with a negative step""" # Assumptions: the initial condition time is not too big assume(abs(x0) < 1e4) # Initial conditions taken from the airy function at the initial time Ai, Aip, Bi, Bip = airy(x0) y0 = [Ai, Aip] # Own solver build (force double precision) RK4_y0 = np.array([[y0]]).astype(np.float64) RK4_solver = RK4Solver(x0, RK4_y0, -self.dx, self.RK4_functions) # Evolution of the system RK4_solver_y = RK4_solver.solve(RK4_solver.x0 - intervalSize)[0, 0, :] Ai, Aip, Bi, Bip = airy(RK4_solver.x0) # Test that both data are almost the same, up to 4 decimal places np.testing.assert_almost_equal(RK4_solver_y, [Ai, Aip], decimal=4)
def exactSolution2(x,t) : dx = x[1] - x[0] left = np.arange(x[0]-1000.,x[0],dx) sizeL = np.size(left) right = np.arange(x[-1] + dx,x[-1] + 1000., dx) sizeR = np.size(right) x2 = np.concatenate((left,x,right)) a = np.power(3.*t,-1./3.) Ai,Aip,Bi,Bip = special.airy(x2*a) e = np.exp(-x2*x2) b = np.convolve(a*Ai,e,'same')/np.sum(np.absolute(e)) c = b[sizeL:sizeL+x.size] print(t) return c
def pbcf_series(mu, ct, zeta, phi): r"""Asymptotic series expansion of parabolic cylinder function: .. math:: U\left(-\frac{1}{2}\mu^{2},\mu t\sqrt{2}\right) :param mu: The value of :math:`\mu = 2n + 1` :param ct: The value of :math:`t = \frac{x}{\sqrt{\mu}}` :param zeta: The value of :math:`\zeta` :param phi: The value of :math:`\phi(\zeta)` """ # Coefficients # http://dlmf.nist.gov/12.10#E43 a0 = 1.0 a1 = 0.10416666666666666667 a2 = 0.08355034722222222222 a3 = 0.12822657455632716049 a4 = 0.29184902646414046425 a5 = 0.88162726744375765242 b0 = 1.0 b1 = -0.14583333333333333333 b2 = -0.09874131944444444444 b3 = -0.14331205391589506173 b4 = -0.31722720267841354810 b5 = -0.94242914795712024914 a = (a0, a1, a2, a3, a4, a5) b = (b0, b1, b2, b3, b4, b5) # Polynomials # http://dlmf.nist.gov/12.10#E9 u0 = 1.0 u1 = ( 1.0*ct**3 - 6.0*ct) / 24.0 u2 = ( -9.0*ct**4 + 249.0*ct**2 + 145.0) / 1152.0 u3 = ( -4042.0*ct**9 + 18189.0*ct**7 - 28287.0*ct**5 - 151995.0*ct**3 - 259290.0*ct) / 414720.0 u4 = ( 72756.0*ct**10 - 321339.0*ct**8 - 154982.0*ct**6 + 50938215.0*ct**4 + 122602962.0*ct**2 + 12773113.0) / 39813120.0 u5 = (82393456.0*ct**15 - 617950920.0*ct**13 + 1994971575.0*ct**11 - 3630137104.0*ct**9 + 4433574213.0*ct**7 - 37370295816.0*ct**5 - 119582875013.0*ct**3 - 34009066266.0*ct) / 6688604160.0 u = (u0, u1, u2, u3, u4, u5) # Airy Evaluation (Bi and Bip unused) Ai, Aip, Bi, Bip = airy(mu**(4.0/6.0) * zeta) # Terms for U # http://dlmf.nist.gov/12.10#E42 A0 = b[0]*u[0] A1 = (b[2]*u[0] + phi**6*b[1]*u[1] + phi**12*b[0]*u[2]) / zeta**3 A2 = (b[4]*u[0] + phi**6*b[3]*u[1] + phi**12*b[2]*u[2] + phi**18*b[1]*u[3] + phi**24*b[0]*u[4]) / zeta**6 B0 = -(a[1]*u[0] + phi**6*a[0]*u[1]) / zeta**2 B1 = -(a[3]*u[0] + phi**6*a[2]*u[1] + phi**12*a[1]*u[2] + phi**18*a[0]*u[3]) / zeta**5 B2 = -(a[5]*u[0] + phi**6*a[4]*u[1] + phi**12*a[3]*u[2] + phi**18*a[2]*u[3] + phi**24*a[1]*u[4] + phi**30*a[0]*u[5]) / zeta**8 # U # http://dlmf.nist.gov/12.10#E35 U = phi * (Ai * (A0 + A1/mu**2.0 + A2/mu**4.0) + Aip * (B0 + B1/mu**2.0 + B2/mu**4.0) / mu**(8.0/6.0)) return U
def compare_airy_one(a = -14, b = 10, n = 100): """ Compares the first approximation of Ai(x) with numpy's Ai(x), in the range [a, b), b > a, using n terms in the approximation sum. """ # Step size of 0.01 x = arange(a, b, 0.01) theory = [airy(y)[0] for y in x] # Compute n terms in the sum experiment = [airy_one(y, n) for y in x] plb.plot(x, theory) plb.plot(x, experiment) plb.show()
def pbcf_asy_tp(n, t): r"""Asymptotic series expansion of parabolic cylinder function: .. math:: U\left(-\frac{1}{2}\mu^{2},\mu t\sqrt{2}\right) for :math:`t \approx 1`. This is the turning point special case. :param n: The order :math:`n` :param t: The rescaled variable :math:`t` """ mu = 2.0 * n + 1.0 # Series inversion zeta = (-1.1154602376350014386 + 0.94683206534259310319*t + 0.20092390951413596864*t**2 - 0.044104995690190539136*t**3 + 0.017469790174220817687*t**4 - 0.0088287554164487068288*t**5 + 0.0051211352582927995985*t**6 - 0.0032244338764873460755*t**7 + 0.0021125921956647975404*t**8 - 0.0013843459602562093761*t**9 + 0.00087302390087403782068*t**10 - 0.00051134856243343516386*t**11 + 0.00026957449214014972347*t**12 - 0.00012440612318221805202*t**13 + 0.000048963028297618756177*t**14 - 0.000015993129143629483122*t**15 + 4.1983046448762575472*10**-6*t**16 - 8.4840463365499518479*10**-7*t**17 + 1.2360723726177868995*10**-7*t**18 - 1.1537952829608371539*10**-8*t**19 + 5.1762857628454208175*10**-10*t**20) phi = (1.0276932750036503140 - 0.21808283408806466225*t + 0.14122174457564771016*t**2 - 0.10816400897094073140*t**3 + 0.088874166058550695301*t**4 - 0.075714541592906584263*t**5 + 0.065443222791321861057*t**6 - 0.056156780196999485459*t**7 + 0.046662565448600134022*t**8 - 0.036547770139551846069*t**9 + 0.026279904347178909432*t**10 - 0.016935586586706330798*t**11 + 0.0095718282783427771267*t**12 - 0.0046495457010873127526*t**13 + 0.0019014010421815025206*t**14 - 0.00063945223108083177494*t**15 + 0.00017170521340783134157*t**16 - 0.000035325775105885003427*t**17 + 5.2214994798105409241*10**-6*t**18 - 4.9317900171943814621*10**-7*t**19 + 2.2343423148466235499*10**-8*t**20) # Airy Evaluation (Bi and Bip unused) Ai, Aip, _, _ = airy(mu**(4.0 / 6.0) * zeta) # Terms for U # http://dlmf.nist.gov/12.10#E42 A0 = 1.0 A1 = -0.0086458333333333333333 + 0.0088247644520537323073*zeta - 0.0074183103614150198401*zeta**2 + 0.0053175928144826954351*zeta**3 - 0.0036749699295810273907*zeta**4 + 0.0024548403578794918840*zeta**5 A2 = 0.0061297344505962282500 - 0.0094387404479761494580*zeta + 0.011065789808355794898*zeta**2 - 0.011160126023304710852*zeta**3 + 0.010218849174417654722*zeta**4 - 0.0087256605902535063232*zeta**5 B0 = -0.040497462318049494582 + 0.015555555555555555556*zeta - 0.0080047422249528129358*zeta**2 + 0.0041844376699171406787*zeta**3 - 0.0023557992011138269642*zeta**4 + 0.0013016588855262778612*zeta**5 B1 = 0.014067425869597622078 - 0.010583886849378850867*zeta + 0.0088855396810720634546*zeta**2 - 0.0071105198593437325742*zeta**3 + 0.0054283720667346030128*zeta**4 - 0.0039819488927847170035*zeta**5 B2 = -0.021934053543058220142 + 0.022346550505843322786*zeta - 0.024595927387236822024*zeta**2 + 0.025053467465276891847*zeta**3 - 0.023734309391991717696*zeta**4 + 0.021194552738417480440*zeta**5 # U # http://dlmf.nist.gov/12.10#E35 U = phi * (Ai * (A0 + A1 / mu**2.0 + A2 / mu**4.0) + Aip * (B0 + B1 / mu**2.0 + B2 / mu**4.0) / mu**(8.0 / 6.0)) return U
def impedance(self, w, L=None, imax=3, free=False): L = L or (2*_np.pi * self.rho) Lfrac = L / (2*_np.pi * self.rho) n = w/_c * self.rho if free: Z = (120/2 * 1.354/3**(1/3)*_np.exp(1j*_np.pi/6) * (w/_c/self.rho**2)**(1/3) * L) return Z u0 = _np.pi**2/2**(2/3) * (n * (2*self.h/self.rho)**(3/2))**(-4/3) Z = (1 + 0*1j)*_Z0 * 16 * u0 F = _np.zeros(len(w), dtype=complex) for p in range(0, imax): up = u0*(2*p + 1)**2 Ai, Ail, Bi, Bil = _scyspe.airy(up) Ri = Ail*Ail + up * Ai*Ai Ai, Ail, Bi, Bil = _scyspe.airye(up) Im = Ail*Bil + up * Ai*Bi F += Ri - 1j * Im Z *= F return Z * n * self.h / self.rho * Lfrac
def A_from_w2(w2, num_vs_sym): def f(t): if num_vs_sym: # numpy matrix M = np.matrix([[0, 1], [-w2(t), 0]]) elif num_vs_sym == False: M = sym.Matrix([[0, 1], [-w2(t), 0]]) return M return f # --- Airy equation stuff --- # Airy = {} Airy["name"] = "Airy" Ai0, Aip0, Bi0, Bip0 = special.airy(0) Airy["x0"] = np.array([Ai0, -Aip0]) Airy["ylim"] = (-0.75, 0.75) def w2_Airy(t): return t Airy["w2"] = w2_Airy Airy["A"] = A_from_w2(w2_Airy, True) def Airy_sol(t): Ai0, Aip0, Bi0, Bip0 = special.airy(0) M = (1 /
def integrand(x, amplitude=0): ai, aip, bi, bip = special.airy((x**2) + ((2 * scaled_potential) / ((2 * amplitude)**1.5))) return (x * ai)**2
def test_airyai(self): assert_mpmath_equal(lambda z: sc.airy(z)[0], mpmath.airyai, [Arg()])
def test_airyai_prime(self): assert_mpmath_equal(lambda z: sc.airy(z)[1], lambda z: mpmath.airyai(z, derivative=1), [Arg()])
def F(x): f = sc.airy(x) return f[0]
# thus, start from scratch print >> sys.stderr,"# starting from scratch" dx = args.dx space = args.space space0 = args.zero speed = args.speed x = (np.arange(space)-space0)*dx # use semianalytical approximations as starting conditions if args.growthterm == "selection": try: if mutationmodel == "diff": # solution is proportial to exp(vx/2)Airy(v^2/4-x) for small fitness (by neglecting nonlinear term) # Airy function is oscillating, however, thus find first zero of it, and approximate u by its # linear branch starting at the maximum of the asymptotic solution above (before its first zero) uairy = np.exp(speed*x/2.)*airy(speed**2/4.-x)[0] u = uairy firstAiZero = min(int((2.3381-speed**2/4)/dx)+space0,space-1) idxmax = u[:firstAiZero].argmax() u = u/u[idxmax]*x[idxmax]/2 u[idxmax:] = x[idxmax:]/2 elif mutationmodel == "exp": # from semianalytic considerations we know u has three regimes (see [Geyrhofer, 2014], also defined in [Good et al., 2012]) try: popsize = np.exp(np.sqrt(2.*np.log(1./mutationrate)*speed))/mutationrate # inverting relation in [Good et al., 2012] idxcrossover2 = ((x-np.sqrt(2*speed*np.log(popsize*np.sqrt(speed))))**2).argmin() # crossover at x_c except: idxcrossover2 = 0 idxcrossover1 = ((x-speed)**2).argmin() # crossover at v u = x/2 if idxcrossover1 < idxcrossover2:
else: g = mt / (h**2) * el * (-E + interpolation(V, z, stepz)) * sol[0] return [dpsi, g] def testSolve(E): n2d = 1.6 * 10**18 electric_field = shooting_poisson(W, n2d, E0) stepz = 10**(-10) siz = 10**3 z = [stepz * i for i in range(siz)] V = [electric_field * z[i] for i in range(len(z))] m = 9.1 * 10**(-31) CI_tableau = [0, 0] CI_tableau[0] = 0. CI_tableau[1] = 0.1 sol_ode = odeint(schrodingertest, CI_tableau, z, (stepz, E, V, m)) psi = [sol_ode[i, 0] for i in range(len(z))] plot(z, psi) plt.show() return psi tabz = [0.01 * i for i in range(500)] tabairy = [airy(zz - 2.3381)[0]**2 for zz in tabz] plot(tabz, tabairy) plt.show()
from cheb import cheb from scipy.linalg import eig from scipy.special import airy import matplotlib.pyplot as plt # p22.py - 5th eigenvector of Airy equation u_xx = lambda*x*u for N in range(12,60,12): D,x = cheb(N) D2 = np.dot(D,D) D2 = D2[1:-1,1:-1] Lam,V = eig(D2,np.diag(x[1:-1])) # generalized ev problem Lam=np.real(Lam) V=np.real(V) V = V[:,Lam>0] Lam = Lam[Lam>0] iisort=np.argsort(Lam) ii=iisort[4] lam=Lam[ii] v = np.concatenate(([0],V[:,ii],[0])) v = v/v[N/2]*airy(0)[0] xx = np.linspace(-1,1,201) vv = np.polyval(np.polyfit(x,v,N),xx); plt.plot(xx,vv) plt.scatter(x,v) plt.title('N = %d eig = %15.10f' % (N,lam)) plt.xlim(-1,1) plt.show() plt.close()
import matplotlib.pyplot as plt y0 = np.empty((2, )) y0[0] = 1.0 / 3**(2. / 3) / gamma(2. / 3) y0[1] = -1.0 / 3**(1. / 3) / gamma(1. / 3) def func(y, z): return np.array([y[1], z * y[0]]) z = np.arange(0, 4., 0.01) y_ana = airy(z)[0] y_odeint = odeint(func, y0, z)[:, 0] def func2(z, y): return np.array([y[1], z * y[0]]) y_ode = [] z_ode = [] edo = ode(func2) edo.set_integrator('dopri5') edo.set_initial_value(y0, t=0) dt = 0.01 while edo.successful() and edo.t < 4.:
def test_airybi_prime_complex(self): assert_mpmath_equal(lambda z: sc.airy(z)[3], lambda z: mpmath.airybi(z, derivative=1), [ComplexArg()])
### p12 ### ch 1.4.3 Integrating using samples ### p12 ### ch 1.4.4 Ordinary differential equations(odeint) ### p13 ### p14 from scipy.integrate import odeint from scipy.special import gamma, airy y1_0 = 1.0/3**(2.0/3.0) / gamma(2.0/3.0) y0_0 = -1.0/3**(1.0/3.0) / gamma(1.0/3.0) y0 = [y0_0, y1_0] def func(y, t): return [t*y[1], y[0]] def gradient(y, t): return [[0, t], [1, 0]] x = arange(0, 4.0, 0.01) t = x ychk = airy(x)[0] y = odeint(func, y0, t) y2 = odeint(func, y0, t, Dfun=gradient) print ychk[:36:6] print y[:36:6,1] print y2[:36:6,1]
from scipy import special from numpy import r_, transpose import pylab as plt z = r_[-5:1.5:100j] vals = special.airy(z) plt.plot(z,transpose(vals)) plt.xlabel('z') plt.title('Airy Functions and Derivatives') plt.show()
def _pp_low_frequency(self, frequency_array, u_max=10, high_frequency_transition=np.inf): """ Computes the parallel-plates impedance according to eq. 8 of [Chao2011]_. For frequencies larger than the cut-off frequencies, it approaches the low-frequency free-space impedance, i.e. the impedance increases as :math:`f^{1/3}`. Parameters ---------- frequency_array : float, array Frequencies at which to compute the impedance. u_max : float, optional Maximum value of u, for which the summands are evaluated. The Airy functions become numerically unstable for u>100. The real part is exponentially supressed, but imaginary part is not and the remaining sum from u_max to infinity is estimated analytically. The default is 10. high_frequency_transition : float, optional Use the low-frequency free-space impedance for frequencies above `high_frequency_transition` times cut_off frequency. The default is np.inf. Raises ------ ValueError Raised if `high_frequency_transition` < 1. Yields ------ None. """ # using high_frequency_transition factor of 1 yields unphysical results if high_frequency_transition <= 1.0: raise ValueError( 'high frequency transition must be greater than 1') n_array = frequency_array / self.f_0 self.impedance = np.zeros_like(n_array, dtype=complex) # parallel plates cut-off frequency in units of f_0 n_cut = np.sqrt(2 / 3) * (np.pi / self.Delta)**1.5 # use approximate equation for frequencies above high_frequency_transition * n_cut approx_indexes = bm.where(n_array, more_than=high_frequency_transition * n_cut) if np.count_nonzero(approx_indexes) > 0: self.impedance[approx_indexes] = self._fs_low_frequency( frequency_array[approx_indexes]) # use exact result for all other frequencies (and ignore f=0) exact_indexes = np.invert(approx_indexes) * n_array != 0 # if there is nothing to calculate, we are done ... if np.count_nonzero(exact_indexes) == 0: return n_array = n_array[ exact_indexes] # override for convenience and exclude f=0 # maximum p(n) to have u(p,n)<u_max(n) pMax_array = np.array( np.ceil(self.Delta * n_array**(2 / 3) * np.sqrt(u_max) / (2**(2 / 3) * np.pi) - 0.5), dtype=int) pMax = pMax_array[ -1] # maximum p; assumes largest frequency is at last array element p_matrix = np.zeros(shape=(len(n_array), pMax), dtype=int) # matrix to store the summands Z_matrix = np.zeros_like(p_matrix, dtype=complex) for nit, n in enumerate(n_array): # first element of p_matrix is 1 to ensure evaluation at u_min... # ... if n is large enough so that u_min < 100, (i.e. airy(u_min) does not yield np.nan) if pMax_array[nit] == 0 and n > ( np.pi / self.Delta)**1.5 / np.sqrt(2) / 100**0.75: p_matrix[nit, 0] = 1 else: p_matrix[nit, :pMax_array[nit]] = ( 2 * np.arange(pMax_array[nit]) + 1)**2 # evaluate Airy functions only at these values of p indexes = p_matrix > 0 # argument of the Airy functions u_matrix = ((np.pi / 2**(1 / 3) / self.Delta)**2 / n_array**(4 / 3) * p_matrix.T).T # evaluate Airy function only at relevant indexes airy_matrix = airy( u_matrix[indexes]) # returns Ai(u), Ai'(u), Bi(u), Bi'(u) Ci_matrix = airy_matrix[0] - 1j * airy_matrix[2] Ci_prime_matrix = airy_matrix[1] - 1j * airy_matrix[3] Z_matrix[indexes] = airy_matrix[1] * Ci_prime_matrix \ + u_matrix[indexes] * airy_matrix[0] * Ci_matrix # sum over p self.impedance[exact_indexes] = np.sum(Z_matrix, axis=1) # the sum in eq. 8 is up to infinity, but we stop at p_max; the real part is exponentially # surpressed for large u, but the imaginary part is not; using the assymptotic expression # of the imaginary summands for large u, the remaining sum from p_max to infinity can be # performed analytically by Mathematica 12.1.0.0. self.impedance[exact_indexes] += 1j * 2**(5/3) / (4096*np.pi**6) \ * (self.Delta * n_array**(2/3))**5 * polygamma(4, pMax_array+1) self.impedance[exact_indexes] *= self.Z0 * 4*np.pi**2 * 2**(1/3) \ * 1/self.Delta / n_array**(1/3)
def pbcf(n, theta): """Asymptotic series expansion of parabolic cylinder function The implementation is based on sections 3.2 and 3.3 from the original paper. Compared to the published version this code adds one more term to the asymptotic series. The detailed formulas can be found at [parabolic-asymptotics]_. The evaluation is done in a transformed variable :math:`\theta := \arccos(t)` where :math:`t := x / \mu` and :math:`\mu := \sqrt{2n + 1}`. Parameters ---------- n : int Quadrature order theta : ndarray Transformed position variable Returns ------- U : ndarray Value of the parabolic cylinder function :math:`U(a, \theta)`. Ud : ndarray Value of the derivative :math:`U^{\prime}(a, \theta)` of the parabolic cylinder function. See Also -------- h_roots_asy References ---------- .. [parabolic-asymptotics] http://dlmf.nist.gov/12.10#vii """ st = sin(theta) ct = cos(theta) # http://dlmf.nist.gov/12.10#vii mu = 2.0 * n + 1.0 # http://dlmf.nist.gov/12.10#E23 eta = 0.5 * theta - 0.5 * st * ct # http://dlmf.nist.gov/12.10#E39 zeta = -(3.0 * eta / 2.0) ** (2.0 / 3.0) # http://dlmf.nist.gov/12.10#E40 phi = (-zeta / st**2) ** (0.25) # Coefficients # http://dlmf.nist.gov/12.10#E43 a0 = 1.0 a1 = 0.10416666666666666667 a2 = 0.08355034722222222222 a3 = 0.12822657455632716049 a4 = 0.29184902646414046425 a5 = 0.88162726744375765242 b0 = 1.0 b1 = -0.14583333333333333333 b2 = -0.09874131944444444444 b3 = -0.14331205391589506173 b4 = -0.31722720267841354810 b5 = -0.94242914795712024914 a = (a0, a1, a2, a3, a4, a5) b = (b0, b1, b2, b3, b4, b5) # Polynomials # http://dlmf.nist.gov/12.10#E9 # http://dlmf.nist.gov/12.10#E10 u0 = 1.0 ctp = ct ** arange(16).reshape((-1,1)) u1 = ( 1.0*ctp[3,:] - 6.0*ct) / 24.0 u2 = ( -9.0*ctp[4,:] + 249.0*ctp[2,:] + 145.0) / 1152.0 u3 = ( -4042.0*ctp[9,:] + 18189.0*ctp[7,:] - 28287.0*ctp[5,:] - 151995.0*ctp[3,:] - 259290.0*ct) / 414720.0 u4 = ( 72756.0*ctp[10,:] - 321339.0*ctp[8,:] - 154982.0*ctp[6,:] + 50938215.0*ctp[4,:] + 122602962.0*ctp[2,:] + 12773113.0) / 39813120.0 u5 = (82393456.0*ctp[15,:] - 617950920.0*ctp[13,:] + 1994971575.0*ctp[11,:] - 3630137104.0*ctp[9,:] + 4433574213.0*ctp[7,:] - 37370295816.0*ctp[5,:] - 119582875013.0*ctp[3,:] - 34009066266.0*ct) / 6688604160.0 v0 = 1.0 v1 = ( 1.0*ctp[3,:] + 6.0*ct) / 24.0 v2 = ( 15.0*ctp[4,:] - 327.0*ctp[2,:] - 143.0) / 1152.0 v3 = ( -4042.0*ctp[9,:] + 18189.0*ctp[7,:] - 36387.0*ctp[5,:] + 238425.0*ctp[3,:] + 259290.0*ct) / 414720.0 v4 = ( -121260.0*ctp[10,:] + 551733.0*ctp[8,:] - 151958.0*ctp[6,:] - 57484425.0*ctp[4,:] - 132752238.0*ctp[2,:] - 12118727) / 39813120.0 v5 = (82393456.0*ctp[15,:] - 617950920.0*ctp[13,:] + 2025529095.0*ctp[11,:] - 3750839308.0*ctp[9,:] + 3832454253.0*ctp[7,:] + 35213253348.0*ctp[5,:] + 130919230435.0*ctp[3,:] + 34009066266*ct) / 6688604160.0 u = (u0, u1, u2, u3, u4, u5) v = (v0, v1, v2, v3, v4, v5) # Airy Evaluation (Bi and Bip unused) Ai, Aip, Bi, Bip = airy(mu**(4.0 / 6.0) * zeta) # Prefactor for U P = 2.0 * sqrt(pi) * mu**(1.0 / 6.0) * phi # Terms for U # http://dlmf.nist.gov/12.10#E42 A0 = b[0]*u[0] A1 = (b[2]*u[0] + phi**6*b[1]*u[1] + phi**12*b[0]*u[2]) / zeta**3 A2 = (b[4]*u[0] + phi**6*b[3]*u[1] + phi**12*b[2]*u[2] + phi**18*b[1]*u[3] + phi**24*b[0]*u[4]) / zeta**6 B0 = -(a[1]*u[0] + phi**6*a[0]*u[1]) / zeta**2 B1 = -(a[3]*u[0] + phi**6*a[2]*u[1] + phi**12*a[1]*u[2] + phi**18*a[0]*u[3]) / zeta**5 B2 = -(a[5]*u[0] + phi**6*a[4]*u[1] + phi**12*a[3]*u[2] + phi**18*a[2]*u[3] + phi**24*a[1]*u[4] + phi**30*a[0]*u[5]) / zeta**8 # U # http://dlmf.nist.gov/12.10#E35 U = P * (Ai * (A0 + A1/mu**2.0 + A2/mu**4.0) + Aip * (B0 + B1/mu**2.0 + B2/mu**4.0) / mu**(8.0/6.0)) # Prefactor for derivative of U Pd = sqrt(2.0*pi) * mu**(2.0/6.0) / phi # Terms for derivative of U # http://dlmf.nist.gov/12.10#E46 C0 = -(b[1]*v[0] + phi**6*b[0]*v[1]) / zeta C1 = -(b[3]*v[0] + phi**6*b[2]*v[1] + phi**12*b[1]*v[2] + phi**18*b[0]*v[3]) / zeta**4 C2 = -(b[5]*v[0] + phi**6*b[4]*v[1] + phi**12*b[3]*v[2] + phi**18*b[2]*v[3] + phi**24*b[1]*v[4] + phi**30*b[0]*v[5]) / zeta**7 D0 = a[0]*v[0] D1 = (a[2]*v[0] + phi**6*a[1]*v[1] + phi**12*a[0]*v[2]) / zeta**3 D2 = (a[4]*v[0] + phi**6*a[3]*v[1] + phi**12*a[2]*v[2] + phi**18*a[1]*v[3] + phi**24*a[0]*v[4]) / zeta**6 # Derivative of U # http://dlmf.nist.gov/12.10#E36 Ud = Pd * (Ai * (C0 + C1 / mu**2.0 + C2 / mu**4.0) / mu**(4.0 / 6.0) + Aip * (D0 + D1 / mu**2.0 + D2 / mu**4.0)) return U, Ud
def new_airy(z): zn = 2.32 return (airy(z-zn)[0])**2
def _pbcf(n, theta): """Asymptotic series expansion of parabolic cylinder function The implementation is based on sections 3.2 and 3.3 from the original paper. Compared to the published version this code adds one more term to the asymptotic series. The detailed formulas can be found at [parabolic-asymptotics]_. The evaluation is done in a transformed variable :math:`\theta := \arccos(t)` where :math:`t := x / \mu` and :math:`\mu := \sqrt{2n + 1}`. Parameters ---------- n : int Quadrature order theta : ndarray Transformed position variable Returns ------- U : ndarray Value of the parabolic cylinder function :math:`U(a, \theta)`. Ud : ndarray Value of the derivative :math:`U^{\prime}(a, \theta)` of the parabolic cylinder function. See Also -------- h_roots_asy References ---------- .. [parabolic-asymptotics] http://dlmf.nist.gov/12.10#vii """ st = sin(theta) ct = cos(theta) # http://dlmf.nist.gov/12.10#vii mu = 2.0*n + 1.0 # http://dlmf.nist.gov/12.10#E23 eta = 0.5*theta - 0.5*st*ct # http://dlmf.nist.gov/12.10#E39 zeta = -(3.0*eta/2.0) ** (2.0/3.0) # http://dlmf.nist.gov/12.10#E40 phi = (-zeta / st**2) ** (0.25) # Coefficients # http://dlmf.nist.gov/12.10#E43 a0 = 1.0 a1 = 0.10416666666666666667 a2 = 0.08355034722222222222 a3 = 0.12822657455632716049 a4 = 0.29184902646414046425 a5 = 0.88162726744375765242 b0 = 1.0 b1 = -0.14583333333333333333 b2 = -0.09874131944444444444 b3 = -0.14331205391589506173 b4 = -0.31722720267841354810 b5 = -0.94242914795712024914 # Polynomials # http://dlmf.nist.gov/12.10#E9 # http://dlmf.nist.gov/12.10#E10 ctp = ct ** arange(16).reshape((-1,1)) u0 = 1.0 u1 = (1.0*ctp[3,:] - 6.0*ct) / 24.0 u2 = (-9.0*ctp[4,:] + 249.0*ctp[2,:] + 145.0) / 1152.0 u3 = (-4042.0*ctp[9,:] + 18189.0*ctp[7,:] - 28287.0*ctp[5,:] - 151995.0*ctp[3,:] - 259290.0*ct) / 414720.0 u4 = (72756.0*ctp[10,:] - 321339.0*ctp[8,:] - 154982.0*ctp[6,:] + 50938215.0*ctp[4,:] + 122602962.0*ctp[2,:] + 12773113.0) / 39813120.0 u5 = (82393456.0*ctp[15,:] - 617950920.0*ctp[13,:] + 1994971575.0*ctp[11,:] - 3630137104.0*ctp[9,:] + 4433574213.0*ctp[7,:] - 37370295816.0*ctp[5,:] - 119582875013.0*ctp[3,:] - 34009066266.0*ct) / 6688604160.0 v0 = 1.0 v1 = (1.0*ctp[3,:] + 6.0*ct) / 24.0 v2 = (15.0*ctp[4,:] - 327.0*ctp[2,:] - 143.0) / 1152.0 v3 = (-4042.0*ctp[9,:] + 18189.0*ctp[7,:] - 36387.0*ctp[5,:] + 238425.0*ctp[3,:] + 259290.0*ct) / 414720.0 v4 = (-121260.0*ctp[10,:] + 551733.0*ctp[8,:] - 151958.0*ctp[6,:] - 57484425.0*ctp[4,:] - 132752238.0*ctp[2,:] - 12118727) / 39813120.0 v5 = (82393456.0*ctp[15,:] - 617950920.0*ctp[13,:] + 2025529095.0*ctp[11,:] - 3750839308.0*ctp[9,:] + 3832454253.0*ctp[7,:] + 35213253348.0*ctp[5,:] + 130919230435.0*ctp[3,:] + 34009066266*ct) / 6688604160.0 # Airy Evaluation (Bi and Bip unused) Ai, Aip, Bi, Bip = airy(mu**(4.0/6.0) * zeta) # Prefactor for U P = 2.0*sqrt(pi) * mu**(1.0/6.0) * phi # Terms for U # http://dlmf.nist.gov/12.10#E42 phip = phi ** arange(6, 31, 6).reshape((-1,1)) A0 = b0*u0 A1 = (b2*u0 + phip[0,:]*b1*u1 + phip[1,:]*b0*u2) / zeta**3 A2 = (b4*u0 + phip[0,:]*b3*u1 + phip[1,:]*b2*u2 + phip[2,:]*b1*u3 + phip[3,:]*b0*u4) / zeta**6 B0 = -(a1*u0 + phip[0,:]*a0*u1) / zeta**2 B1 = -(a3*u0 + phip[0,:]*a2*u1 + phip[1,:]*a1*u2 + phip[2,:]*a0*u3) / zeta**5 B2 = -(a5*u0 + phip[0,:]*a4*u1 + phip[1,:]*a3*u2 + phip[2,:]*a2*u3 + phip[3,:]*a1*u4 + phip[4,:]*a0*u5) / zeta**8 # U # http://dlmf.nist.gov/12.10#E35 U = P * (Ai * (A0 + A1/mu**2.0 + A2/mu**4.0) + Aip * (B0 + B1/mu**2.0 + B2/mu**4.0) / mu**(8.0/6.0)) # Prefactor for derivative of U Pd = sqrt(2.0*pi) * mu**(2.0/6.0) / phi # Terms for derivative of U # http://dlmf.nist.gov/12.10#E46 C0 = -(b1*v0 + phip[0,:]*b0*v1) / zeta C1 = -(b3*v0 + phip[0,:]*b2*v1 + phip[1,:]*b1*v2 + phip[2,:]*b0*v3) / zeta**4 C2 = -(b5*v0 + phip[0,:]*b4*v1 + phip[1,:]*b3*v2 + phip[2,:]*b2*v3 + phip[3,:]*b1*v4 + phip[4,:]*b0*v5) / zeta**7 D0 = a0*v0 D1 = (a2*v0 + phip[0,:]*a1*v1 + phip[1,:]*a0*v2) / zeta**3 D2 = (a4*v0 + phip[0,:]*a3*v1 + phip[1,:]*a2*v2 + phip[2,:]*a1*v3 + phip[3,:]*a0*v4) / zeta**6 # Derivative of U # http://dlmf.nist.gov/12.10#E36 Ud = Pd * (Ai * (C0 + C1/mu**2.0 + C2/mu**4.0) / mu**(4.0/6.0) + Aip * (D0 + D1/mu**2.0 + D2/mu**4.0)) return U, Ud
def F(z): zn = 2.32 return (coeff*(airy(z-zn)[0])*2*A**(1.5)*z*exp(-A*z))**2
# -*- coding: utf-8 -*- """ Created on Mon Sep 14 01:08:34 2015 @author: pedrogonzalez """ from scipy.special import airy from matplotlib.pyplot import * import numpy as np xvals = np.linspace(-15, 3.0, 200) airyvals = airy(xvals) # np.array([airy(x) for x in xvals]) ai = (airyvals)[0] dai = (airyvals)[1] bi = (airyvals)[2] dbi = (airyvals)[3] fig, (ax1, ax2) = subplots(nrows=2, ncols=1, sharex=True) ax1.plot(xvals, ai, color="black") ax1.set_ylim(-.75, .75) ax1.set_title("Funcion_Airy_Ai") ax1.axhline(0.0, color="black") ax1.axvline(0.0, color="black") ax2.plot(xvals, bi, color="black") ax2.set_ylim(-.75, .75) ax2.set_title("Funcion_Airy_Bi") ax2.axhline(0.0, color="black")
#!usr/bin/env python from scipy import * import matplotlib as pl from scipy.special import airy from scipy import interpolate as Inter #a = random.ranf((10)) b = range(-100,250,1) #print a #print b #Airy_solution1 = airy(a) #print Airy_solution1 Airy_solution2 = airy(b) #print Airy_solution2 #Interpolate = Inter.interp1d(x1,Airy_solution2) #x=[1,200,300] #for i in x: Interpolate = Inter.interp1d(b,Airy_solution2) f=open("x.txt","r") k = f.readlines() #print k for i in k: i1 = float(i.replace('\n', '')) print Interpolate(i1)
plt.rcParams['font.size'] = 10 plt.rcParams['legend.numpoints'] = 3 ticks = np.arange(0, 1200, 200) labels = np.arange(-500, 700, 200) nbPoints = 250 x = np.linspace(-500, 500, 2 * nbPoints + 1) y = np.linspace(-500, 500, 2 * nbPoints + 1) X, Y = np.meshgrid(x, y) z = np.zeros((2 * nbPoints + 1, 2 * nbPoints + 1), dtype=np.complex) for i in range(2 * nbPoints + 1): for j in range(500): airyTest = airy(x[i] + 1j * y[j])[0] if (airyTest == airyTest): z[i, j] = airy(x[i] + 1j * y[j])[0] figAiScipyRe = plt.figure(figsize=(4, 4)) axAiScipyRe = figAiScipyRe.add_subplot(111) plt.pcolormesh(X, Y, np.abs(np.real(z)), cmap=msi, norm=LogNorm(), rasterized=True) plt.title(r"|Re$(\text{Ai}(x+iy))|$ -- SciPy") plt.xlabel(r"$x$") plt.ylabel(r"$y$") #ax1.xaxis.set_ticks(np.arange(-500,501,100))
eV = Hartree / 27.211386 Ang = a_0 / 0.529177210 VAng = HartreeBohr / 51.422065211 # Electric field in AU E = 0.5 * eV # hartree # L = 5. * Ang # bohr Epslon = 1. * VAng alpha = (2. * Epslon)**(1. / 3.) x0 = E / e / Epslon dzita = lambda x: alpha * (x - x0) V = lambda x: Vparametrized(x, Epslon) kSq = lambda x: kSquaredParametrized(x, E, V) Ai = lambda x: sp.airy(dzita(x))[0] Bi = lambda x: sp.airy(dzita(x))[2] a = x0 - 15. * Ang b = x0 + 15. * Ang # print x0 delta = b - a epsMachine = 1.11e-16 N = [100 * 2**x + 1 for x in range(0, 16)] # N=[1000] print N H = [delta / (n - 1) for n in N] print H # EPS = [epsMachine/h for h in H] errors = [] # print N
plt.rcParams['font.size'] = 10 plt.rcParams['legend.numpoints'] = 3 ticks = np.arange(0, 1200, 200) labels = np.arange(-500, 700, 200) nbPoints = 250 x = np.linspace(-500,500,2*nbPoints+1) y = np.linspace(-500,500,2*nbPoints+1) X, Y = np.meshgrid(x,y) z = np.zeros((2*nbPoints+1,2*nbPoints+1),dtype=np.complex) for i in range(2*nbPoints+1): for j in range(500): airyTest = airy(x[i]+1j*y[j])[0] if (airyTest == airyTest): z[i,j] = airy(x[i]+1j*y[j])[0] figAiScipyRe = plt.figure(figsize=(4,4)) axAiScipyRe = figAiScipyRe.add_subplot(111) plt.pcolormesh(X, Y, np.abs(np.real(z)), cmap=msi, norm=LogNorm(), rasterized=True) plt.title(r"|Re$(\text{Ai}(x+iy))|$ -- SciPy") plt.xlabel(r"$x$") plt.ylabel(r"$y$") #ax1.xaxis.set_ticks(np.arange(-500,501,100)) #ax1.yaxis.set_ticks(np.arange(-500,501,100)) plt.savefig("realAiry-scipy.png", bbox_inches='tight') figAiScipyIm = plt.figure(figsize=(4,4)) axAiScipyIm = figAiScipyIm.add_subplot(111)
def fundamentalSolution(x,t) : a = np.power(3.*t,-1./3.) Ai,Aip,Bi,Bip = special.airy(x*a) return a*Ai
def test_airyai_complex(self): assert_mpmath_equal(lambda z: sc.airy(z)[0], mpmath.airyai, [ComplexArg()])
from scipy import special from numpy import r_, transpose import pylab as plt z = r_[-5:1.5:100j] vals = special.airy(z) plt.plot(z, transpose(vals)) plt.xlabel('z') plt.title('Airy Functions and Derivatives') plt.show()
def test_airybi_complex(self): assert_mpmath_equal(lambda z: sc.airy(z)[2], lambda z: mpmath.airybi(z), [ComplexArg()])
def func(x): return airy(x)[0]
# Calculate the probability for a particle in the best variational wavefunction to be in the true ground state, # PHYS334 Assignment 6 from scipy.special import airy from scipy.integrate import quad from pylab import * x = linspace(0, 20, 10000) # exact solution zn = 2.32 def new_airy(z): zn = 2.32 return (airy(z-zn)[0])**2 coeff = quad(new_airy, 0, Inf)[0] ** (-0.5) print("After normalization, the coefficient = " + str(coeff)) y = coeff*airy(x - zn)[0] # variational method A = 0.8735 yprime = 2*A**(1.5)*x*exp(-A*x) ## print the plots figure() plot(x,y,label="True wavefunction") plot(x,yprime,label="Variational wavefunction") xlabel("x") ylabel("$\psi(x)$") title("variation wavefunction & true wavefunction") legend()
plt.close('all') plt.figure(figsize=(7, 7), dpi=80) iplot = 1 Nvec = np.arange(12, 49, 12) for j in range(4): N = Nvec[j] D, x = cheb(N) D2 = np.dot(D, D) D2 = D2[1:N, 1:N] lam, V = sp.linalg.eig(D2, np.diag(x[1:N])) lam = np.real(lam) idx_positive = np.argwhere(lam > 0).ravel() V = V[:, idx_positive] lam = lam[idx_positive] idx_sort = np.argsort(lam) ii = idx_sort[4] lam = lam[ii] v = np.append(0, np.append(V[:, ii], 0)) Ai, Aip, Bi, Bip = special.airy(0) v = v / v[int(N // 2)] * Ai xx = np.linspace(-1, 1, 101) vv = np.polyval(np.polyfit(x, v, N), xx) plt.subplot(2, 2, j + 1) plt.plot(xx, vv) plt.grid(True) plt.title(r'$N = %d, \mathrm{eig} = %15.10f$' % (N, lam)) plt.show()