def ExactIntegrationOfSinus(t, a=None, b=None): with precision(300): if a == None and b == None: return 0.5 * math.pi * math.sqrt(t) * (mpmath.angerj(0.5, t) - mpmath.angerj(-0.5, t)) elif a == None and b != None: a = 0 elif b == None: b = t mpmath.mp.dps = 50 mpmath.mp.pretty = True pi = mpmath.mp.pi pi = +pi fcos = mpmath.fresnelc fsin = mpmath.fresnels arg_b = mpmath.sqrt(2 * (t - b) / pi) if a == "MinusInfinity": return mpmath.sqrt( 0.5 * mpmath.mp.pi) * (-2 * mpmath.sin(t) * fcos(arg_b) + 2 * mpmath.cos(t) * fsin(arg_b) + mpmath.sin(t) - mpmath.cos(t)) else: arg_a = mpmath.sqrt(2 * (t - a) / pi) return mpmath.sqrt(2 * mpmath.mp.pi) * ( (fsin(arg_b) - fsin(arg_a)) * mpmath.cos(t) + (fcos(arg_a) - fcos(arg_b)) * mpmath.sin(t))
def _view_cone_calc(lat_geoc, lon_geoc, sat_pos, sat_vel, q_max, m): """Semi-private: Performs the viewing cone visibility calculation for the day defined by m. Note: This function is based on a paper titled "rapid satellite-to-site visibility determination based on self-adaptive interpolation technique" with some variation to account for interaction of viewing cone with the satellite orbit. Args: lat_geoc (float): site location in degrees at the start of POI lon_geoc (float): site location in degrees at the start of POI sat_pos (Vector3D): position of satellite (at the same time as sat_vel) sat_vel (Vector3D): velocity of satellite (at the same time as sat_pos) q_max (float): maximum orbital radius m (int): interval offsets (number of days after initial condition) Returns: Returns 4 numbers representing times at which the orbit is tangent to the viewing cone, Raises: ValueError: if any of the 4 formulas has a complex answer. This happens when the orbit and viewing cone do not intersect or only intersect twice. Note: With more analysis it should be possible to find a correct interval even in the case where there are only two intersections but this is beyond the current scope of the project. """ lat_geoc = (lat_geoc * mp.pi) / 180 lon_geoc = (lon_geoc * mp.pi) / 180 # P vector (also referred to as orbital angular momentum in the paper) calculations p_unit_x, p_unit_y, p_unit_z = cross(sat_pos, sat_vel) / (mp.norm(sat_pos) * mp.norm(sat_vel)) # Following are equations from Viewing cone section of referenced paper r_site_magnitude = earth_radius_at_geocetric_lat(lat_geoc) gamma1 = THETA_NAUGHT + mp.asin((r_site_magnitude * mp.sin((mp.pi / 2) + THETA_NAUGHT)) / q_max) gamma2 = mp.pi - gamma1 # Note: atan2 instead of atan to get the correct quadrant. arctan_term = mp.atan2(p_unit_x, p_unit_y) arcsin_term_gamma, arcsin_term_gamma2 = [(mp.asin((mp.cos(gamma) - p_unit_z * mp.sin(lat_geoc)) / (mp.sqrt((p_unit_x ** 2) + (p_unit_y ** 2)) * mp.cos(lat_geoc)))) for gamma in [gamma1, gamma2]] angle_1 = (arcsin_term_gamma - lon_geoc - arctan_term + 2 * mp.pi * m) angle_2 = (mp.pi - arcsin_term_gamma - lon_geoc - arctan_term + 2 * mp.pi * m) angle_3 = (arcsin_term_gamma2 - lon_geoc - arctan_term + 2 * mp.pi * m) angle_4 = (mp.pi - arcsin_term_gamma2 - lon_geoc - arctan_term + 2 * mp.pi * m) angles = [angle_1, angle_2, angle_3, angle_4] # Check for complex answers if any([not isinstance(angle, mp.mpf) for angle in angles]): raise ValueError() # Map all angles to 0 to 2*pi for idx in range(len(angles)): while angles[idx] < 0: angles[idx] += 2 * mp.pi while angles[idx] > 2 * mp.pi: angles[idx] -= 2 * mp.pi # Calculate the corresponding time for each angle and return return [mp.nint((1 / ANGULAR_VELOCITY_EARTH) * angle) for angle in angles]
def redshift_factor(radius, angle, incl, M, b_): """Calculate the redshift factor (1 + z), ignoring cosmological redshift.""" # TODO: the paper makes no sense here gff = (radius * mpmath.sin(incl) * mpmath.sin(angle))**2 gtt = -(1 - (2. * M) / radius) z_factor = (1. + np.sqrt(M / (radius ** 3)) * b_ * np.sin(incl) * np.sin(angle)) * \ (1 - 3. * M / radius) ** -.5 return z_factor
def integrand(theta, phi): evals[0] += 1 qab = q * mp.sin(theta) qa = qab * mp.cos(phi) qb = qab * mp.sin(phi) qc = q * mp.cos(theta) Zq = KERNEL_MP(qa, qb, qc)**2 return Zq * mp.sin(theta)
def sec_der(x_val: Real) -> mp.mpf: """Define the actual second derivative.""" x_squared = mp.power(x_val, 2) return ( mp.cos(x_val) + (-4 * x_squared) * mp.cos(x_squared) + -2 * mp.sin(x_squared) + mp.sin(x_val) )
def f2(x): """ Another angular integral in electron noise calculation. """ term1 = 2*x**3 * (2*mp.si(2*x)-mp.si(x)) term2 = 2*x**2 * (mp.cos(2*x) - mp.cos(x)) term3 = x * (mp.sin(2*x) - 2*mp.sin(x)) - (mp.cos(2*x) - 4* mp.cos(x) + 3) return (term1 + term2 + term3)/(12 * x**2)
def get_rotation_matrix_north_pole_to(theta, phi): from numpy import array, matmul from math import sin, cos Rx = array([[1, 0, 0], [0, sin(phi), cos(phi)], [0, -cos(phi), sin(phi)]]) Rz = array([[sin(theta), cos(theta), 0], [-cos(theta), sin(theta), 0], [0, 0, 1]]) rotation_matrix = matmul(Rz, Rx) return rotation_matrix
def go_down(phi, r): # It returns the orbit new_phi which is below phi and has distance r # (on the sphere on which our directions are located) from math import asin, sin, pi if sin(phi) - r >= -1: new_phi = asin(sin(phi) - r) else: new_phi = -pi / 2 return new_phi
def plot_basic(self): x = numpy.arange(0.0, float(1/mpmath.sin(mpmath.pi/3)), 0.01) t = [] for l in numpy.nditer(x): if l < (1 / (2 * mpmath.sin(mpmath.pi/3))): t.append(float(mpmath.tan(mpmath.pi/3) * l)) else: t.append(float(1 - mpmath.tan(mpmath.pi/3) * (l - 1/(2*mpmath.sin(mpmath.pi/3))))) pylab.plot(x, t) pylab.hold(True)
def S_double_hol_conn(x1, x2, t, s, b): v1, v2, vb1, vb2 = v(x1, t, s, b), v(x2, t, s, b), vb(x1, t, s, b), vb(x2, t, s, b) deriv = (pi**(-4)) * Dw(v1, s, b) * (-Dw(-vb1, s, b)) * Dw( v2, s, b) * (-Dw(-vb2, s, b)) if s < 1: conn = (s**2) * sinh(pi * (v1 - v2) / s) * sinh(pi * (vb1 - vb2) / s) else: conn = sin(pi * (v1 - v2)) * sin(pi * (vb1 - vb2)) return re(log(deriv * conn**2)) / 12 - log((x2 - x1)**2) / 6
def getAntiprismVolumeOperator(n, k): result = getProduct([ fdiv( fprod([ n, sqrt(fsub(fmul(4, cos(cos(fdiv(pi, fmul(n, 2))))), 1)), sin(fdiv(fmul(3, pi), fmul(2, n))) ]), fmul(12, sin(sin(fdiv(pi, n))))), sin(fdiv(fmul(3, pi), fmul(2, n))), getPower(k, 3) ]) return result.convert('meter^3')
def FDoubleConn(x1,x2,t,s,b): """ inside of log() for connected HEE. We take single interval subsystem A=[x1,x2]. """ v1 = v(x1,t,s,b) v2 = v(x2,t,s,b) vb1 = vb(x1,t,s,b) vb2 = vb(x2,t,s,b) F = (pi**(-4))*Dw(v1,s,b)*(-Dw(-vb1,s,b))*Dw(v2,s,b)*(-Dw(-vb2,s,b)) if s<1: return F * (s**4)*((sinh(pi*(v1-v2)/s)*sinh(pi*(vb1-vb2)/s))**2) else: return F * (sin(pi*(v1-v2))*sin(pi*(vb1-vb2)))**2
def Diagonalizzazione(I): α = AngoloDiRotazione(I) Iη = I[0] Iξ = I[1] Iηξ = I[2] if α != 0: Iy = Iη * mpmath.cos(α)**2 + Iξ * mpmath.sin( α)**2 - 2 * Iηξ * mpmath.cos(α) * mpmath.sin(α) Iz = Iξ * mpmath.sin(α)**2 + Iξ * mpmath.cos( α)**2 + 2 * Iηξ * mpmath.cos(α) * mpmath.sin(α) J = [Iy, Iz] return J else: return I
def FDoubleDisc(x1,x2,t,s,b): """ inside of log() for disconnected HEE. We take single interval subsystem A=[x1,x2]. This has very complicated minimizasion because the configuration of boundary surface Q varys by Hawking-Page transition. """ v1 = v(x1,t,s,b) v2 = v(x2,t,s,b) vb1 = vb(x1,t,s,b) vb2 = vb(x2,t,s,b) h1 = v1-vb1 hp1 = h1+j*s/2 hm1 = h1-j*s/2 h2 = v2-vb2 hp2 = h2+j*s/2 hm2 = h2-j*s/2 F = (pi**(-4))*Dw(v1,s,b)*(-Dw(-vb1,s,b))*Dw(v2,s,b)*(-Dw(-vb2,s,b)) if s<1: g1 = min([re(sinh(pi*hp1/s)**2),re(sinh(pi*hm1/s)**2)]) g2 = min([re(sinh(pi*hp2/s)**2),re(sinh(pi*hm2/s)**2)]) return F * (s**4)*g1*g2 else: m1 = (sin(pi*hp1)*sin(pi*hp2))**2 m2 = ((sin(pi*hp1)*sin(pi*hm2))**2)*exp(2*pi*s) m3 = ((sin(pi*hm1)*sin(pi*hp2))**2)*exp(2*pi*s) m4 = (sin(pi*hm1)*sin(pi*hm2))**2 return F * min([re(m1),re(m2),re(m3),re(m4)])
def analytical_H2_N2_impedance_Kulikovsky(sigma_e,sigma_p,L_CL,Cdl_vol,frequency): omega = 2*np.pi*frequency k_sigma = sigma_e/(sigma_p+1e-14) Omega_tilde = omega*Cdl_vol*L_CL**2/(sigma_p+1e-14) p0 = cmath.sqrt(-1j*Omega_tilde*(1+1.0/k_sigma)) q0 = cmath.sqrt(-2*k_sigma*(1+k_sigma)*Omega_tilde) tmp1 = complex(mp.fmul(1j*q0,complex(mp.sin(p0)))) tmp2 = complex(mp.fmul((1+k_sigma**2),complex(mp.cos(p0)))) tmp3 = complex(mp.fmul((1j*q0-(1+1j)*p0),complex(mp.sin(p0)))) tmp31 = complex(mp.fadd(2*k_sigma,tmp2)) tmp32 = complex(mp.fmul(1+1j,tmp31)) tmp33 = complex(mp.fmul(k_sigma,tmp3)) tmp4 = complex(mp.fdiv((tmp1+tmp32),(tmp33+1e-14))) Z_Kulikovsky = 1000*L_CL/sigma_p*tmp4 return Z_Kulikovsky
def calculate_coordinates(input_angles): # Constants scalling_const = np.sqrt(.3) f = 195 * scalling_const * math.power(10, -3) t = 375 * scalling_const * math.power(10, -3) coord_list = [] for angle in input_angles: T_1 = angle[0] - np.pi T_2 = angle[1] - np.pi x = float((f * math.cos(T_1) + t * math.cos( (T_1 - T_2))) * math.power(10, 3)) y = float((f * math.sin(T_1) + t * math.sin( (T_1 - T_2))) * math.power(10, 3)) coord_list.append([x, y]) return coord_list
def __ln_expansion(self,u,n_iter = 50): from mpmath import ln, pi, sin, exp, mpc # TODO: test for pathological cases? om1, om3 = self.periods[0]/2, self.periods[1]/2 assert(u.real < 2*om1 and u.real >= 0) assert(u.imag < 2*om3.imag and u.imag >= 0) tau = om3/om1 q = exp(mpc(0,1)*pi()*tau) eta1 = self.zeta(om1) om1_2 = om1 * 2 retval = ln(om1_2/pi()) + eta1*u**2/(om1_2) + ln(sin(pi()*u/(om1_2))) for r in range(1,n_iter + 1): q_2 = q**(2*r) retval += q_2/(r * (1 - q_2))*(2. * sin(r*pi()*u/(om1_2)))**2 return retval
def family_graphical_combination(t, c, angle_alpha_prime): """ Aberdeen family of graphical operators """ if not (isinstance(t, Opinion) and isinstance(c, Opinion) \ and t.check() and c.check()): raise Exception("Two valid Opinions are required!") if mpmath.almosteq(angle_alpha_prime, -mpmath.pi / 3, epsilon): new_magnitude = c.get_magnitude_ratio() * ( mpmath.mpf("2") * t.getUncertainty() / mpmath.sqrt(mpmath.mpf("3"))) #new_magnitude = 0 elif mpmath.almosteq(angle_alpha_prime, mpmath.mpf("2/3") * mpmath.pi, epsilon): new_magnitude = c.get_magnitude_ratio() * ( mpmath.mpf("2") * (mpmath.mpf("1") - t.getUncertainty()) / mpmath.sqrt(mpmath.mpf("3"))) #new_magnitude = 0 elif mpmath.almosteq(angle_alpha_prime, mpmath.mpf("1/2") * mpmath.pi, epsilon): #new_magnitude = 1 - t.getUncertainty() new_magnitude = 2 * t.getBelief() else: new_magnitude = c.get_magnitude_ratio() * (mpmath.mpf("2") * \ (mpmath.sqrt(mpmath.power(mpmath.tan(angle_alpha_prime), mpmath.mpf("2")) +1 ) / ( mpmath.absmax(mpmath.tan(angle_alpha_prime) + mpmath.sqrt(mpmath.mpf("3"))) ) ) * \ t.getBelief()) new_uncertainty = t.getUncertainty( ) + mpmath.sin(angle_alpha_prime) * new_magnitude new_disbelief = t.getDisbelief() + ( t.getUncertainty() - new_uncertainty) * mpmath.cos( mpmath.pi / 3) + mpmath.cos(angle_alpha_prime) * mpmath.sin( mpmath.pi / 3) * new_magnitude if mpmath.almosteq(new_uncertainty, 1, epsilon): new_uncertainty = mpmath.mpf("1") if mpmath.almosteq(new_uncertainty, 0, epsilon): new_uncertainty = mpmath.mpf("0") if mpmath.almosteq(new_disbelief, 1, epsilon): new_disbelief = mpmath.mpf("1") if mpmath.almosteq(new_disbelief, 0, epsilon): new_disbelief = mpmath.mpf("0") return Opinion(1 - new_disbelief - new_uncertainty, new_disbelief, new_uncertainty, "1/2")
def calc_t_r(qr, r1, r2, r3, r4, En, Lz, aa, M=1): """ delta_t_r in Drasco and Hughes (2005) Parameters: qr (float) r1 (float): radial root r2 (float): radial root r3 (float): radial root r4 (float): radial root En (float): energy Lz (float): angular momentum aa (float): spin Keyword Args: M (float): mass Returns: t_r (float) """ pi = mp.pi psi_r = calc_psi_r(qr, r1, r2, r3, r4) kr = ((r1 - r2) * (r3 - r4)) / ((r1 - r3) * (r2 - r4)) rp = M + sqrt(-(aa**2) + M**2) rm = M - sqrt(-(aa**2) + M**2) hr = (r1 - r2) / (r1 - r3) hp = ((r1 - r2) * (r3 - rp)) / ((r1 - r3) * (r2 - rp)) hm = ((r1 - r2) * (r3 - rm)) / ((r1 - r3) * (r2 - rm)) return -((En * ((-4 * (r2 - r3) * (-(((-2 * aa**2 + (4 - (aa * Lz) / En) * rm) * ((qr * ellippi(hm, kr)) / pi - ellippi(hm, psi_r, kr))) / ((r2 - rm) * (r3 - rm))) + ((-2 * aa**2 + (4 - (aa * Lz) / En) * rp) * ((qr * ellippi(hp, kr)) / pi - ellippi(hp, psi_r, kr))) / ((r2 - rp) * (r3 - rp)))) / (-rm + rp) + 4 * (r2 - r3) * ((qr * ellippi(hr, kr)) / pi - ellippi(hr, psi_r, kr)) + (r2 - r3) * (r1 + r2 + r3 + r4) * ((qr * ellippi(hr, kr)) / pi - ellippi(hr, psi_r, kr)) + (r1 - r3) * (r2 - r4) * ((qr * ellipe(kr)) / pi - ellipe(psi_r, kr) + (hr * cos(psi_r) * sin(psi_r) * sqrt(1 - kr * sin(psi_r)**2)) / (1 - hr * sin(psi_r)**2)))) / sqrt( (1 - En**2) * (r1 - r3) * (r2 - r4)))
def get_angle_alpha(self): if (mpmath.almosteq(self.getBelief(), 1, epsilon)): return mpmath.mpf("0") return mpmath.atan( (self.getUncertainty() * mpmath.sin(mpmath.pi / mpmath.mpf("3"))) / (self.getDisbelief() + self.getUncertainty() * mpmath.cos(math.pi / mpmath.mpf("3"))))
def P(self,z): # A+S 18.9. from mpmath import sqrt, mpc, sin, ellipfun, mpf Delta = self.Delta e1, e2, e3 = self.__roots if self.__ng3: z = mpc(0,1) * z if Delta > 0: zs = sqrt(e1 - e3) * z m = (e2 - e3) / (e1 - e3) retval = e3 + (e1 - e3) / ellipfun('sn',u=zs,m=m)**2 elif Delta < 0: H2 = (sqrt((e2 - e3) * (e2 - e1))).real assert(H2 > 0) m = mpf(1) / mpf(2) - 3 * e2 / (4 * H2) zp = 2 * z * sqrt(H2) retval = e2 + H2 * (1 + ellipfun('cn',u=zp,m=m)) / (1 - ellipfun('cn',u=zp,m=m)) else: g2, g3 = self.__invariants if g2 == 0 and g3 == 0: retval = 1 / (z**2) else: c = e1 / 2 retval = -c + 3 * c / (sin(sqrt(3 * c) * z))**2 if self.__ng3: return -retval else: return retval
def ln_expansion2(wp, u, n_iter=25): from mpmath import ln, pi, sin, exp, mpc # TODO: test for pathological cases? om1, om3 = wp.periods[0] / 2, wp.periods[1] / 2 assert (u.real < 2 * om1 and u.real >= 0) assert (abs(u.imag) < 2 * om3.imag) tau = om3 / om1 q = exp(mpc(0, 1) * pi() * tau) eta1 = wp.zeta(om1) om1_2 = om1 * 2 retval = ln(om1_2 / pi()) + eta1 * u**2 / (om1_2) + ln( sin(pi() * u / (om1_2))) for r in range(1, n_iter + 1): q_2 = q**(2 * r) retval += q_2 / (r * (1 - q_2)) * (2. * sin(r * pi() * u / (om1_2)))**2 return retval
def sin(arg): """Sine. This function is a wrapper around a lower level function. If the argument is a standard *float* or *int*, the function from the builtin :mod:`math` module will be used. If the argument is an :mod:`mpmath` float, the corresponding multiprecision function, if available, will be used. Otherwise, the argument is assumed to be a series type and a function from the piranha C++ library is used. :param arg: sine argument :returns: sine of *arg* :raises: :exc:`TypeError` if the type of *arg* is not supported, or any other exception raised by the invoked low-level function >>> from .types import poisson_series, polynomial, rational, short >>> t = poisson_series(polynomial(rational,short))() >>> sin(2 * t('x')) sin(2*x) >>> sin('y') # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TypeError: invalid argument type(s) """ if isinstance(arg,float) or isinstance(arg,int): import math return math.sin(arg) try: from mpmath import mpf, sin if isinstance(arg,mpf): return sin(arg) except ImportError: pass from ._core import _sin return _cpp_type_catcher(_sin,arg)
def test_onaxis_match(self): # set fixed radius self.paramv['R'] = 0.1 groundtruth_levels = self.plotdata['onaxis_db'].tolist() all_obtained_raw = [] for alpha in self.alpha_values: subdf = self.by_alpha.get_group(alpha) this_alpha_set = [] for kaval in tqdm.tqdm(subdf['ka']): self.paramv['alpha'] = np.radians(alpha) self.paramv['a'] = self.paramv['R']*mpmath.sin(self.paramv['alpha']) self.paramv['k'] = kaval/self.paramv['a'] onaxis_value = d_zero(self.paramv['k'], self.paramv['R'], self.paramv['alpha']) this_alpha_set.append(float(np.abs(onaxis_value))) this_alpha_normalised = np.array(this_alpha_set) all_obtained_raw.append(this_alpha_normalised) all_obtained_raw = np.concatenate(all_obtained_raw) all_obtained_db = 20*np.log10(all_obtained_raw) difference = all_obtained_db - groundtruth_levels print(np.max(np.abs(difference))) self.assertTrue(np.max(np.abs(difference))<1)
def __call__(self,t): with mp.extradps(self.prec): t = mpf(t) if t == 0: print "ERROR: Inverse transform can not be calculated for t=0" return ("Error"); N = 2*self.N # Initiate the stepsize (mit aktueller Präsision) h = 2*pi/N # The for loop is evaluating the Laplace inversion at each point theta i # which is based on the trapezoidal rule ans = 0.0 for k in range(self.N): theta = -pi + (k+0.5)*h z = self.shift + N/t*(Talbot.c1*theta/tan(Talbot.c2*theta) - Talbot.c3 + Talbot.c4*theta) dz = N/t * (-Talbot.c1*Talbot.c2*theta/sin(Talbot.c2*theta)**2 + Talbot.c1/tan(Talbot.c2*theta)+Talbot.c4) v1 = exp(z*t)*dz prec = floor(max(log10(abs(v1)),0)) with mp.extradps(prec): value = self.F(z) ans += v1*value return ((h/pi)*ans).imag
def get_ang(pos_1, pos_2, pos_3): mmp.mp.dps = 30 x1, y1, z1 = get_each(pos_1) x2, y2, z2 = get_each(pos_2) x3, y3, z3 = get_each(pos_3) cosb = (x1 * x2 + y1 * y2 + z1 * z2)/(mmp.sqrt(x1**2 + y1**2 + z1**2) * mmp.sqrt(x2**2 + y2**2 + z2**2)) cosc = (x1 * x3 + y1 * y3 + z1 * z3)/(mmp.sqrt(x1**2 + y1**2 + z1**2) * mmp.sqrt(x3**2 + y3**2 + z3**2)) cosa = (x3 * x2 + y3 * y2 + z3 * z2)/(mmp.sqrt(x3**2 + y3**2 + z3**2) * mmp.sqrt(x2**2 + y2**2 + z2**2)) sinb = mmp.sin(mmp.acos(cosb)) sinc = mmp.sin(mmp.acos(cosc)) cosA = (cosa - cosb * cosc) /(sinb * sinc) return mmp.acos(cosA)
def BSLaplace(S,K,T,t,r,sig,N,phi): """Solving the Black Scholes PDE in the Laplace domain""" x = ln(S/K) r = mpf(r);sig = mpf(sig);T = mpf(T);t=mpf(t) S = mpf(S);K = mpf(K);x=mpf(x) mu = r - 0.5*(sig**2) tau = T - t c1 = mpf('0.5017') c2 = mpf('0.6407') c3 = mpf('0.6122') c4 = mpc('0','0.2645') ans = 0.0 h = 2*pi/N h = mpf(h) for k in range(N/2): # Use symmetry theta = -pi + (k+0.5)*h z = N/tau*(c1*theta/tan(c2*theta) - c3 + c4*theta) dz = N/tau*(-c1*c2*theta/(sin(c2*theta)**2) + c1/tan(c2*theta)+c4) eps1 = (-mu + sqrt(mu**2 + 2*(sig**2)*(z+r)))/(sig**2) eps2 = (-mu - sqrt(mu**2 + 2*(sig**2)*(z+r)))/(sig**2) b1 = 1/(eps1-eps2)*(eps2/(z+r) + (1 - eps2)/z) b2 = 1/(eps1-eps2)*(eps1/(z+r) + (1 - eps1)/z) ans += exp(z*tau)*bs(x,b1,b2,eps1,eps2,z,r,phi)*dz val = (K*(h/(2j*pi)*ans)).real return 2*val
def forward(base, humerus, radius, angleL, angleR): E = two * radius * (base + humerus * (mpmath.cos(angleR) - mpmath.cos(angleL))) F = two * humerus * radius * (mpmath.sin(angleR) - mpmath.sin(angleL)) G = base * base + two * humerus * humerus + two * base * humerus * mpmath.cos( angleR) - two * humerus * humerus * mpmath.cos(angleR - angleL) if G - E != 0 and E * E + F * F - G * G > 0: # avoid div by zero, sqrt of negative lumpXminus = (-F - mpmath.sqrt(E * E + F * F - G * G)) / (G - E) lumpYminus = (-F - mpmath.sqrt(E * E + F * F - G * G)) / (G - E) xMinus = base + humerus * mpmath.cos(angleR) + radius * mpmath.cos( two * mpmath.atan(lumpXminus)) yMinus = humerus * mpmath.sin(angleR) + radius * mpmath.sin( two * mpmath.atan(lumpYminus)) return [xMinus, yMinus]
def Pprime(self,z): # A+S 18.9. from mpmath import ellipfun, sqrt, cos, sin, mpc, mpf Delta = self.Delta e1, e2, e3 = self.__roots if self.__ng3: z = mpc(0,1) * z if Delta > 0: zs = sqrt(e1 - e3) * z m = (e2 - e3) / (e1 - e3) retval = -2 * sqrt((e1 - e3)**3) * ellipfun('cn',u=zs,m=m) * ellipfun('dn',u=zs,m=m) / (ellipfun('sn',u=zs,m=m)**3) elif Delta < 0: H2 = (sqrt((e2 - e3) * (e2 - e1))).real assert(H2 > 0) m = mpf(1) / mpf(2) - 3 * e2 / (4 * H2) zp = 2 * z * sqrt(H2) retval = -4 * sqrt(H2**3) * ellipfun('sn',u=zp,m=m) * ellipfun('dn',u=zp,m=m) / ((1 - ellipfun('cn',u=zp,m=m))**2) else: g2, g3 = self.__invariants if g2 == 0 and g3 == 0: retval = -2 / (z**3) else: c = e1 / 2 A = sqrt(3 * c) retval = -6 * c * A * cos(A * z) / (sin(A * z))**3 if self.__ng3: return mpc(0,-1) * retval else: return retval
def rotate_point(x, y, degrees): radians = math.radians(degrees) cos_theta = math.cos(radians) sin_theta = math.sin(radians) return x * cos_theta - y * sin_theta, \ x * sin_theta + y * cos_theta
def sigma(self,z): # A+S 18.10. from mpmath import pi, jtheta, exp, mpc, sqrt, sin Delta = self.Delta e1, _, _ = self.__roots om = self.__periods[0] / 2 omp = self.__periods[1] / 2 if self.__ng3: z = mpc(0,1) * z if Delta > 0: tau = omp / om q = (exp(mpc(0,1) * pi() * tau)).real eta = -(pi()**2 * jtheta(n=1,z=0,q=q,derivative=3)) / (12 * om * jtheta(n=1,z=0,q=q,derivative=1)) v = (pi() * z) / (2 * om) retval = (2 * om) / pi() * exp((eta * z**2)/(2 * om)) * jtheta(n=1,z=v,q=q)/jtheta(n=1,z=0,q=q,derivative=1) elif Delta < 0: om2 = om + omp om2p = omp - om tau2 = om2p / (2 * om2) q = mpc(0,(mpc(0,1) * exp(mpc(0,1) * pi() * tau2)).imag) eta2 = -(pi()**2 * jtheta(n=1,z=0,q=q,derivative=3)) / (12 * om2 * jtheta(n=1,z=0,q=q,derivative=1)) v = (pi() * z) / (2 * om2) retval = (2 * om2) / pi() * exp((eta2 * z**2)/(2 * om2)) * jtheta(n=1,z=v,q=q)/jtheta(n=1,z=0,q=q,derivative=1) else: g2, g3 = self.__invariants if g2 == 0 and g3 == 0: retval = z else: c = e1 / 2 A = sqrt(3 * c) retval = (1 / A) * sin(A*z) * exp((c*z**2) / 2) if self.__ng3: return mpc(0,-1) * retval else: return retval
def __call__(self,t): if t == 0: print("ERROR: Inverse transform can not be calculated for t=0") return ("Error"); # Initiate the stepsize h = 2*pi/self.N ans = 0.0 # parameters from # T. Schmelzer, L.N. Trefethen, SIAM J. Numer. Anal. 45 (2007) 558-571 c1 = mpf('0.5017') c2 = mpf('0.6407') c3 = mpf('0.6122') c4 = mpc('0','0.2645') # The for loop is evaluating the Laplace inversion at each point theta i # which is based on the trapezoidal rule for k in range(self.N): theta = -pi + (k+0.5)*h z = self.shift + self.N/t*(c1*theta/tan(c2*theta) - c3 + c4*theta) dz = self.N/t * (-c1*c2*theta/sin(c2*theta)**2 + c1/tan(c2*theta)+c4) ans += exp(z*t)*self.F(z)*dz return ((h/(2j*pi))*ans).real
def get_angle_beta(self): if mpmath.almosteq(self.getDisbelief(), 1, epsilon): return mpmath.pi / 3 return mpmath.atan( (self.getUncertainty() * mpmath.sin(mpmath.pi / mpmath.mpf("3"))) / (mpmath.mpf("1") - (self.getDisbelief() + self.getUncertainty() * mpmath.cos(mpmath.pi / mpmath.mpf("3")))))
def P(self, z): # A+S 18.9. from mpmath import sqrt, mpc, sin, ellipfun, mpf Delta = self.Delta e1, e2, e3 = self.__roots if self.__ng3: z = mpc(0, 1) * z if Delta > 0: zs = sqrt(e1 - e3) * z m = (e2 - e3) / (e1 - e3) retval = e3 + (e1 - e3) / ellipfun('sn', u=zs, m=m)**2 elif Delta < 0: H2 = (sqrt((e2 - e3) * (e2 - e1))).real assert (H2 > 0) m = mpf(1) / mpf(2) - 3 * e2 / (4 * H2) zp = 2 * z * sqrt(H2) retval = e2 + H2 * (1 + ellipfun('cn', u=zp, m=m)) / ( 1 - ellipfun('cn', u=zp, m=m)) else: g2, g3 = self.__invariants if g2 == 0 and g3 == 0: retval = 1 / (z**2) else: c = e1 / 2 retval = -c + 3 * c / (sin(sqrt(3 * c) * z))**2 if self.__ng3: return -retval else: return retval
def getRadialMatrixElementSemiClassical(self, n, l, s, j, n1, l1, s1, j1): #get the effective principal number of both states nu = n - self.getQuantumDefect(n, l, s, j) nu1 = n1 - self.getQuantumDefect(n1, l1, s1, j1) #get the parameters required to calculate the sum l_c = (l + l1 + 1.) / 2. nu_c = sqrt(nu * nu1) delta_nu = nu - nu1 delta_l = l1 - l gamma = (delta_l * l_c) / nu_c g0 = (1. / (3. * delta_nu)) * (mpmath.angerj(delta_nu - 1., -delta_nu) - mpmath.angerj(delta_nu + 1, -delta_nu)) g1 = -(1. / (3. * delta_nu)) * (mpmath.angerj(delta_nu - 1., -delta_nu) + mpmath.angerj(delta_nu + 1, -delta_nu)) g2 = g0 - mpmath.sin(pi * delta_nu) / (pi * delta_nu) g3 = (delta_nu / 2.) * g0 + g1 radial_ME = (3 / 2) * nu_c**2 * (1 - (l_c / nu_c)**(2))**0.5 * ( g0 + gamma * g1 + gamma**2 * g2 + gamma**3 * g3) return radial_ME
def ln_expansion(wp,u,n_iter = 50): from mpmath import ln, pi, sin, exp, mpc # TODO: test for pathological cases? if wp.periods[1].real == 0: om1, om3 = wp.periods[0]/2, wp.periods[1]/2 else: om1, om3 = wp.periods[1].conjugate()/2, wp.periods[1]/2 tau = om3/om1 q = exp(mpc(0,1)*pi()*tau) eta1 = wp.zeta(om1) om1_2 = om1 * 2 retval = ln(om1_2/pi()) + eta1*u**2/(om1_2) + ln(sin(pi()*u/(om1_2))) for r in range(1,n_iter + 1): q_2 = q**(2*r) retval += q_2/(r * (1 - q_2))*(2. * sin(r*pi()*u/(om1_2)))**2 return retval
def Pprime(self, z): # A+S 18.9. from mpmath import ellipfun, sqrt, cos, sin, mpc, mpf Delta = self.Delta e1, e2, e3 = self.__roots if self.__ng3: z = mpc(0, 1) * z if Delta > 0: zs = sqrt(e1 - e3) * z m = (e2 - e3) / (e1 - e3) retval = -2 * sqrt( (e1 - e3)**3) * ellipfun('cn', u=zs, m=m) * ellipfun( 'dn', u=zs, m=m) / (ellipfun('sn', u=zs, m=m)**3) elif Delta < 0: H2 = (sqrt((e2 - e3) * (e2 - e1))).real assert (H2 > 0) m = mpf(1) / mpf(2) - 3 * e2 / (4 * H2) zp = 2 * z * sqrt(H2) retval = -4 * sqrt(H2**3) * ellipfun('sn', u=zp, m=m) * ellipfun( 'dn', u=zp, m=m) / ((1 - ellipfun('cn', u=zp, m=m))**2) else: g2, g3 = self.__invariants if g2 == 0 and g3 == 0: retval = -2 / (z**3) else: c = e1 / 2 A = sqrt(3 * c) retval = -6 * c * A * cos(A * z) / (sin(A * z))**3 if self.__ng3: return mpc(0, -1) * retval else: return retval
def f1(x): """ An angular integral that appears in electron noise calculation. """ term1 = x * (mp.si(x) - 0.5 * mp.si(2*x)) term2 = -2 * mp.sin(0.5 * x)**4 return (term1 + term2)/x**2
def test_talbot_with_more_complicated(): """test for Talbot numerical inverse Laplace with sin""" a = Talbot(f=f4, n=24, shift=0, dps=None) #single value of t: ok_(mpallclose(a(2, args=(1,)), mpmath.mpf('2.0')*mpmath.sin(mpmath.mpf('2.0'))))
def test_odefun_harmonic(): mp.dps = 15 # Harmonic oscillator f = odefun(lambda x, y: [-y[1], y[0]], 0, [1, 0]) for x in [0, 1, 2.5, 8, 3.7]: # we go back to 3.7 to check caching c, s = f(x) assert c.ae(cos(x)) assert s.ae(sin(x))
def getAntiprismVolume( n, k ): if real( n ) < 3: raise ValueError( 'the number of sides of the prism cannot be less than 3,' ) if not isinstance( k, RPNMeasurement ): return getAntiprismVolume( n, RPNMeasurement( real( k ), 'meter' ) ) if k.getDimensions( ) != { 'length' : 1 }: raise ValueError( '\'antiprism_volume\' argument 2 must be a length' ) result = getProduct( [ fdiv( fprod( [ n, sqrt( fsub( fmul( 4, cos( cos( fdiv( pi, fmul( n, 2 ) ) ) ) ), 1 ) ), sin( fdiv( fmul( 3, pi ), fmul( 2, n ) ) ) ] ), fmul( 12, sin( sin( fdiv( pi, n ) ) ) ) ), sin( fdiv( fmul( 3, pi ), fmul( 2, n ) ) ), getPower( k, 3 ) ] ) return result.convert( 'meter^3' )
def error(coefs, progress=True): (a, b) = coefs xs = (x * mp.pi / mp.mpf(4096) for x in range(-4096, 4097)) err = max(fabs(sin(x) - f(x, a, b)) for x in xs) if progress: print('(a, b, c): ({}, {}, {})'.format(a, b, c(a, b))) print('evaluated error: ', err) print() return float(err)
def sph_yn_exact(n, z): """Return the value of y_n computed using the exact formula. The expression used is http://dlmf.nist.gov/10.49.E4 . """ zm = mpmathify(z) s1 = sum((-1)**k*_a(2*k, n)/zm**(2*k+1) for k in xrange(0, int(n/2) + 1)) s2 = sum((-1)**k*_a(2*k+1, n)/zm**(2*k+2) for k in xrange(0, int((n-1)/2) + 1)) return -cos(zm - n*pi/2)*s1 + sin(zm - n*pi/2)*s2
def rotate(self, identifier, angles, step=1): ang_num = 2*math.pi/360 rotateZ = [math.cos(angles[0]*ang_num),-math.sin(angles[0]*ang_num),0,math.sin(angles[0]*ang_num),math.cos(angles[0]*ang_num),0,0,0,1] rotateY = [math.cos(angles[1]*ang_num),0,-math.sin(angles[1]*ang_num),0,1,0,math.sin(angles[1]*ang_num),0,math.cos(angles[1]*ang_num)] rotateX = [1,0,0,0,math.cos(angles[2]*ang_num),-math.sin(angles[2]*ang_num),0,math.sin(angles[2]*ang_num),math.cos(angles[2]*ang_num)] antirotateZ = [math.cos(-angles[0]*ang_num),-math.sin(-angles[0]*ang_num),0,math.sin(-angles[0]*ang_num),math.cos(-angles[0]*ang_num),0,0,0,1] antirotateY = [math.cos(-angles[1]*ang_num),0,-math.sin(-angles[1]*ang_num),0,1,0,math.sin(-angles[1]*ang_num),0,math.cos(-angles[1]*ang_num)] antirotateX = [1,0,0,0,math.cos(-angles[2]*ang_num),-math.sin(-angles[2]*ang_num),0,math.sin(-angles[2]*ang_num),math.cos(-angles[2]*ang_num)] #self.command("transform "+identifier+""+"{ {%s %s %s} {%s %s %s} {%s %s %s} }"%tuple(rotateZ)) self.command("transform "+identifier+"."+str(step+1)+"{ {%s %s %s} {%s %s %s} {%s %s %s} }"%tuple(antirotateZ)) #self.command("transform "+identifier+""+"{ {%s %s %s} {%s %s %s} {%s %s %s} }"%tuple(rotateY)) self.command("transform "+identifier+"."+str(step+1)+"{ {%s %s %s} {%s %s %s} {%s %s %s} }"%tuple(antirotateY)) #self.command("transform "+identifier+""+"{ {%s %s %s} {%s %s %s} {%s %s %s} }"%tuple(rotateX)) self.command("transform "+identifier+"."+str(step+1)+"{ {%s %s %s} {%s %s %s} {%s %s %s} }"%tuple(antirotateX)) for i in range(0,3): self.orientation[i] += angles[i]
def __init__(self, resource_handler, voxel_handler, world_dimensions = (64, 64, 16), voxel_dimensions = (72, 36, 36), active_layer = 0, visibility_flag = ONLY_SHOW_EXPOSED): self._world_dimensions = world_dimensions self._voxel_dimensions = voxel_dimensions grid_length = world_dimensions[WIDTH] * world_dimensions[HEIGHT] * world_dimensions[DEPTH] self._active_layer = active_layer self.visibility_flag = visibility_flag #The unprojected length of the horizontal side of each voxel self._side_length = mp.nint(self._voxel_dimensions[WIDTH] * mp.sin(mp.pi / 4)) WorldBase.__init__(self, resource_handler, voxel_handler, grid_length, (0, 0))
def Hypergeometric1F1(a,b,t,N): # Initiate the stepsize h = 2*pi/N; c1 = mpf('0.5017') c2 = mpf('0.6407') c3 = mpf('0.6122') c4 = mpc('0','0.2645') # The for loop is evaluating the Laplace inversion at each point theta # which is based on the trapezoidal rule ans = 0.0 for k in range(N): theta = -pi + (k+0.5)*h z = N/t*(c1*theta/tan(c2*theta) - c3 + c4*theta) dz = N/t*(-c1*c2*theta/sin(c2*theta)**2 + c1/tan(c2*theta)+c4) ans += exp(z*t)*F(a,b,t,z)*dz return gamma(b)*t**(1-b)*exp(t)*((h/(2j*pi))*ans)
def g(theta,phi): R = abs(re(spherharm(l,m,theta,phi))) x = R*cos(phi)*sin(theta) y = R*sin(phi)*sin(theta) z = R*cos(theta) return [x,y,z]
from pylab import * import mpmath mpmath.mp.dps = 50 # higher precision for demonstration #Nv=100000 Nv=100000 a = [mpmath.sin(2.*mpmath.pi*n/Nv) for n in range(Nv)] b = array(a) print b.dot(b) - Nv/2 b32= array(a,dtype=float32) b64= array(a,dtype=float64) b128= array(a,dtype=float128) print b32.dot(b32) - Nv/2. print b64.dot(b64) - Nv/2. print b128.dot(b128) - Nv/2. print print mpmath.norm(b) - mpmath.sqrt(Nv/2) print norm(b32) - sqrt(Nv/2) print norm(b64) - sqrt(Nv/2) print norm(b128) -sqrt(Nv/2)
def agnesi(x): return dtheta/((x/aa)**2+r1)*mpm.sin(l*z)
def sin(op): op = convertToRadians(op) return mpmath.sin(op)
def ftot(t): return mp.cos(mp.cos(t)) * mp.sin(t) * mp.exp(1j * omega * mp.sin(t))
TEST_YELLOW = pygame.Color(255, 0, 255, 255)#-16711681 TEST_BLUE = pygame.Color(0, 0, 255, 255)#-65536 #Visibility flags SHOW_ALL = 0 ONLY_SHOW_EXPOSED = 1 #135 degrees THETA = 3 * mp.pi / 4 #Isometric Unprojection UNPROJECT = mp.matrix([[1, 0, 0], [0, -1, 0], #NOTE: the y coordinate has to be inverted because my [0, 0, 1]]) #grid coordinates are a bit weird UNPROJECT *= mp.matrix([[ mp.cos(THETA), mp.sin(THETA), 0], [-mp.sin(THETA), mp.cos(THETA), 0], [ 0, 0, 1]]) UNPROJECT *= mp.matrix([[1, 0, 0], [0, 2, 0], [0, 0, 1]]) class OutOfIt(Exception): def __init__(self, msg, value): self.msg = msg self.value = value def __repr__(self):
def eval(self, z): return mpmath.sin(z)
def g(theta,phi): R = abs(re(a*spherharm(l,m1,theta,phi)+b*spherharm(l,m2,theta,phi)))**2 x = R*cos(phi)*sin(theta) y = R*sin(phi)*sin(theta) z = R*cos(theta) return [x,y,z]
def ExactIntegrationOfSinusKernel(t, a = None, b = None): with precision(300): if a == None and b == None: return 0.5 * math.pi * math.sqrt(t) * (mpmath.angerj(0.5, t) - mpmath.angerj(-0.5, t)) if a == None and b != None: a = t elif b == None: b = 0. mpmath.mp.pretty = True pi = mpmath.mp.pi pi = +pi fcos = mpmath.fresnelc fsin = mpmath.fresnels arg_a = mpmath.sqrt(2 * (t - a) / mpmath.mp.pi) arg_b = mpmath.sqrt(2 * (t - b) / mpmath.mp.pi) return mpmath.sqrt(2 * mpmath.mp.pi) * ((fsin(arg_b) - fsin(arg_a)) * mpmath.cos(t) + (fcos(arg_a) - fcos(arg_b)) * mpmath.sin(t))
def cart_state(self,tau): from mpmath import cos, sin xi,eta,phi = self.state(tau) return xi*eta*cos(phi),xi*eta*sin(phi),(xi**2 - eta**2)/2
def solveCubicPolynomial( a, b, c, d ): if mp.dps < 50: mp.dps = 50 if a == 0: return solveQuadraticPolynomial( b, c, d ) f = fdiv( fsub( fdiv( fmul( 3, c ), a ), fdiv( power( b, 2 ), power( a, 2 ) ) ), 3 ) g = fdiv( fadd( fsub( fdiv( fmul( 2, power( b, 3 ) ), power( a, 3 ) ), fdiv( fprod( [ 9, b, c ] ), power( a, 2 ) ) ), fdiv( fmul( 27, d ), a ) ), 27 ) h = fadd( fdiv( power( g, 2 ), 4 ), fdiv( power( f, 3 ), 27 ) ) # all three roots are the same if h == 0: x1 = fneg( root( fdiv( d, a ), 3 ) ) x2 = x1 x3 = x2 # two imaginary and one real root elif h > 0: r = fadd( fneg( fdiv( g, 2 ) ), sqrt( h ) ) if r < 0: s = fneg( root( fneg( r ), 3 ) ) else: s = root( r, 3 ) t = fsub( fneg( fdiv( g, 2 ) ), sqrt( h ) ) if t < 0: u = fneg( root( fneg( t ), 3 ) ) else: u = root( t, 3 ) x1 = fsub( fadd( s, u ), fdiv( b, fmul( 3, a ) ) ) real = fsub( fdiv( fneg( fadd( s, u ) ), 2 ), fdiv( b, fmul( 3, a ) ) ) imaginary = fdiv( fmul( fsub( s, u ), sqrt( 3 ) ), 2 ) x2 = mpc( real, imaginary ) x3 = mpc( real, fneg( imaginary ) ) # all real roots else: j = sqrt( fsub( fdiv( power( g, 2 ), 4 ), h ) ) k = acos( fneg( fdiv( g, fmul( 2, j ) ) ) ) if j < 0: l = fneg( root( fneg( j ), 3 ) ) else: l = root( j, 3 ) m = cos( fdiv( k, 3 ) ) n = fmul( sqrt( 3 ), sin( fdiv( k, 3 ) ) ) p = fneg( fdiv( b, fmul( 3, a ) ) ) x1 = fsub( fmul( fmul( 2, l ), cos( fdiv( k, 3 ) ) ), fdiv( b, fmul( 3, a ) ) ) x2 = fadd( fmul( fneg( l ), fadd( m, n ) ), p ) x3 = fadd( fmul( fneg( l ), fsub( m, n ) ), p ) return [ chop( x1 ), chop( x2 ), chop( x3 ) ]