def ecuaciones(self, t, x, *args, **kwargs): V = self.V I = self.I R = self.R ws = self.ws dx = self.dx # Calculo de theta thetar = x[-1] wr = x[-2] # Se evalua la referencia angular theta = eval(self.theta) wref = eval(self.wref) # Corrientes de dq0 I = self.Linv * x[:self.nx] # Para eléctrico self.te = (x[0] * I[1] - x[1] * I[0]) # Inductancias de voltajes rotacionales G = matrix([-wref*x[1], wref*x[0], 0, -(wref-wr)*x[4], (wref-wr)*x[3], 0]) # Voltajes en ABC Va = self.VA * sin(self.ws*t).real Vb = self.VB * sin(self.ws*t - 2*pi/3).real Vc = self.VC * sin(self.ws*t + 2*pi/3).real # Voltajes en dq0 V[:3] = self.transformada_park(theta, matrix([Va, Vb, Vc])) # Evaluación de las ED dx[0:self.nx] = (V - R * I - G) * ws dx[-2] = (self.te - self.tm) / (2*self.H) dx[-1] = x[6]*ws return dx
def transformada_park(self, theta, Vabc): C = raiz2_3 * matrix([[cos(theta).real, cos(theta - defase).real, cos(theta + defase).real],\ [-sin(theta).real, -sin(theta - defase).real, -sin(theta + defase).real],\ [raiz1_2, raiz1_2, raiz1_2]]) return C.T * Vabc
def test_sin(self): self.assertAlmostEqual(qmath.sin(self.f1), math.sin(self.f1)) self.assertAlmostEqual(qmath.sin(self.c1), cmath.sin(self.c1)) self.assertAlmostEqual(qmath.sin(self.c2), cmath.sin(self.c2)) self.assertAlmostEqual(qmath.sin(Quat(self.f1)), math.sin(self.f1)) self.assertAlmostEqual(qmath.sin(Quat(0, 3)), cmath.sin(3J)) self.assertAlmostEqual(qmath.sin(Quat(4, 5)), cmath.sin(4 + 5J)) self.assertAlmostEqual(qmath.sin(Quat(0, self.f1)), Quat(0, math.sinh(self.f1)))
def test_trig_basic(): for x in (range(100) + range(-100,0)): t = x / 4.1 assert cos(Float(t)).ae(math.cos(t)) assert sin(Float(t)).ae(math.sin(t)) assert tan(Float(t)).ae(math.tan(t)) assert sin(1+1j).ae(cmath.sin(1+1j)) assert sin(-4-3.6j).ae(cmath.sin(-4-3.6j))
def limit_term(ky): if s == 0: N_ab = E elif (s == 1) or (s == -1): N_ab = t2 else: print 'Sublattice error in gRib_Arm' return 2.0*N_ab*sin(ky*(m2-n2))*sin(ky*(m1-n1))/( nE*( E**2 - t2**2 ) )
def sin(c): """ sin(a+x)= sin(a) cos(x) + cos(a) sin(x) """ if not isinstance(c,pol): return math.sin(c) a0,p=c.separate(); lst=[math.sin(a0),math.cos(a0)] for n in range(2,c.order+1): lst.append( -lst[-2]/n/(n-1)) return phorner(lst,p)
def p1(x): a = 1.0/2*pi*sqrt(x[1])/x[0] b = x[2]*cos(x[4]) + x[3]*sin(x[4]) c = x[3]*sin(x[4]) - x[2]*cos(x[4]) d = x[0]*abs(sin(x[4])) e = pi*acos(exp(-d)) f = a/b/e g = f/(x[1] + f) h = c/g - b/f return h
def bearing_to(self, point): lat1 = to_rad(self.lat) lat2 = to_rad(point.lat) dLng = to_rad(point.lng - self.lng) y = cmath.sin(dLng) * cmath.cos(lat2) x = cmath.cos(lat1) * cmath.sin(lat2) \ - cmath.sin(lat1) * cmath.cos(lat2) * cmath.cos(dLng) brng = math.atan2(y.real, x.real) return (to_deg(brng.real)+360) % 360
def _cospi_complex(z): if z.real < 0: z = -z n, r = divmod(z.real, 0.5) z = pi*complex(r, z.imag) n %= 4 if n == 0: return cmath.cos(z) if n == 1: return -cmath.sin(z) if n == 2: return -cmath.cos(z) if n == 3: return cmath.sin(z)
def _n_Ztotal(self, Omega, j0, c10): fc = self.fc z_step = 1.0/self.channels phi = [-j - 1j*Omega for j in j0] psi = cmath.sqrt(-1j*Omega/fc.express["nD_d"]) nlJfix = fc.express["lJfix"]/fc.express["j_ref"] lbmupsi = self.fc.express["nl_d"]*self.fc.express["mu"]*psi sqrtphi = [cmath.sqrt(phii) for phii in phi] sinsqrtphi = [cmath.sin(s) for s in sqrtphi] sinlbmupsi = cmath.sin(lbmupsi) coslbmupsi = cmath.cos(lbmupsi) tanlbmupsi = cmath.tan(lbmupsi) y_v = [0.0]*(self.channels + 1) def function_rhs_ch(k): # all expressions below found in maxima: ABcommon = fc.express["nD_d"]*fc.express["mu"]*sinsqrtphi[k]*sqrtphi[k]*psi/(j0[k]*sinsqrtphi[k]*sqrtphi[k]*sinlbmupsi + c10[k]*fc.express["nD_d"]*fc.express["mu"]*phi[k]*psi*coslbmupsi) A = c10[k]*phi[k]*ABcommon B = -j0[k]*ABcommon/coslbmupsi+fc.express["nD_d"]*fc.express["mu"]*psi*tanlbmupsi return (A/nlJfix, (B - 1j*fc.express["xi2epsilon2"]*Omega)/nlJfix) c11peta = [0.0]*(self.channels + 1) # TODO: upload maxima script # found in maxima: c11peta[0] = (sinsqrtphi[0]*sqrtphi[0]*c10[0]*phi[0])/(j0[0]*sinsqrtphi[0]*sqrtphi[0] + c10[0]*fc.express["nD_d"]*fc.express["mu"]*phi[0]*psi/tanlbmupsi) Zloc = [0.0]*(self.channels + 1) # found in maxima: denominator = sinsqrtphi[0]*sqrtphi[0]*((c10[0]*phi[0])/(c11peta[0]*j0[0]) - 1.0) if denominator == 0.0: denominator = eff_zero Zloc[0] = -1.0 / denominator + self._n_Zccl(j0[0], sqrtphi[0]) invZtotal = 1.0/Zloc[0] for i in xrange(1, self.channels + 1): if self.num_method == 1: # Runge--Kutta method y_v[i] = RK_step(function_rhs_ch, (i-1)*2, y_v[i-1], z_step) ii = i*2 else: # finite-difference method coef = function_rhs_ch(i) y_v[i] = (y_v[i-1] + coef[0]*z_step)/(1.0 - z_step*coef[1]) ii = i # all expressions below found in maxima: c11peta[i] = y_v[i]/coslbmupsi - (sinsqrtphi[ii]*sqrtphi[ii]*(y_v[i]*j0[ii]/coslbmupsi - c10[ii]*phi[ii]))/(j0[ii]*sinsqrtphi[ii]*sqrtphi[ii] + c10[ii]*fc.express["nD_d"]*fc.express["mu"]*phi[ii]*psi/tanlbmupsi) denominator = sinsqrtphi[ii]*sqrtphi[ii]*((c10[ii]*phi[ii])/(c11peta[i]*j0[ii]) - 1.0) if denominator == 0.0: denominator = eff_zero Zloc[i] = -1.0 / denominator + self._n_Zccl(j0[ii], sqrtphi[ii]) invZtotal += 1.0/Zloc[i] invZtotal = invZtotal*z_step - (1.0/Zloc[0]+1.0/Zloc[-1])*z_step/2.0 self.y_v = y_v self.Zloc_v = Zloc return 1.0/invZtotal
def oneArgFuncEval(function, value): # Evaluates functions that take a complex number input if function == "sin": return cmath.sin(value) elif function == "cos": return cmath.cos(value) elif function == "tan": return cmath.tan(value) elif function == "asin": return cmath.asin(value) elif function == "acos": return cmath.acos(value) elif function == "atan": return cmath.atan(value) elif function == "csc": return 1.0 / cmath.sin(value) elif function == "sec": return 1.0 / cmath.cos(value) elif function == "cot": return 1.0 / cmath.tan(value) elif function == "ln": return cmath.log(value) elif function == "sqr": return cmath.sqrt(value) elif function == "abs": return cmath.sqrt((value.real ** 2) + (value.imag ** 2)) elif function == "exp": return cmath.exp(value) if function == "sinh": return cmath.sinh(value) elif function == "cosh": return cmath.cosh(value) elif function == "tanh": return cmath.tanh(value) elif function == "asinh": return cmath.asinh(value) elif function == "acosh": return cmath.acosh(value) elif function == "atanh": return cmath.atanh(value) elif function == "ceil": return math.ceil(value.real) + complex(0, 1) * math.ceil(value.imag) elif function == "floor": return math.floor(value.real) + complex(0, 1) * math.floor(value.imag) elif function == "trunc": return math.trunc(value.real) + complex(0, 1) * math.trunc(value.imag) elif function == "fac": if value.imag == 0 and value < 0 and value.real == int(value.real): return "Error: The factorial function is not defined on the negative integers." return gamma(value + 1) elif function == "log": return cmath.log10(value)
def getDist(lat1,long1,lat2,long2): """ Calc the distance between 2 points using Vincenty """ lat1 = math.radians(lat1) long1 = math.radians(long1) lat2 = math.radians(lat2) long2 = math.radians(long2) R = 6371 # km d = cmath.acos(cmath.sin(lat1) * cmath.sin(lat2) + \ cmath.cos(lat1) * cmath.cos(lat2) * cmath.cos(long2 - long1)) * R return abs(d) # cast to float
def test_trig_hyperb_basic(): for x in (list(range(100)) + list(range(-100,0))): t = x / 4.1 assert cos(mpf(t)).ae(math.cos(t)) assert sin(mpf(t)).ae(math.sin(t)) assert tan(mpf(t)).ae(math.tan(t)) assert cosh(mpf(t)).ae(math.cosh(t)) assert sinh(mpf(t)).ae(math.sinh(t)) assert tanh(mpf(t)).ae(math.tanh(t)) assert sin(1+1j).ae(cmath.sin(1+1j)) assert sin(-4-3.6j).ae(cmath.sin(-4-3.6j)) assert cos(1+1j).ae(cmath.cos(1+1j)) assert cos(-4-3.6j).ae(cmath.cos(-4-3.6j))
def distance_to(self, point): lat1 = to_rad(self.lat) lng1 = to_rad(self.lng) lat2 = to_rad(point.lat) lng2 = to_rad(point.lng) dLat = lat2 - lat1 dlng = lng2 - lng1 a = cmath.sin(dLat/2.0) * cmath.sin(dLat/2.0) \ + cmath.cos(lat1) * cmath.cos(lat2) \ * cmath.sin(dlng/2) * cmath.sin(dlng/2) c = 2 * math.atan2(cmath.sqrt(a).real, cmath.sqrt(1-a).real); d = self.R * c; return d.real
def filter_func(k): import cmath temp = 0.25 * (4 - cfl**2 + cfl**2 * cmath.cos(2 * k * dx)) - 1j * cfl * cmath.sin(k * dx) return temp**(t * v / (cfl * dx))
def pixelToMillimeterConversion(self, coord, roe): fieldOfView = roe.getFieldOfView() distance = roe.getDistance() height, width, _ = roe.getImage().shape imageHeigth = height imageWidth = width # calculate length of diagonal of image in mm diagonalMillimeter = float(distance) * math.tan((fieldOfView / 2) * (math.pi / 180)) * 2 # calculate angle of diagonal theta = math.atan(imageHeigth / imageWidth) # calculate width of image in milimeter imageWidthMillimeter = math.cos(theta) * diagonalMillimeter # calculate heigth of image in millimeter imageHeigthInMillimeter = math.sin(theta) * diagonalMillimeter # calculate the size of a pixel in x directon in mm pixelSizeDirX = imageHeigthInMillimeter / imageHeigth # calculate the size of a pixel in y directon in mm pixelSizeDirY = imageWidthMillimeter / imageWidth xPositionMillimeter = coord.getxCoor() * pixelSizeDirX yPositionMillimeter = coord.getyCoor() * pixelSizeDirY millimeterCoordinate = coordinate(int(round(xPositionMillimeter.real, 2)), int(round(yPositionMillimeter.real, 2))) roe.addRoePositionMillimeter(millimeterCoordinate)
def PitchResponseDueToElevator(self, de, T, ElevatorName): """ Returns the normalized change in alpha due to a step input of the elevator. Eq. 4.45, pg. 141 """ PPa = self.PitchPhaseAng() PF = self.PitchFreq() PD = self.PitchDamp() # PD = 0.5 # PF = 8.98/SEC # PPa = math.atan(math.sqrt(1 - PD**2)/ PD) # Split the equation for aesthetic purposes dA = [] for t in T: Num = math.e**( -PD * PF * t ) Denom = math.sqrt(1. - PD**2) Angle = math.sqrt(1. - PD**2) * PF * t + PPa SinA = math.sin(Angle) dA.append( max(0, (1. - Num / Denom * SinA).real) ) if len(dA)==1: return dA[0] else: return npy.array(dA)
def LWTDWS(alpha, c, cg, c0, H): alpha0 = None H0 = None errorMsg = None deg2rad = math.pi / 180.0 arg = (c0 / c) * cmath.sin(alpha * deg2rad) if ComplexUtil.greaterThanEqual(arg, 1): errorMsg = "Error: Violation of assumptions for Snells Law" return alpha0, H0, errorMsg alpha0 = (cmath.asin(arg)) / deg2rad ksf = cmath.sqrt(c0 / (2 * cg)) # shoaling coefficient alphaCos = cmath.cos(alpha0 * deg2rad) / cmath.cos(alpha * deg2rad) if ComplexUtil.lessThan(alphaCos, 0): errorMsg = "Error: Alpha1 data out of range" return alpha0, H0, errorMsg krf = cmath.sqrt(alphaCos) # refraction coefficient H0 = H / (ksf * krf) return alpha0, H0, errorMsg
def examples(): y = complex(2, 3) print("real part: ", y.real) print("imag part: ", y.imag) print("Squar: ", pow(y, 2)) print("Distance: ", abs(y)) print("cmath sin: ", cmath.sin(y))
def __init__(self, *args, **kwargs): if len(args) is 2: self._data = complex(*args) return if len(args) is 1: if isinstance(args[0], (self.__class__, gms.Vector)): self._data = complex(args[0].x, args[0].y) return if isinstance(args[0], complex): self._data = complex(args[0]) return if isinstance(args[0], list): self.__class__.__init__(self, *args[0]) return if len(args) is 0: if set(kwargs.keys()) == set(("x", "y")): self.__class__.__init__(self, kwargs["x"], kwargs["y"]) return if set(kwargs.keys()) == set(("magnitude", "angle")): self.__class__.__init__( self, kwargs["magnitude"] * cm.cos(kwargs["angle"]), kwargs["magnitude"] * cm.sin(kwargs["angle"])) return if len(kwargs) is 0: self.__class__.__init__(self, 0.0, 0.0) return raise ValueError
def _Y_1(k, theta, phi): if k == 0: return cmath.cos(theta) if abs(k) == 1: return -1.0 * cmath.sqrt(0.5) * cmath.sin(theta) * cmath.exp(k * 1.j * phi) else: raise RuntimeError('bad k value')
def complexmath(self): a = complex(2,4) b = 3 - 5j import cmath print( cmath.sin(a)) print( cmath.cos(b))
def _internal_compute(a, dir): global iteration_count N = len(a) if N == 1: return a a_even = [] a_odd = [] i=0 for element in a: if i % 2 == 0: a_even.append(element) else: a_odd.append(element) i += 1 b_even = _internal_compute(a_even, dir) b_odd = _internal_compute(a_odd, dir) out_vector = list( range(0, N ) ) #initialization Wn = cmath.cos( cmath.pi*2/N ) + dir*1j*cmath.sin( cmath.pi*2/N ) W=1 for m in range(0, int(N/2)): iteration_count+=1 out_vector[m]= b_even[m] + W*b_odd[m] out_vector[m+int(N/2)] = b_even[m]-W*b_odd[m] W = W*Wn return out_vector
def reflection_coef(eps1, eps2, theta, polarz): """ :param eps1: permittivity in medium 1 :param eps2: permittivity in medium 2 :param theta: angle between incident wave and normal to surface in degrees :param polarz: polarization of the wave :return: reflection coefficient """ eps_r = eps2 / eps1 theta = theta * cm.pi / 180 if polarz.upper() == 'H': return (cm.cos(theta) - cm.sqrt(eps_r - cm.sin(theta)**2)) / ( cm.cos(theta) + cm.sqrt(eps_r - cm.sin(theta)**2)) else: return -(cm.sqrt(eps_r - cm.sin(theta)**2) - eps_r * cm.cos(theta)) / ( cm.sqrt(eps_r - cm.sin(theta)**2) + eps_r * cm.cos(theta))
def __test1__(): n = 10 xs = [sin(j) for j in xrange(n)] Xs = dft(xs) xs2 = idft(Xs) for j in xrange(n): assert __dist__(xs[j]-xs2[j], 0)<.0001
def fractalTree(iterations, origin, trunkLength, reductionFactor, theta, dtheta): if iterations == 0: return x0, y0 = origin x, y = x0 + trunkLength * cos(theta), y0 - trunkLength * sin(theta) strokeColor = getColor(iterations) turtle.penup() turtle.setposition(-x0, -y0) turtle.pendown() turtle.color(strokeColor) turtle.pendown() turtle.goto(-x.real, -y.real) turtle.penup() previousPosition = (x0, y0) fractalTree(iterations - 1, (x.real, y.real), trunkLength * reductionFactor, reductionFactor, theta + dtheta, dtheta) # turtle.penup() # turtle.setposition(previousPosition) # turtle.pendown() fractalTree(iterations - 1, (x.real, y.real), trunkLength * reductionFactor, reductionFactor, theta - dtheta, dtheta)
def fresnel2(t0, N0, N1, deg=False): """ Calculate the Fresnel coefficients for an interface. Arguments: t0: incident angle (in radians or degrees if deg=True) N0: complex refraction index of the incident medium (n+ik) N1: complex refraction index of the second medium (n+ik) deg: flag controlling the incidence angle units Return rp, rs, tp, ts for the p and s polarizations. """ if deg == True: t0 = t0 * m.pi / 180. ct0 = cm.cos(t0) st0 = cm.sin(t0) st1 = N0 / N1 * st0 ct1 = cm.sqrt(1 - st1 * st1) rp = (N1 * ct0 - N0 * ct1) / (N1 * ct0 + N0 * ct1) rs = (N0 * ct0 - N1 * ct1) / (N0 * ct0 + N1 * ct1) tp = (2. * N0 * ct0) / (N1 * ct0 + N0 * ct1) ts = (2. * N0 * ct0) / (N0 * ct0 + N1 * ct1) return rp, rs, tp, ts
def U_gate(theta, phi, lamda, dtype=complex, sparse=False): r"""Arbitrary unitary single qubit gate. .. math:: U_3(\theta, \phi, \lambda) = \begin{bmatrix} \cos(\theta / 2) & - e^{i \lambda} \sin(\theta / 2) \\ e^{i \phi} \sin(\theta / 2) & e^{i(\lambda + \phi)}\cos(\theta / 2) \end{bmatrix} Parameters ---------- theta : float Angle between 0 and pi. phi : float Angle between 0 and 2 pi. lamba : float Angle between 0 and 2 pi. Returns ------- U : (2, 2) array The unitary matrix, cached. """ from cmath import cos, sin, exp c2, s2 = cos(theta / 2), sin(theta / 2) U = qu( [[c2, -exp(1j * lamda) * s2], [exp(1j * phi) * s2, exp(1j * (lamda + phi)) * c2]], dtype=dtype, sparse=sparse ) make_immutable(U) return U
def computeOmegas(self, n): self.V = [] self.Vin = [] for i in range(n): value = complex(cmath.cos(2j*math.pi/n), cmath.sin(2j*math.pi/n)) self.V.append(value) self.Vin.append(1/value)
def sin_iteration(z): for i in range(bailout): if abs(z.imag) > 50.0: break else: z = c*sin(z) return i
def multilayer(wavelength, theta, epsilon, thickness, polarisation): Nlay = len(epsilon) k0 = 2 * np.pi / wavelength n1 = cmath.sqrt(epsilon[0]) k1 = n1 * k0 k_x = k1 * cmath.sin(theta) k = [cmath.sqrt(epsi) * k0 for epsi in epsilon] kz = [cmath.sqrt(ki**2 - k_x**2) for ki in k] ## calculate the transition matrix M M11 = M22 = 1.0 + 0j M21 = M12 = 0.0 + 0j Mi11 = Mi12 = Mi21 = Mi22 = 1 + 0j # empty 2x2 complex matrix M = np.zeros([2, 2]) + 0j M_tmp = np.zeros([2, 2]) + 0j for il in range(Nlay - 1): if polarisation == 'p': Ki = (epsilon[il] / epsilon[il + 1]) * (kz[il + 1] / kz[il]) elif polarisation == 's': Ki = kz[il + 1] / kz[il] phasei = np.exp(1j * thickness[il] * kz[il]) Mi11 = 0.5 * (1 + Ki) / phasei Mi21 = 0.5 * (1 - Ki) * phasei Mi12 = 0.5 * (1 - Ki) / phasei Mi22 = 0.5 * (1 + Ki) * phasei M_tmp[0, 0] = 0.5 * (1 + Ki) / phasei M_tmp[1, 0] = 0.5 * (1 - Ki) * phasei M_tmp[0, 1] = 0.5 * (1 - Ki) / phasei M_tmp[1, 1] = 0.5 * (1 + Ki) * phasei M = M * M_tmp M11new = M11 * Mi11 + M12 * Mi21 M21new = M21 * Mi11 + M22 * Mi21 M12new = M11 * Mi12 + M12 * Mi22 M22new = M21 * Mi12 + M22 * Mi22 M11 = M11new M12 = M12new M21 = M21new M22 = M22new t = 1 / M11 r = M21 * t R = abs(r)**2 T = 1 - R return (R, T)
def LiveLaunch_V_LO(self, Result='v', History=False): """ Computes the takeoff velocity with the live engine """ if self.dirty: self.Refresh() angle = self.Bungee_Alpha x = self.Bungee_X Weight = self.TotalWeight m = Weight / gacc Fg = Weight * math.sin(self.Bungee_Alpha / RAD).real A_GR = self.param.A_GR def ODE(x, V): return (self.BungeeForce(x) + self.Thrust(V) - self.AerodynamicDrag(V, Alpha2d=A_GR) - self.RollingDrag(V, Alpha2d=A_GR) - Fg) / m int_ts, y1, y1d, y1dd = IntegrateDistanceODE(x, ODE, History) ret = [] if 'x' in Result: ret.append(self.ToUnumList(y1, M)) if 'v' in Result: ret.append(self.ToUnumList(y1d, M / SEC)) if 'a' in Result: ret.append(self.ToUnumList(y1dd, M / SEC**2)) return ret[0] if len(ret) == 1 else ret
def generate_sinusoidal_wave(frequency, phase, amplitude, sample_rate, duration): output = [] for i in range(duration * sample_rate): t = i / sample_rate angle = frequency * 2 * cmath.pi * t + phase output.append((amplitude * cmath.sin(angle)).real) return output
def unblurImage_Weiner_AND_Inverse(array, height, width, T, a, b, IorW, K): for i in range(width): for j in range(height): u = (i - (width // 2)) # Center u v = (j - (height // 2)) # Center v blur = cmath.pi * ( (u * a) + (v * b) + 0.00001 ) # Calculate blur using a = b linear uniform motion H = (T / (blur)) * cmath.sin(blur) * cmath.e**(-(cmath.sqrt(-1)) * blur) Hr = np.real(H) # Butterworth Lowpass Filter radius = 256 magnitude = 10 distanceToCenter = math.sqrt((i - (width // 2))**2 + (j - (height // 2))**2) B = 1 / (1 + (distanceToCenter / radius)**(2 * magnitude)) #Inverse Unblur with Butterworth lowpass filter radius if (IorW): array[i][j] = array[i][j] / H * B #Weiner else: array[i][j] = (((1 / H) * ((abs(H * np.conj(H))) / (abs(H * np.conj(H)) + K))) * array[i][j]) return array
def gamma(z): """ Gamma function: Lanczos approximation implementation.e Numerical Recipes in C (2nd ed. Cambridge University Press 1992) """ g = 5 p0 = float(1.000000000190015) p1 = float(76.18009172947146) p2 = float(-86.50532032941677) p3 = float(24.01409824083091) p4 = float(-1.231739572450155) p5 = float(1.208650973866179e-3) p6 = float(-5.395239384953e-6) coefs = [p0, p1, p2, p3, p4, p5, p6] z = complex(z) if z.real < 0.5: #Recursion method: reflection formula return cmath.pi / (cmath.sin(cmath.pi * z) * gamma(1 - z)) else: ax_1 = cmath.sqrt(cmath.pi * 2) / z ax2_sum = coefs[0] for i in range(1, g + 2): ax2_sum += coefs[i] / (z + i) t = z + g + 0.5 ax_3 = (t ** (z + 0.5)) * cmath.exp(-t) return ((ax_1 * ax2_sum) * ax_3).real
def test_link_complex(ctx): ctx.mkbyref('mycsinf', sinname, ltypes.l_complex64) ctx.mkbyref('mycsin', sinname, ltypes.l_complex128) ctx.mkbyref('mycsinl', sinname, ltypes.l_complex256) # print(ctx.module) ctx.link() print(ctx.module) m = support.make_mod(ctx) input = 10+2j result = cmath.sin(input) call = support.call_complex_byref typeof = lambda f: _base_type(f.argtypes[0]) assert typeof(m.mycsinf) == ctypes.c_float assert typeof(m.mycsin) == ctypes.c_double, typeof(m.mycsin) assert typeof(m.mycsinl) in (ctypes.c_double, ctypes.c_longdouble) r1 = call(m.mycsinf, input) r2 = call(m.mycsin, input) r3 = call(m.mycsinl, input) print("expect:", result) print("got:", r1, r2, r3) assert np.allclose([result] * 3, [r1, r2, r3])
def testas_3(): alpha = [0] * (N + 1) beta = [0] * (N + 1) p = [0] * (N + 1) y = [0] * (N + 1) Fj = [0] * (N + 1) alpha[1] = kapa1 beta[1] = gama1 for i in range(1, N, 1): p[i] = cmath.sin(i**2 - 7) + cmath.cos(i * 8) * 5 * 1j p[0] = kapa1 * p[1] + gama1 p[N] = kapa2 * p[N - 1] + gama2 for i in range(1, N, 1): Fj[i] = C(h, tau) * p[i] - p[i + 1] - p[i - 1] alpha[i + 1] = alpha_plius_1(alpha[i], h, tau) beta[i + 1] = beta_plius_1(alpha[i + 1], beta[i], Fj[i]) y[N] = ((kapa2 * beta[N]) + gama2) / (1.0 - (kapa2 * alpha[N])) for i in range(N, 0, -1): y[i - 1] = Thomas(alpha[i], y[i], beta[i]) skirtumas = difference(y, p) # if(skirtumas < 10**(-12)): # return True return skirtumas
def fft(poly): n = len(poly) print poly if n < 2: return poly if n % 2 == 1: poly.append(0) n += 1 wn = complex(cmath.cos(2 * cmath.pi / float(n)), cmath.sin(2 * cmath.pi / float(n))) w = 1 odd = [poly[i] for i in xrange(1, n, 2)] even = [poly[i] for i in xrange(0, n, 2)] odd_fft = fft(odd) even_fft = fft(even) sum_fft = range(n) for i in xrange(0, n / 2): sum_fft[i] = even_fft[i] + w * odd_fft[i] sum_fft[i + n / 2] = even_fft[i] - w * odd_fft[i] w = w * wn return sum_fft
def fsim(theta, phi, dtype=complex, **kwargs): r"""The 'fermionic simulation' gate: .. math:: \mathrm{fsim}(\theta, \phi) = \begin{bmatrix} 1 & 0 & 0 & 0\\ 0 & \cos(\theta) & -i sin(\theta) & 0\\ 0 & -i sin(\theta) & \cos(\theta) & 0\\ 0 & 0 & 0 & \exp(-i \phi) \end{bmatrix} Note that ``theta`` and ``phi`` should be specified in radians and the sign convention with this gate varies. Here for example, ``fsim(- pi / 2, 0) == iswap()``. """ from cmath import cos, sin, exp a = cos(theta) b = -1j * sin(theta) c = exp(-1j * phi) gate = [[1, 0, 0, 0], [0, a, b, 0], [0, b, a, 0], [0, 0, 0, c]] gate = qu(gate, dtype=dtype, **kwargs) make_immutable(gate) return gate
def clngamma(z): """The logarithm of the gamma function for a complex argument """ z = complex(z) # common case optimization n = floor(z.real) if n == z: if n <= 0: return complex(1.0 / 0.0) # Infinity elif n <= len(__factorial): return complex(__factorial[int(n) - 1]) zz = z if z.real < 0.5: zz = 1 - z g = __lanczos_gamma c = __lanczos_coefficients zz = zz - 1. zh = zz + 0.5 zgh = zh + g zp = zgh ** (zh * 0.5) # trick for avoiding FP overflow above z=141 ss = 0.0 for k in range(len(c) - 1, 0, -1): ss += c[k] / (zz + k) f = (sqrt_2pi * (c[0] + ss)) * ((zp * cm.exp(-zgh)) * zp) if z.real < 0.5: f = pi / (cm.sin(pi * z) * f) return cm.log(f)
def make_axis(self): self.widget.clear() self.max_x = eval(self.lineEdit.text()) self.min_x = eval(self.lineEdit_3.text()) self.max_y = eval(self.lineEdit_2.text()) self.min_y = eval(self.lineEdit_4.text()) self.main_step = eval(self.lineEdit_7.text()) list_x = [ x for x in numpy.arange(self.min_x, self.max_x, self.main_step) ] list_sin_y = [cmath.sin(y).real for y in list_x] list_cos_y = [cmath.cos(y).real for y in list_x] self.widget.setLimits(xMin=self.min_x, xMax=self.max_x, yMin=self.min_y, yMax=self.max_y) self.widget.addLegend() self.widget.plot(list_x, list_sin_y, pen='r', name="sin(x)") self.widget.plot(list_x, list_cos_y, pen='b', name="cos(x)") self.widget.showGrid(x=True, y=True)
def cgamma(z): """Gamma function with complex arguments and results.""" z = complex(z) n = floor(z.real) if n == z: if n <= 0: return complex(1.0 / 0.0) # Infinity elif n <= len(__factorial): return complex(__factorial[int(n) - 1]) zz = z if z.real < 0.5: # Reflection formula zz = 1 - z g = __lanczos_gamma c = __lanczos_coefficients zz = zz - 1. zh = zz + 0.5 zgh = zh + g zp = zgh**(zh * 0.5) # trick for avoiding FP overflow above z=141 ss = 0.0 for k in range(len(c) - 1, 0, -1): ss += c[k] / (zz + k) f = (sqrt_2pi * (c[0] + ss)) * ((zp * cm.exp(-zgh)) * zp) if z.real < 0.5: f = pi / (cm.sin(pi * z) * f) return complex(f)
def draw_wheel(self, canvas, wheel_pos, arc_center_pos, size, theta): # Radius of the dot to draw at the wheel wheel_dot_radius = size / self.WHEEL_DOT_RADIUS_RATIO # Draw a dot at the center of the wheel canvas.create_oval(wheel_pos[0] - wheel_dot_radius, wheel_pos[1] - wheel_dot_radius, wheel_pos[0] + wheel_dot_radius, wheel_pos[1] + wheel_dot_radius, fill="black") # Created a dotted line from the wheel to the center of the circle it will be driving around if not self.go_forward: canvas.create_line(wheel_pos[0], wheel_pos[1], arc_center_pos[0], arc_center_pos[1], dash=(1, 1)) dx = size / self.WHEEL_LENGTH_RATIO * cmath.cos(deg2rad(theta)).real dy = size / self.WHEEL_LENGTH_RATIO * cmath.sin(deg2rad(theta)).real # Draw the wheel line canvas.create_line(wheel_pos[0] - dx, wheel_pos[1] - dy, wheel_pos[0] + dx, wheel_pos[1] + dy, width=size / self.WHEEL_WIDTH_RATIO) return
def clngamma(z): """The logarithm of the gamma function for a complex argument """ z = complex(z) # common case optimization n = floor(z.real) if n == z: if n <= 0: return complex(1.0 / 0.0) # Infinity elif n <= len(__factorial): return complex(__factorial[int(n) - 1]) zz = z if z.real < 0.5: zz = 1 - z g = __lanczos_gamma c = __lanczos_coefficients zz = zz - 1. zh = zz + 0.5 zgh = zh + g zp = zgh**(zh * 0.5) # trick for avoiding FP overflow above z=141 ss = 0.0 for k in range(len(c) - 1, 0, -1): ss += c[k] / (zz + k) f = (sqrt_2pi * (c[0] + ss)) * ((zp * cm.exp(-zgh)) * zp) if z.real < 0.5: f = pi / (cm.sin(pi * z) * f) return cm.log(f)
def gamma(z): # great function from Wiki, but maybe could use memorization? epsilon = 0.0000001 def withinepsilon(x): return abs(x) <= epsilon from cmath import sin, sqrt, pi, exp p = [ 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7 ] z = complex(z) # Reflection formula (edit: this use of reflection (thus the if-else structure) seems unnecessary and just adds more code to execute. it calls itself again, so it still needs to execute the same "for" loop yet has an extra calculation at the end) if z.real < 0.5: result = pi / (sin(pi * z) * gamma(1 - z)) else: z -= 1 x = 0.99999999999980993 for (i, pval) in enumerate(p): x += pval / (z + i + 1) t = z + len(p) - 0.5 result = sqrt(2 * pi) * t**(z + 0.5) * exp(-t) * x if withinepsilon(result.imag): return result.real return result
def inverse_fft(arr): n = len(arr) if (n == 1): return list([arr[0]]) w = [0] * n for i in range(0, n): alpha = (-2 * (cmath.pi) * i) / n w[i] = complex(cmath.cos(alpha), cmath.sin(alpha)) a0 = [0] * int(n / 2) a1 = [0] * int(n / 2) for i in range(0, int(n / 2)): a0[i] = arr[i * 2] a1[i] = arr[i * 2 + 1] y0 = inverse_fft(a0.copy()) y1 = inverse_fft(a1.copy()) y = [0] * n for k in range(0, int(n / 2)): y[k] = y0[k] + w[k] * y1[k] y[k + int(n / 2)] = y0[k] - w[k] * y1[k] return y
def fresnel2(t0, N0, N1, deg=False): """ Calculate the Fresnel coefficients for an interface. Arguments: t0: incident angle (in radians or degrees if deg=True) N0: complex refraction index of the incident medium (n+ik) N1: complex refraction index of the second medium (n+ik) deg: flag controlling the incidence angle units Return rp, rs, tp, ts for the p and s polarizations. """ if deg == True: t0 = t0*m.pi/180. ct0 = cm.cos(t0) st0 = cm.sin(t0) st1 = N0/N1*st0 ct1 = cm.sqrt(1-st1*st1) rp = (N1*ct0 - N0*ct1)/(N1*ct0 + N0*ct1) rs = (N0*ct0 - N1*ct1)/(N0*ct0 + N1*ct1) tp = (2.*N0*ct0)/(N1*ct0 + N0*ct1) ts = (2.*N0*ct0)/(N0*ct0 + N1*ct1) return rp, rs, tp, ts
def __init__(self, eps1, mu1, eps2, mu2, E0p, E0s, dist, lambd, theta, diam_part, indice_rifr): self.eps1 = eps1 self.mu1 = mu1 self.eps2 = eps2 self.mu2 = mu2 self.n1 = np.sqrt(eps1*mu1) self.n2 = np.sqrt(eps2*mu2) self.dist = dist self.gamma = asin(self.n1/self.n2*sin(theta)) alpha = -np.imag(self.gamma) self.k = 2*pi/lambd exp_ = np.exp(-self.k*dist*sinh(alpha)) self.Es = E0s*2*(mu2/mu1)*cos(theta)/((mu2/mu1)*cos(theta)+1j*(self.n2/self.n1)*sinh(alpha))*exp_ self.Ep = E0p*2*(self.n2/self.n1)*cos(theta)/((eps2/eps1)*cos(theta)+1j*(self.n2/self.n1)*sinh(alpha))*exp_ self.indice_rifr = indice_rifr self.size_param = self.k*diam_part/2 self.raggio = diam_part / 2; an, bn = ms.Mie_ab(self.indice_rifr, self.size_param) self.an = an self.bn = bn
def get_intersecting_intervals(self, x_m): if self.x0 - self.a < x_m < self.x0 + self.a: t = cm.acos((x_m - self.x0) / self.a) z = abs(self.b * cm.sin(t)) return [(self.z0 - z, self.z0 + z)] else: return []
def calc(self): ''' Calculates the time for the descent segment :Source: adapted from DLR-LY-IL Performance Tool, J. Fuchte, 2011 ''' #T is the indice for top, b for bottom! altT = self.parent.atmosphere.hCR.getValue() altB = self.parent.atmosphere.hFL1500.getValue() sigmaT = self.parent.atmosphere.sigmaCR.getValue() sigmaB = self.parent.atmosphere.sigmaFL1500.getValue() IAS = self.parent.IASDESCENT.getValue() gamma = self.parent.gammaDESCENT.getValue() tasT = IAS * sigmaT tasB = IAS * sigmaB if sin(gamma * rad) != 0. and (tasT + tasB / 2.) != 0.: time = (altT - altB) * tan((90 - gamma) * rad) / ((tasT + tasB / 2.)) return self.setValueCalc(time) ################################################################################################### #EOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFE# ###################################################################################################
def __test3__(): n = 16 xs = [sin(j) for j in xrange(n)] Xs = dft(xs) Xs2 = fft(xs) for j in xrange(n): assert __dist__(Xs[j]-Xs2[j], 0)<.0001
def time_evolve(u, u_): # 按薛定谔方程演化一步的函数 u->u_ for i in range(N): # 此时刻 H 的对角元 b[i],为后文做准备 b[i] = 1./dx**2 -1 / sqrt(((i-Nx)*dx)**2 + 2) + (i-Nx)*dx*E0*sin(ome*t/(2*Npulse))**2*sin(ome*t) ## 先求 u_=(1-1/2iHΔt) u u_[0] = (1 - 0.5j*dt*b[i]) * u[0] - 0.5j*dt*c[i] * u[1] u_[N-1] = - 0.5j*dt*a[i] * u[N-2] + (1 - 0.5j*dt*b[i]) * u[N-1] for i in range(1, N-1): u_[i] = - 0.5j*dt*a[i] * u[i-1] + (1 - 0.5j*dt*b[i]) * u[i] - 0.5j*dt*c[i] * u[i+1] ## 再用追赶法求 (1+1/2iHΔt) u_' = u_ be[0] = (1 + 0.5j*dt*b[0]) for i in range(1, N): # 追 be[i] = (1 + 0.5j*dt*b[i]) m[i] = 0.5j*dt*a[i] / be[i-1] be[i] -= m[i] * 0.5j*dt*c[i-1] u_[i] -= m[i] * u_[i-1] u_[N-1] /= (1 + 0.5j*dt*b[i-1]) for i in range(N-2, -1, -1): # 赶 u_[i] = (u_[i] - 0.5j*dt*c[i] * u_[i+1]) / be[i] ## 此时u_[i] 就是演化下一刻的波函数 ## 吸收虚假信号 for i in range(N): if abs((i-Nx)*dx) > 0.75*x_max: u_[i] *= exp(-(abs((i-Nx)*dx)-0.75*x_max)**2/0.04) ## 归一化 unorm = sqrt(sum([abs(u_[i])**2 for i in range(N)])) for i in range(N): u_[i] /= unorm
def cgamma(z) : """Gamma function with complex arguments and results.""" z = complex(z) n = floor(z.real) if n == z : if n <= 0 : return complex(1.0/0.0) # Infinity elif n <= len(__factorial) : return complex(__factorial[int(n)-1]) zz = z if z.real < 0.5 : # Reflection formula zz = 1-z g = __lanczos_gamma c = __lanczos_coefficients zz = zz - 1. zh = zz + 0.5 zgh = zh + g zp = zgh** (zh*0.5) # trick for avoiding FP overflow above z=141 ss = 0.0 for k in range(len(c)-1,0,-1): ss += c[k]/(zz+k) f = (sqrt_2pi*(c[0]+ss)) * (( zp*cm.exp(-zgh)) *zp) if z.real<0.5 : f = pi /( cm.sin(pi*z) *f) return complex(f)
def f_xyz_def(xr, xi, yr, yi, zr, zi): x = complex(xr, xi) y = complex(yr, yi) z = complex(zr, zi) return cmath.cos((x**2 + y**2) / z) + 1j * cmath.sin((x**2 + y**2) / z)
def set_dMi_thickness(self, N, thickness, sin2_theta_0): """Calculate the derivative of the characteristic matrices of a layer with regard to its thickness This method takes 3 arguments: N the index of refraction of the layer; thickness the thickness of the layer; sin2_theta_0 the normalized sinus squared of the propagation angle.""" for i in range(self.wvls.length): k = two_pi/self.wvls.wvls[i] N_square = N.N[i]*N.N[i] N_s = cmath.sqrt(N_square-sin2_theta_0.sin2[i]) N_p = N_square/N_s # Correct branch selection. if N_s.real == 0.0: N_s = -N_s N_p = -N_p dphi = k*N_s phi = dphi*thickness j_cos_phi_dphi = 1.0j*cmath.cos(phi)*dphi self.s[i][0] = self.s[i][3] = self.p[i][0] = self.p[i][3] = -cmath.sin(phi)*dphi self.s[i][1] = j_cos_phi_dphi/N_s self.p[i][1] = j_cos_phi_dphi/N_p self.s[i][2] = N_s*j_cos_phi_dphi self.p[i][2] = N_p*j_cos_phi_dphi
def draw_wheel(self, canvas, wheel_pos, arc_center_pos, size, theta): # Radius of the dot to draw at the wheel wheel_dot_radius = size/self.WHEEL_DOT_RADIUS_RATIO # Draw a dot at the center of the wheel canvas.create_oval(wheel_pos[0]-wheel_dot_radius, wheel_pos[1]-wheel_dot_radius, wheel_pos[0]+wheel_dot_radius, wheel_pos[1]+wheel_dot_radius, fill="black") # Created a dotted line from the wheel to the center of the circle it will be driving around if not self.go_forward: canvas.create_line(wheel_pos[0], wheel_pos[1], arc_center_pos[0], arc_center_pos[1], dash=(1, 1)) dx = size/self.WHEEL_LENGTH_RATIO*cmath.cos(deg2rad(theta)).real dy = size/self.WHEEL_LENGTH_RATIO*cmath.sin(deg2rad(theta)).real # Draw the wheel line canvas.create_line(wheel_pos[0]-dx, wheel_pos[1]-dy, wheel_pos[0]+dx, wheel_pos[1]+dy, width=size/self.WHEEL_WIDTH_RATIO) return
def c1_analytic(nf): if even(nf): if abs(nf-2.) < 0.25 : return 1./sqrt(2) else: return 0.0 else: return (4.*sqrt(2)/pi) * ( 1. / ((nf+2.)*(nf-2.)) ) * sin(nf*pi/2.) * (-1)
def to_pixel(self, zoom): 'zoom 11 to 18' siny = cmath.sin(to_rad(self.lat)) y = cmath.log((1 + siny) / (1 - siny)); lat = (128 << zoom) * (1 - y / (2 * PI)); lng = (self.lng + 180.0) * (256 << zoom) / 360.0 return lat.real, lng
def test_complex(): a = complex(2, 4) b = 3 - 4j print a print b print a.real print a.imag print a.conjugate() print a + b print a * b print a / b print abs(b) import cmath print cmath.sin(a) print cmath.cos(b) print cmath.exp(a) print cmath.sqrt(-1)
def moveCursor(alfa): speed = 10 d = display.Display().screen().root.query_pointer()._data obecnyx = d["root_x"] obecnyy = d["root_y"] ruchx = round(real(cos(alfa))*speed) ruchy = -round(real(sin(alfa))*speed) setCursorPosition(obecnyx+ruchx, obecnyy+ruchy)