def test_cos(self): self.assertAlmostEqual(qmath.cos(self.f1), math.cos(self.f1)) self.assertAlmostEqual(qmath.cos(self.c1), cmath.cos(self.c1)) self.assertAlmostEqual(qmath.cos(self.c2), cmath.cos(self.c2)) self.assertAlmostEqual(qmath.cos(Quat(self.f1)), math.cos(self.f1)) self.assertAlmostEqual(qmath.cos(Quat(0, 3)), cmath.cos(3J)) self.assertAlmostEqual(qmath.cos(Quat(4, 5)), cmath.cos(4 + 5J)) self.assertAlmostEqual(qmath.cos(Quat(0, self.f1)), Quat(math.cosh(self.f1)))
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 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 cos(c): """ cos(a+x)= cos(a) sin(x) - sin(a) cos(x) """ if not isinstance(c,pol): return math.cos(c) a0,p=c.separate(); lst=[math.cos(a0),-math.sin(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 _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 int_temp(kA): qp = acos( 0.5*(-cos(kA) + sqrt( (E**2/t**2) - (sin(kA))**2 ) ) ) qm = acos( 0.5*(-cos(kA) - sqrt( (E**2/t**2) - (sin(kA))**2 ) ) ) if qp.imag < 0.0: qp = -qp if qm.imag < 0.0: qm = -qm sig = copysign(1,m-n) const = 1j/(4.0*pi*t**2) if s == 0: return const*E*( exp( 1j*( kA*(m+n) + sig*qp*(m-n) ) ) / ( sin(2*qp) + sin(qp)*cos(kA) ) \ + exp( 1j*( kA*(m+n) + sig*qm*(m-n) ) ) / ( sin(2*qm) + sin(qm)*cos(kA) ) ) elif s == 1: fp = t*( 1.0 + 2.0*cos(qp)*exp(1j*kA) ) fm = t*( 1.0 + 2.0*cos(qm)*exp(1j*kA) ) return const*( exp( 1j*( kA*(m+n) + sig*qp*(m-n) ) )*fp / ( sin(2*qp) + sin(qp)*cos(kA) ) \ + exp( 1j*( kA*(m+n) + sig*qm*(m-n) ) )*fm / ( sin(2*qm) + sin(qm)*cos(kA) ) ) elif s == -1: ftp = t*( 1.0 + 2.0*cos(qp)*exp(-1j*kA) ) ftm = t*( 1.0 + 2.0*cos(qm)*exp(-1j*kA) ) return const*( exp( 1j*( kA*(m+n) + sig*qp*(m-n) ) )*ftp / ( sin(2*qp) + sin(qp)*cos(kA) ) \ + exp( 1j*( kA*(m+n) + sig*qm*(m-n) ) )*ftm / ( sin(2*qm) + sin(qm)*cos(kA) ) ) else: print "Sublattice error in gBulk_kA"
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 collatz(self, c, *p): for i in range(0, self.maxiter): c = (2 + 7*c - (2 + 5*c)*cmath.cos(cmath.pi*c))/4; m = abs(c) if m > self.limit: break return i, m
def test_dft_brute_force(self): x=[] for n in range(8): x.append(cmath.cos(2*cmath.pi*n/8)) print_(x) X=dft(x) print_(X)
def goto(self, brng, dist): if isinstance(brng, LatLng): brng = self.bearing_to(brng) brng = to_rad(brng) dist = float(dist) / self.R lat1 = to_rad(self.lat) lng1 = to_rad(self.lng) lat2 = cmath.asin(cmath.sin(lat1) * cmath.cos(dist) + cmath.cos(lat1) * cmath.sin(dist) * cmath.cos(brng)) lng2 = lng1 + math.atan2((cmath.sin(brng) * cmath.sin(dist) * cmath.cos(lat1)).real, (cmath.cos(dist) - cmath.sin(lat1) * cmath.sin(lat2)).real) lng2 = (lng2+3*PI) % (2*PI) - PI return LatLng(to_deg(lat2.real), to_deg(lng2.real))
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 complexmath(self): a = complex(2,4) b = 3 - 5j import cmath print( cmath.sin(a)) print( cmath.cos(b))
def calcRaymer(self): """ calculates the Wings Mass :Source: Aircraft Design: A Conceptual Approach, D. P. Raymer, AIAA Education Series, 1992, Second Edition, p.399, eq. 15.25 """ S = self.parent.refArea.getValue() mTOM = self.parent.aircraft.mTOM.getValue() tcRoot = self.parent.tcAVG.getValue() AR = self.parent.aspectRatio.getValue() phi25 = self.parent.phi25.getValue() n = 3.75 taperRatio = self.parent.taperRatio.getValue() Scs = 80.0 mTOM = mTOM * 2.204 S = S * 3.281 ** 2 return self.setValueCalc( 0.0051 * (mTOM * n) ** 0.557 * S ** 0.649 * AR ** 0.5 * tcRoot ** -0.4 * (1 + taperRatio) ** 0.1 * 1 / cos(phi25 * rad) * Scs ** 0.1 )
def calc(self): ''' Calculates the drag divergence Mach number from the wings thickness to chord ratio, the wing sweep and the local Cl. :Source: W.H. Mason, Configuration Aerodynamics, 2006, p. 7-18, eq. 7-4 ''' #Getters tcAVG = self.parent.tcAVG.getValue() phi25 = self.parent.phi25.getValue() cL = self.parent.aircraft.cLCR.getValue() #inverse calculation of local Cl cl = cL / (1.075) #kA is a technology factor for determining the capabilities of the airfoil #Mason states 0.95 for super-critical design and 0.87 for NACA 6 series airfoils kA = 0.95 phiCos = cos(phi25 * rad) if cl > 1.: self.log.warning('VAMPzero CALC: Wave Drag Convergence issues as local lift exceeds one.') self.log.warning('VAMPzero CALC: Will reset cl to one and continue calculation, hope to achieve convergence in the next iteration') cl = 1. machDD = kA / phiCos - tcAVG / phiCos ** 2 - cl / (10. * phiCos ** 3) else: machDD = kA / phiCos - tcAVG / phiCos ** 2 - cl / (10. * phiCos ** 3) return self.setValueCalc(machDD)
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 calcCEAS(self): ''' This calculation is based on a multi-fidelity study that we did for the CEAS conference in 2011. We ran a set of 500 LIFTING_LINE calculations and applied a symbolic regression application named Eurequa to the data that we obtained. The design space of this equation is: * taperRatio 0.1 - 0.6 * phi25 -20deg - 30 deg * aspectRatio 6 - 16 * twist -10 - 0 * kinkRatio 0.2-0.4 :Source: An Integrated Method for the Determination of the Oswald Factor in a Multi-Fidelity Design Environment, D. Boehnke, J. Jepsen, B. Nagel, V. Gollnick, C. Liersch, CEAS 2011 :Source: Distilling Free-Form Natural Laws from Experimental Data, M. Schmidt , H. Lipson, Science, Vol. 324, no. 5923, pp. 81 - 85., 2009 :Source: Ein Mehrfach-Traglinienverfahren und seine Verwendung fuer Entwurf und Nachrechnung nichtplanarer Fluegelanordnungen, K. H. Horstmann, DFVLR-FB 87-51, 1987 ''' taperRatio = self.parent.taperRatio.getValue() phi = self.parent.phi25.getValue() aspectRatio = self.parent.aspectRatio.getValue() eta = self.parent.etaKink.getValue() twist = self.parent.twist.getValue() t1 = 0.04 - 0.0007 * aspectRatio - 0.00019 * phi * twist t2 = 0.16 - 0.0007 * aspectRatio * phi - 0.0007 * aspectRatio * phi * eta - 0.55 * taperRatio t3 = taperRatio ** 0.03 * cos(t2 * rad) return self.setValueCalc(t1 + t3)
def cos_iteration(z): for i in range(bailout): if abs(z.imag) > 50.0: break else: z = c*cos(z) return i
def calc(self): ''' Calculates the form factor for the wing :Source: Aircraft Design: A Conceptual Approach, D. P. Raymer, AIAA Education Series, 1992, Second Edition, p.283 ''' machCR = self.parent.aircraft.machCR.getValue() tcAVG = self.parent.tcAVG.getValue() ctm = self.parent.airfoilr.ctm.getValue() phi25 = self.parent.phi25.getValue() #@note: Root Airfoil value is taken for Calculation of the FormFaktor term1 = 1 + 0.6 / ctm * tcAVG + 100 * tcAVG ** 4 #Assumption that phiMax equals phi25 #@todo: calc formFactor: kill assumption that phiMax equals phi25 term2 = 1.34 * machCR ** 0.18 * (cos(phi25 * rad)) ** 0.28 return self.setValueCalc(term1 * term2) ################################################################################################### #EOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFE# ###################################################################################################
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 forest_model_c_scat(m_canopy, m_soil, rms_g, volume, angle, T, S, C, freq=5.255, eps_top=1, const=-5.12e-3): """ backscattering of forest, according to Pulliainen et.al. Parameters ---------- m_canopy : float relative canopy m_soil : float relative soil moisture rms_g : float surface roughness of ground in meters volume : float forest stem volume angle : float incidence angle in degrees T : float temperature in deg Celsius S : float proportion of sand C : float proportion of clay freq : float, optional frequency of EM wave in GHz eps_top : float, optional dielectricity constant of top layer const : float, optional some kind of constant - not documented """ freqHz = freq * 1e9 angle_rad = angle / 180.0 * cmath.pi eps_low = eps_g_func(freqHz, S, C, T, m_soil) # backscatter soil sigma0 = oh_r(eps_top, eps_low, freqHz, angle, rms_g) # ASCAT has VV polarization sigma_s = sigma0['vv'] sigma_cvv = 0.131 * m_canopy * cmath.cos(angle_rad) * (1 - cmath.exp(const * m_canopy * volume / cmath.cos(angle_rad))) + ( sigma_s * cmath.exp(const * m_canopy * volume / cmath.cos(angle_rad))) return sigma_cvv.real
def oh_r(eps_top, eps_low, f, theta, rms_g): """ Oh et.al. (1992) surface backscatter calculations This functions calculations surface backscatter using the Oh et al. (1992) surface model. References Oh et al., 1992, An empirical model and an inversion technique for rader scattering from bare soil surfaces. IEEE Trans. Geos. Rem., 30, pp. 370-380 Parameters ---------- eps_top : complex number complex permittivity of upper(incoming) medium eps_low : complex number complex permittivity of lower medium f : float frequency in hertz theta : float incidence angle in degrees rms_g : float surface rms height in m """ # speed of light in m/s c = 2.998e8 # calculate wavelength in upper medium by using real part of refarctive index n_upper = cmath.sqrt(eps_top) wavelength = (c / f) / n_upper.real k_rms = (2. * cmath.pi / wavelength) * rms_g eps_eff = eps_low / eps_top gam0 = gammah(eps_eff, 0) gamh = gammah(eps_eff, theta) gamv = gammav(eps_eff, theta) theta = theta / 180.0 * cmath.pi # precalulcate cosines of angles ct = cmath.cos(theta) # Oh model equations g = 0.7 * (1. - cmath.exp(-0.65 * k_rms ** 1.8)) root_p = 1. - ((2. * theta / cmath.pi) ** (1. / (3. * gam0))) * cmath.exp(-k_rms) p = (1 - (2 * theta / cmath.pi) ** (1 / (3 * gam0)) * cmath.exp(-1 * k_rms)) ** 2 q = 0.23 * cmath.sqrt(gam0) * (1. - cmath.exp(-k_rms)) sigma0 = {} sigma0['vv'] = g * (ct * (ct * ct)) * (gamv + gamh) / root_p # sig0vv = ((g*(cos(theta))^3)/sqrt(p))*(gamv+gamh); sigma0['vh'] = q * sigma0['vv'] sigma0['hh'] = root_p * root_p * sigma0['vv'] return sigma0
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)
def set_strain( strain = 0, angle = 0 ): """ Sets Global values to be used in all calculations. Strain = 0.0 - 0.2 for realistic strain. Angle: 0 = Zigzag direction, pi/2 = Armchair direction, only works for these directions!! """ global t1, t2 # Strain matrix sig = 0.165 E11 = strain*(cos(angle)**2 - sig*sin(angle)**2) E12 = strain*((1+sig)*cos(angle)*sin(angle)) E22 = strain*(sin(angle)**2 - sig*cos(angle)**2) # New distances l1 = 1 + E22 l2 = 1 + 0.75*E11 - (sqrt(3.0)/2)*E12 + 0.25*E22 # New hoppings t1 = -exp(-3.37*(l1-1)) t2 = -exp(-3.37*(l2-1))
def complex_math(): a = complex(2, 4) b = 3 - 5j print(a.conjugate()) # 正弦 余弦 平方根等 print(cmath.sin(a)) print(cmath.cos(a)) print(cmath.sqrt(a))
def test_cos_cc (self): src_data = [complex(i,i+1) for i in range(-5, 5, 2)] expected_result = tuple(cmath.cos(i) for i in src_data) src = gr.vector_source_c(src_data) op = gr.transcendental('cos', 'complex_float') snk = gr.vector_sink_c() self.tb.connect(src, op, snk) self.tb.run() result = snk.data() self.assertComplexTuplesAlmostEqual(expected_result, result, places=5)
print(max(x, y)) print(min(x, y)) print(pow(y, 2)) #y^2 print(math.sqrt(y)) #y's square root print(u"common random:") a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] print(random.choice(a)) print(random.randrange(2, 100, 5)) #(2,100) 按5递增 print(random.random()) #(0,1) print(u"common cmath:") x = 100 print(cmath.acos(x)) print(cmath.sin(x)) print(cmath.cos(x)) print(u"constant:") print(cmath.pi) ''' result is: commmon math: 100 1.9 -100 3.61 1.378404875209022 common random: 4 77 0.5780858557339232
def cos(a, b): result = a**2 + b**2 return cmath.cos(result) + 1.6j
math.sin(x) NameError: name 'x' is not defined >>> math.sin(2) 0.9092974268256817 >>> math.cos(4) -0.6536436208636119 >>> math.cosh(15) 1634508.6862362083 >>> math.atan(2) 1.1071487177940904 >>> math.degrees(math.sin(2)) 52.098904879217365 >>> import cmath >>> cmath.sin(2) (0.9092974268256817-0j) >>> cmath.cos(4) (-0.6536436208636119+0j) >>> cmath.cosh(15) (1634508.6862362083+0j) >>> cmath.atan(2) (1.1071487177940904+0j) >>> cmath.degrees(cmath.sin(2)) Traceback (most recent call last): File "<pyshell#23>", line 1, in <module> cmath.degrees(cmath.sin(2)) AttributeError: 'module' object has no attribute 'degrees' >>> help(cmath) Help on built-in module cmath: NAME
def c(): #a=input() plt.plot([cos(x) for x in range(int(e.get()))]) plt.show()
def cellid(self): lat = self.lat lng = self.lng d3 = cmath.cos(lat) d4 = d3 * cmath.cos(lng).real d5 = d3 * cmath.sin(lng).real d6 = cmath.sin(lat).real d7 = abs(lat) d8 = abs(d5) d9 = abs(d6) i = 3 d10 = -d5 / d6 d11 = -d4 / d6 a = [0, ]*1024 b = [0, ]*1024 c = [[0, 1, 3, 2], [0, 2, 3, 1], [3, 2, 0, 1], [3, 1, 0, 2],] def f_a_II(i1, i2): return c[i1][i2] def f_a_I(i1): return [1, 0, 0, 3][i1] def b_a_IIIIII(p1, p2, p3, p4, p5, p6): if p1 == 4: return i3 = p3 + p2 << 4 a[p4+(i3<<2)] = p6 + (p5 << 2) b[p4+(p5<<2)] = p6 + (i3 << 2) i = p1 + 1 j = p2 << 1 k = p3 << 1 m = p5 << 2 for n in range(0, 4): i1 = f_a_II(p6, n) i2 = f_a_I(n) b_a_IIIIII(i, j + (i1 >> 1), k + (i1 & 0x1), p4, m+n, p6^i2) def b_a(double): return int(max(0, min(2**30-1, round(2**29 - 0.5 + 2**29 * double)))) def aa_b(double): double = 4 * cmath.atan(double).real / PI if double > 0: return cmath.sqrt(1 + 3 * double).real - 1 else: return 1 - cmath.sqrt(1 - 3 * double).real b_a_IIIIII(0, 0, 0, 0, 0, 0) b_a_IIIIII(0, 0, 0, 1, 0, 1) b_a_IIIIII(0, 0, 0, 2, 0, 2) b_a_IIIIII(0, 0, 0, 3, 0, 3) print a l = 0 j = b_a(aa_b(d10)) k = b_a(aa_b(d11)) l = i << 60 m = i & 0x1 for n in range(7, -1, -1): i1 = m + ((0xF & j >> n * 4) << 6) + ((0xF & k >> n * 4) << 2) i2 = a[i1] print i2, i1 l |= i2 >> 2 << 4 * (n * 2) m = i2 & 0x3 return 1L + (l << 1);
def cos_usecase(x): return cmath.cos(x)
def solve(Ninput,f,dom,k,y,DtNmap,name,actual=None,img_show=True,fix=None): t0=time() # Erik's 1D fixing if fix=="AUTO": fixt=k*dom.width fix=(6*cmath.cos(fixt)-6+fixt**2*cmath.cos(fixt)+2*fixt**2)/(12*(1-cmath.cos(fixt))**2) # set up mesh dom.extend(Ninput) # set up solution vectors u=[None]*(Ninput+2) # create matrix A=lil_matrix((Ninput+2,Ninput+2),dtype=complex) b=array([0]*(Ninput+2),dtype=complex) #FEM for i in range(0,Ninput+2): phi_i,dphi_i=element.new_linear(dom(i-1),dom(i),dom(i+1)) int_over_me=[dom(i-1),dom(i+1)] xv=[] yv=[] yv2=[] def integrand(x): return phi_i(x)*f(x) bnew,error=integrate.quad(integrand,int_over_me[0],int_over_me[1]) for j in range(0,Ninput+2): if j>=i-2 and j<=i+2: Aentry=0 phi_j,dphi_j=element.new_linear(dom(j-1),dom(j),dom(j+1)) def integrand1(x): return dphi_i(x)*dphi_j(x) def integrand2(x): return phi_i(x)*phi_j(x) i1,error=integrate.quad(integrand1,int_over_me[0],int_over_me[1]) i2,error=integrate.quad(integrand2,int_over_me[0],int_over_me[1]) Aentry+=i1 Aentry-=k**2*i2 Aentry+=DtNmap(phi_i,phi_j) if fix!=None: for ki in range(max(1,i-1),min(Ninput,i+2)): Aentry+=fix*jump(dphi_i,dom(ki),dom.width/2)*jump(dphi_j,dom(ki),dom.width/2)*dom.width Aentry+=fix*dom.width*(dphi_i(dom[1])-1j*k*phi_i(dom[1]))*(dphi_j(dom[1]).conjugate()+1j*k*phi_j(dom[1]).conjugate()) Aentry-=fix*dom.width*(dphi_i(dom[0])-1j*k*phi_i(dom[0]))*(dphi_j(dom[0]).conjugate()+1j*k*phi_j(dom[0]).conjugate()) #FIX THESE TWO LINES A[i,j]=Aentry b[i]=bnew #solve A=A.tocsr() b=array(b) soln=spsolve(A,b) def solution(x): if x<dom[0]: return soln[0]*y(dom[0]-x) for i in range(1,len(u)): if x<dom(i): return (soln[i]-soln[i-1])*(x-dom(i-1))/(dom(i)-dom(i-1))+soln[i-1] return soln[-1]*y(x-dom[1]) t1=time() #draw some pretty pictures if img_show: uMesh=linspace(dom[0]-dom.FEM_width/2,dom[1]+dom.FEM_width/2,3000) uPlot=[solution(p) for p in uMesh] if actual!=None: yv=[actual(p) for p in uMesh] yer=[abs(real(a-b)) for a,b in zip(uPlot,yv)] plt.clf() plt.plot(uMesh,uPlot) labels=['FEM BEM Coupling'] if actual!=None: plt.plot(uMesh,yv) labels.append('Actual Solution') plt.legend(labels, loc='upper left',prop={'size':8}) plt.grid(True) plt.title(name+" FEM in ("+str(dom[0])+","+str(dom[1])+") with "+str(Ninput)+" mesh nodes") plt.savefig(join(worldwide.PATH,'graph.png')) plt.show() plt.clf() maxyer=0 if actual!=None: plt.title("Error for "+name+" FEM in ("+str(dom[0])+","+str(dom[1])+") with "+str(Ninput)+" mesh nodes") plt.plot(uMesh,yer) plt.legend(['Error'],loc='upper left',prop={'size':8}) plt.grid(True) plt.savefig(join(worldwide.PATH,'graph-error.png')) plt.show() maxyer=max(yer) elif actual!=None: def yer(x): return -abs(real(solution(x)-actual(x))) maxyer=-minimise_scalar(yer).fun t1=time() print("Time taken for "+str(int(Ninput))+" nodes: %f seconds" %(t1-t0)) if actual!=None: return maxyer,t1-t0 else: return 0,t1-t0
def test_cos(self): self.assertAlmostEqual(complex(-27.03495, -3.851153), cmath.cos(complex(3, 4)))
def main(): ar = np.array(["wavelength", "reflectance", "transmittance"]) z = 0 for y in range(len(arr)): wl = arr[y][0] om = c * (cmath.pi * 2) / (wl) ## create complex arrays for outputs of matmult steps temp = np.zeros((2, 2), complex) Mmatrix = np.zeros((2, 2), complex) # create initial D matrix and invert it dM = dmatrix(getN(arr, 1, z), theta, lpol, 1, arr, z) inverseDM = npla.inv(dM) # create product of D P D^-1 for all intermediate layers sumproduct = product(numLayers, lpol, theta, om, arr, z) # create D for final layer dL = getD(numLayers) nL = getN(arr, numLayers, z) LDM = dmatrix(nL, theta, lpol, 3, arr, z) # This is SP = PRODUCT_l (D_l P D_l^-1) * D_Nlayers np.dot(sumproduct, LDM, temp) # This is M = D_1 * SP np.dot(inverseDM, temp, Mmatrix) # Now get the r, t amplitudes along with R and T r = Mmatrix[1, 0] / Mmatrix[0, 0] R = r * np.conjugate(r) lt = 1 / Mmatrix[0, 0] finalAngle = t(theta, 1, numLayers, arr, z) T = lt*np.conj(lt) * (getN(arr, numLayers, z)) * cmath.cos(finalAngle) / ((cmath.cos(theta) * getN(arr, 1, z))) A = 1 - T - R m = np.array([wl, R, T]) ar = np.vstack((ar,m)) ar = np.real(ar) z +=1 ans = [A, T, R] # for k in range(len(ar)): # for l in range(3): # a = ar[k][l] # a = np.real(a) # print(a, end =" ") # print() text_file = open("/Users/jtsatsaros2018/Documents/test1", "a") for k in range(len(ar)): for l in range(3): a = ar[k][l] a = np.real_if_close(a) text_file.write(str(a)) text_file.write("\n") text_file.close() return ans
print(random.choice(a)) # 从指定的范围(2-100按5递增的数据集)中随机选中一个 print(random.randrange(2, 100, 5)) # 生成一个随机数,在(0,1)之间 print(random.random()) print("*" * 100) # 分隔 print("常用三角函数") z = 100 # 返回z的反余弦弧度值 print(cmath.acos(z)) # 返回z的正弦弧度值 print(cmath.sin(z)) # 返回z的余弦弧度值 print(cmath.cos(z)) print("*" * 100) # 分隔 print("数学常量") print(cmath.pi) x1 = 1.68 y1 = 10 # 将x转化为整数 print(int(x1)) # 将y转换成浮点数 print(float(y1)) # 将x转换为复数,实数部分为x,虚数部分为0 print(complex(x1))
quit() #Convert back from zero mean data for i in range(0, N): if normalize == 'True': gen_x[ensemble][i] *= std[i] gen_x[ensemble][i] += mu[i] if i > 0: gen_x[ensemble][i] += gen_x[ensemble][i - 1] #Compute the beam pattern for i in range(0, NU): for j in range(0, N): R[ensemble][i] += cmath.exp( complex(0, -1) * (KHAT * cmath.cos((i * (2 * pi) / NU) - gen_x[ensemble][j]) - KHAT * cmath.cos(theta_T - gen_x[ensemble][j]))) R[ensemble][i] = R[ensemble][i] / N #Compute cost for j in range(0, NU): #Only compute the cost if it's above the desired if ((20 * np.log10(abs(R[ensemble][j]))) > des[2][j]): cost[ensemble] += ( (20 * np.log10(abs(R[ensemble][j]))) - des[2][j]) * ( (20 * np.log10(abs(R[ensemble][j]))) - des[2][j]) #Normalize with frequency resolution so higher resol != higher cost cost[ensemble] = cost[ensemble] / NU #Now save it all to file
from fractal import CIFS from cmath import sin, cos, exp, sinh, cosh man = CIFS([500, 500]) man.setRange(20, 20) man.setRadius(5) # man.setFunction(lambda z: exp(z) * cos(z)) # man.setFunction(lambda z: cos(exp(z))) # man.setFunction(lambda z: sin(exp(z))) # man.setFunction(lambda z: sin(cos(z))) # man.setFunction(lambda z: exp(sin(z))) # man.setFunction(lambda z: exp(cos(z))) # man.setFunction(lambda z: sin(z)*cosh(z)) # man.setFunction(lambda z: sinh(z**2)) # man.setFunction(lambda z: sinh(z**3)) # man.setFunction(lambda z: sinh(z**4)) # man.setFunction(lambda z: sin(z**2)) # man.setFunction(lambda z: sin(z**3)) # man.setFunction(lambda z: z**sin(z)) # man.setFunction(lambda z: z**cos(z)) man.setFunction(lambda z: z**sin(z) + z**cos(z)) # man.setFunction(lambda z: exp(z) - z ** z) man.doCifs(150) man.wait()
def int_temp(kA): qp = acos( 0.5*(-cos(kA) + sqrt( (E**2/t**2) - (sin(kA))**2 ) ) ) qm = acos( 0.5*(-cos(kA) - sqrt( (E**2/t**2) - (sin(kA))**2 ) ) ) if qp.imag < 0.0: qp = -qp if qm.imag < 0.0: qm = -qm sig = copysign(1,DZ) # Check this versus zigzag SI (should be same though, on exponential) const = 1j/(2.0*pi*t**2) if s_lat == 'bb': return const*E*exp(1j*sig*qp*(DZ))*sin(kA*DA1)*sin(kA*DA2) / ( sin(2*qp) + sin(qp)*cos(kA) ) \ + const*E*exp(1j*sig*qm*(DZ))*sin(kA*DA1)*sin(kA*DA2) / ( sin(2*qm) + sin(qm)*cos(kA) ) elif s_lat == 'ww': fp = 1.0 + 2.0*cos(qp)*exp(1j*kA) fm = 1.0 + 2.0*cos(qm)*exp(1j*kA) ftp = 1.0 + 2.0*cos(qp)*exp(-1j*kA) ftm = 1.0 + 2.0*cos(qm)*exp(-1j*kA) fpasq = 1.0 + 4.0*cos(qp)*cos(kA) + 4.0*cos(qp)**2 fmasq = 1.0 + 4.0*cos(qm)*cos(kA) + 4.0*cos(qm)**2 Np = ( ftp*exp(-1j*kA*DA1) - fp*exp(1j*kA*DA1) )*( fp*exp(1j*kA*DA2) - ftp*exp(-1j*kA*DA2) )/fpasq Nm = ( ftm*exp(-1j*kA*DA1) - fm*exp(1j*kA*DA1) )*( fm*exp(1j*kA*DA2) - ftm*exp(-1j*kA*DA2) )/fmasq return 0.25*const*E*exp(1j*sig*qp*DZ)*Np / ( sin(2*qp) + sin(qp)*cos(kA) ) \ + 0.25*const*E*exp(1j*sig*qm*DZ)*Nm / ( sin(2*qm) + sin(qm)*cos(kA) ) else: print 's_lat not a valid character'
def circulate(pos): theta = 2*pi*pos/len(chords) x = int(abs(scale+margin+scale*cos(theta))) y = int(abs(scale+margin+scale*sin(theta))) return x,y
def realPart( n, N, k ): """ given a value n, N, and k, return the real part of a function F """ phase = 2 * cmath.pi * ( n * k ) / N return F(n)*cmath.cos(phase)
def operator_to_matrix(operator, arg=None): if arg is not None: arg = float(arg) return { 'Rx': np.array([[cmath.cos(arg / 2), -1j * cmath.sin(arg / 2)], [1j * cmath.sin(arg / 2), cmath.cos(arg / 2)]]), 'Ry': np.array([[cmath.cos(arg / 2), -cmath.sin(arg / 2)], [cmath.sin(arg / 2), cmath.cos(arg / 2)]]), 'Rz': np.array([[cmath.exp(-1j * arg / 2), 0], [0, cmath.exp(1j * arg / 2)]]), 'CR': np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, cmath.exp(arg * 1j)]]), 'CRk': np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, cmath.exp((2 * cmath.pi * 1j) / 2 ** arg)]]), }.get(operator, 'Invalid generator: There should be no argument for generator: ' + operator) return { 'X': np.array([[0, 1], [1, 0]]), 'Y': np.array([[0, -1j], [1j, 0]]), 'Z': np.array([[1, 0], [0, -1]]), 'H': (1/2**0.5) * np.array([[1, 1], [1, -1]]), 'I': np.array([[1, 0], [0, 1]]), 'S': np.array([[1, 0], [0, 1j]]), 'Sdag': np.array([[1, 0], [0, -1j]]), 'T': np.array([[1, 0], [0, cmath.exp((1j * cmath.pi) / 4)]]), 'Tdag': np.array([[1, 0], [0, cmath.exp((-1j * cmath.pi) / 4)]]), 'CNOT': np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]), 'CX': np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]), 'CY': np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, -1j], [0, 0, 1j, 0]]), 'CZ': np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]]), 'SWAP': np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]), 'Toffoli': np.array([[1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0]]) }.get(operator, 'Invalid generator: The given generator does not exist: ' + operator)
def cmathFuc(self): print(cmath.cos(45)) print(cmath.log10(100)) print(cmath.e)
def matrix_to_operator(matrix, arg=None): eye = np.identity(matrix.shape[0]) #if np.isclose(matrix, eye).all(): # return 'I' operator = { 'X': np.array([[0, 1], [1, 0]]), 'Y': np.array([[0, -1j], [1j, 0]]), 'Z': np.array([[1, 0], [0, -1]]), 'H': (1/2**0.5) * np.array([[1, 1], [1, -1]]), 'S': np.array([[1, 0], [0, 1j]]), 'Sdag': np.array([[1, 0], [0, -1j]]), 'T': np.array([[1, 0], [0, cmath.exp((1j * cmath.pi) / 4)]]), 'Tdag': np.array([[1, 0], [0, cmath.exp((-1j * cmath.pi) / 4)]]), 'CNOT': np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]), 'CX': np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]), 'CY': np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, -1j], [0, 0, 1j, 0]]), 'CZ': np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]]), 'SWAP': np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]), 'Toffoli': np.array([[1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0]]) } for key, value in operator.items(): if matrix.shape == value.shape: if np.isclose(matrix, value).all(): print('Rounded') return key if arg is not None: arg = float(arg) operators = { 'Rx': np.array([[cmath.cos(arg / 2), -1j * cmath.sin(arg / 2)], [1j * cmath.sin(arg / 2), cmath.cos(arg / 2)]]), 'Ry': np.array([[cmath.cos(arg / 2), -cmath.sin(arg / 2)], [cmath.sin(arg / 2), cmath.cos(arg / 2)]]), 'Rz': np.array([[cmath.exp(-1j * arg / 2), 0], [0, cmath.exp(1j * arg / 2)]]), 'CR': np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, cmath.exp(arg * 1j)]]), 'CRk': np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, cmath.exp((2 * cmath.pi * 1j) / 2 ** arg)]]), } for key, value in operators.items(): if np.isclose(matrix, value).all(): return key + ' ' + str(arg) return 'Invalid generator: The given matrix does not require an argument or the matrix is invalid' else: # No argument is given so we try to find the R gate ourselves if matrix.shape == (2, 2): # R if matrix[0][1] == 0 and matrix[1][0] == 0: # Rz return 'Rz ' + str(2 * -change_domain(cmath.phase(matrix[0,0]), new_domain=[0, 2*np.pi])) elif isinstance(matrix[1, 0], complex): # Rx return 'Rx ' + str(2 * change_domain(cmath.acos(matrix[0,0]).real)) else: # Ry return 'Ry ' + str(2 * change_domain(cmath.acos(matrix[0,0]).real)) elif matrix.shape == (4, 4): # Controlled R if np.count_nonzero(matrix - np.diag(np.diagonal(matrix))) == 0: # This checks if the matrix is diagonalized if matrix[0][0] == matrix[1][1] == matrix[2][2] == 1: # This checks whether the first 3 diagonal entries are 1 polar_coords = cmath.polar(matrix[3][3]) if np.isclose(polar_coords[0], 1): # Check whether r_coord equals 1 phi = polar_coords[1] if np.isclose(phi, 0): return 'CR ' + str(phi) k = cmath.log(-(2 * cmath.pi) / phi, 2).real if isinstance(k, int) or k.is_integer(): return 'CRk ' + str(int(k)) return 'CR ' + str(phi) return 'Invalid generator' else: return 'Invalid generator' return 'Something went wrong'
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import math from fractions import Fraction import cmath a, b, c = float('inf'), float('-inf'), float('nan') print(type(a), a, type(b), b, type(c), c) print(math.isinf(a), math.isnan(c), a == a, c == c) print(a + 45, a * 10, 10 / a, a / a, a + b, a == float('inf')) print(c + 45, c * 10, 10 / c, c == float('nan'), c is float('nan')) a, b = Fraction(5, 4), Fraction(7, 16) print(a + b, a * b) c = Fraction(3, 8) * Fraction(7, 5) print(c.numerator, c.denominator, float(c), c.limit_denominator(8), c.limit_denominator(64)) print(Fraction(*4.625.as_integer_ratio()), Fraction(4.625), Fraction(" -4.625 \t\n")) a, b = complex(2, 4), 3 - 5j print(a, a.real, a.imag, a.conjugate(), a.conjugate) print(b, a + b, a * b, a / b, abs(a)) print(cmath.sin(a), cmath.cos(a), cmath.exp(a)) print(cmath.sqrt(-1))
def cos(x): if isinstance(x, complex): return cmath.cos(x) else: return math.cos(x)
#复数计算 a = complex(2, 4) b = 3 - 5j print(a) print(b) print(a.real, b.real) print(a.conjugate()) print(a + b) print(a * b) print(a / b) print(abs(a)) #如果要执行有关复函数的操作,可以使用cmath import cmath print(cmath.sin(a)) print(cmath.cos(a)) print(cmath.exp(a)) import numpy as np a = np.array([2 + 3j, 4 + 5j, 6 - 7j, 8 + 9j]) print(a) print(a + 2) print(np.sin(a)) #python的标准函数不会产生复数,如果希望产生复数的结果,要使用cmath函数 print(cmath.sqrt(-1))
priority=4), "acos": _CustomQuirkOperationToken( unary_action=lambda e: sympy.acos(e) * 180 / sympy.pi, binary_action=None, priority=4), } PARSE_COMPLEX_TOKEN_MAP_DEG["arccos"] = PARSE_COMPLEX_TOKEN_MAP_DEG["acos"] PARSE_COMPLEX_TOKEN_MAP_DEG["arcsin"] = PARSE_COMPLEX_TOKEN_MAP_DEG["asin"] PARSE_COMPLEX_TOKEN_MAP_RAD: Dict[str, _HangingToken] = { **PARSE_COMPLEX_TOKEN_MAP_ALL, "cos": _CustomQuirkOperationToken( unary_action=lambda e: sympy.cos(e) if isinstance(e, sympy.Basic) else cmath.cos(e), binary_action=None, priority=4, ), "sin": _CustomQuirkOperationToken( unary_action=lambda e: sympy.sin(e) if isinstance(e, sympy.Basic) else cmath.sin(e), binary_action=None, priority=4, ), "asin": _CustomQuirkOperationToken( unary_action=lambda e: sympy.asin(e) if isinstance(e, sympy.Basic) else np.arcsin(e), binary_action=None,
def execute_pcode(z, code, const_tab): MAX_STACK: int32 = 1024 stack = np.empty(MAX_STACK, dtype=complex64) sp: int32 = 0 pc: int32 = 0 cc: int8 = code[pc] zero: complex64 = 0 + 0j while cc != SEND: if cc == SPUSHC: stack[sp] = const_tab[code[pc + 1]] sp += 1 pc += 1 elif cc == SPUSHZ: stack[sp] = z sp += 1 elif cc == SADD: sp -= 2 stack[sp] += stack[sp + 1] sp += 1 elif cc == SSUB: sp -= 2 stack[sp] -= stack[sp + 1] sp += 1 elif cc == SMUL: sp -= 2 stack[sp] *= stack[sp + 1] sp += 1 elif cc == SDIV: sp -= 2 stack[sp] = stack[sp] / stack[ sp + 1] if stack[sp + 1] != zero and isfinite( stack[sp + 1]) and isfinite(stack[sp]) else zero sp += 1 elif cc == SPOW: sp -= 2 stack[sp] = stack[sp]**stack[sp + 1] sp += 1 elif cc == SNEG: stack[sp - 1] = -stack[sp - 1] elif cc == SSIN: stack[sp - 1] = sin(stack[sp - 1]) elif cc == SCOS: stack[sp - 1] = cos(stack[sp - 1]) elif cc == STAN: stack[sp - 1] = tan(stack[sp - 1]) elif cc == SASIN: stack[sp - 1] = asin(stack[sp - 1]) elif cc == SACOS: stack[sp - 1] = acos(stack[sp - 1]) elif cc == SATAN: stack[sp - 1] = atan(stack[sp - 1]) elif cc == SLOG: stack[sp - 1] = log(stack[sp - 1]) if stack[sp - 1] != zero else zero elif cc == SEXP: stack[sp - 1] = exp(stack[sp - 1]) pc += 1 cc = code[pc] return stack[0]
import potentials import cmath a = -10. b = 10. dim = 500 deltaX = (b - a) / dim deltaT = 1 # EIGEN STATES? baseMatrix = np.matrix(np.zeros((dim, dim), dtype=np.complex)) initialValues = np.matrix(np.zeros((dim,1), dtype=np.complex)) for i in range(dim): initialValues[i, 0] = cmath.cos(a + i * deltaX) V = potentials.potential('harmonic oscillator', a, b, 0, 0) def zeroConditions(dim): # Psi(0) = Psi(x) = 1 baseMatrix[0, 0] = 1 baseMatrix[dim - 1, dim - 1] = 1 def periodicConditions(dim, val): # Psi(0) = Psi(x) baseMatrix[0, 0] = val baseMatrix[dim - 1, dim - 1] = val
acos = _mathfun(math.acos, cmath.acos) asin = _mathfun(math.asin, cmath.asin) atan = _mathfun_real(math.atan, cmath.atan) cosh = _mathfun_real(math.cosh, cmath.cosh) sinh = _mathfun_real(math.sinh, cmath.sinh) tanh = _mathfun_real(math.tanh, cmath.tanh) floor = _mathfun_real( math.floor, lambda z: complex(math.floor(z.real), math.floor(z.imag))) ceil = _mathfun_real(math.ceil, lambda z: complex(math.ceil(z.real), math.ceil(z.imag))) cos_sin = _mathfun_real(lambda x: (math.cos(x), math.sin(x)), lambda z: (cmath.cos(z), cmath.sin(z))) cbrt = _mathfun(lambda x: x**(1. / 3), lambda z: z**(1. / 3)) def nthroot(x, n): r = 1. / n try: return float(x)**r except (ValueError, TypeError): return complex(x)**r def _sinpi_real(x): if x < 0: return -_sinpi_real(-x)
def planPath(boundaryPoints, pathDirection, gridSpacing, originPoint, pVal): ingressPt = 1 # pathDirection = "NorthSouth" # p = 0.6 p = pVal # gridSpacing = 0.5 # const = 20 m = 10**(-p + 1) # m = 0.1 xOrigin = originPoint[0] yOrigin = originPoint[1] # Close boundary path xBoundary = [] yBoundary = [] # for i in xrange(0, len(boundaryPoints)-1): for point in boundaryPoints: xBoundary.append(point[0]) yBoundary.append(point[1]) xBoundary.append(xBoundary[0]) yBoundary.append(yBoundary[0]) # Path for WP validation: originalBoundaryPath = path.Path(boundaryPoints) # Boundary points xvals = [] yvals = [] for i in range(1, len(xBoundary) - 1): xvals.extend( np.linspace(xBoundary[i - 1], xBoundary[i], 10 * gridSpacing)) yvals.extend( np.linspace(yBoundary[i - 1], yBoundary[i], 10 * gridSpacing)) xvals.extend(np.linspace(xvals[len(xvals) - 1], xvals[0], 10 * gridSpacing)) yvals.extend(np.linspace(yvals[len(yvals) - 1], yvals[0], 10 * gridSpacing)) # Z-plane (complex plane) Z = [] for i in xrange(0, len(xvals) - 1): tmpZ = (xvals[i] + yvals[i] * 1j) Z.append(tmpZ) # R = m|r|^p tempOrigin = xOrigin + yOrigin * 1j magR = [] angR = [] realR = [] imagR = [] R = [] for i in xrange(0, len(Z) - 1): magR.append(m * np.absolute(Z[i] - tempOrigin)**p) angR.append(np.angle(Z[i] - tempOrigin)) realR.append(magR[i] * cmath.cos(angR[i])) imagR.append(magR[i] * cmath.sin(angR[i])) R.append(realR[i] + imagR[i] * 1j) realR.append(magR[0] * cmath.cos(angR[0])) imagR.append(magR[0] * cmath.sin(angR[0])) transformedBoundaryPoints = [] for i in xrange(0, len(realR) - 1): transformedBoundaryPoints.append((realR[i].real, imagR[i].real)) transformedBoundaryPoints.append((realR[0].real, imagR[0].real)) transformedBoundaryPath = path.Path(transformedBoundaryPoints) # Create smallest rectangle encompassing points: rect = minimum_bounding_box(realR, imagR) # returns [xmin xmax ymin ymax] minGridVal = rect[0].real maxGridVal = rect[1].real if rect[2].real <= rect[0].real: minGridVal = rect[2].real if rect[3].real >= rect[1].real: maxGridVal = rect[3].real meshX = np.linspace(rect[0], rect[1], 50 * gridSpacing) # (maxGridVal - minGridVal)/gridSpacing)) meshY = np.linspace(rect[2], rect[3], 50 * gridSpacing) # (maxGridVal - minGridVal)/gridSpacing)) # Create meshgrid in bounding box: if pathDirection == "NorthSouth": gridY, gridX = np.meshgrid(meshY.real, meshX.real) elif pathDirection == "EastWest": gridX, gridY = np.meshgrid(meshX.real, meshY.real) # Find which points in meshgrid are in the polygon defined by boundary{oints: XY = np.dstack((gridX, gridY)) XY_flat = XY.reshape((-1, 2)) inOut_flat = transformedBoundaryPath.contains_points(XY_flat) inOut = inOut_flat.reshape(gridX.shape) # print "IN vs. OUT:" # print inOut xInGridPts = [i[0] for i in XY_flat[inOut_flat]] yInGridPts = [i[1] for i in XY_flat[inOut_flat]] Grid = [] for i in xrange(0, len(xInGridPts) - 1): Grid.append(xInGridPts[i] + yInGridPts[i] * 1j) # Lawnmower pattern: x_lawn = [xInGridPts[0]] y_lawn = [yInGridPts[0]] for i in xrange(1, len(xInGridPts) - 1): if pathDirection == "NorthSouth": if xInGridPts[i - 1] != xInGridPts[i]: x_lawn.append(xInGridPts[i - 1]) x_lawn.append(xInGridPts[i]) y_lawn.append(yInGridPts[i - 1]) y_lawn.append(yInGridPts[i]) elif pathDirection == "EastWest": if yInGridPts[i - 1] != yInGridPts[i]: x_lawn.append(xInGridPts[i - 1]) x_lawn.append(xInGridPts[i]) y_lawn.append(yInGridPts[i - 1]) y_lawn.append(yInGridPts[i]) for i in xrange(1, len(x_lawn) - 1, 4): tempFirstXValue = x_lawn[i - 1] tempSecondXValue = x_lawn[i] tempFirstYValue = y_lawn[i - 1] tempSecondYValue = y_lawn[i] x_lawn[i - 1] = tempSecondXValue x_lawn[i] = tempFirstXValue y_lawn[i - 1] = tempSecondYValue y_lawn[i] = tempFirstYValue x_lawnExtended = [] y_lawnExtended = [] for i in range(1, len(x_lawn) - 1): x_lawnExtended.extend( np.linspace( x_lawn[i - 1].real, x_lawn[i].real, 50 * gridSpacing)) # (maxGridVal - minGridVal)/gridSpacing)) y_lawnExtended.extend( np.linspace( y_lawn[i - 1].real, y_lawn[i].real, 50 * gridSpacing)) # (maxGridVal - minGridVal)/gridSpacing)) Lawn = [] for i in range(0, len(x_lawnExtended)): Lawn.append(x_lawnExtended[i].real + y_lawnExtended[i].real * 1j) # Boundary Back to Z-plane magZ = [] angZ = [] realZ = [] imagZ = [] for i in xrange(0, len(Z) - 1): magZ.append(((1 / m) * np.absolute(R[i]))**(1 / p)) angZ.append(np.angle(R[i])) realZ.append(magZ[i] * cmath.cos(angZ[i]) + xOrigin) imagZ.append(magZ[i] * cmath.sin(angZ[i]) + yOrigin) realZ.append(magZ[0] * cmath.cos(angZ[0])) imagZ.append(magZ[0] * cmath.sin(angZ[0])) # Convert grid back to real plane magGridZ = [] angGridZ = [] realGridZ = [] imagGridZ = [] for i in xrange(0, len(Grid) - 1): magGridZ.append(((1 / m) * np.absolute(Grid[i]))**(1 / p)) angGridZ.append(np.angle(Grid[i])) realGridZ.append(magGridZ[i] * cmath.cos(angGridZ[i]) + xOrigin) imagGridZ.append(magGridZ[i] * cmath.sin(angGridZ[i]) + yOrigin) # Convert lawnmower back to real plane magLawnZ = [] angLawnZ = [] realLawnZ = [] imagLawnZ = [] for i in xrange(0, len(Lawn) - 1): # dist = np.sqrt((Lawn[i].real - tempOrigin.real)**2 + (Lawn[i].imag - tempOrigin.imag)**2) dist = np.absolute(Lawn[i]) - np.absolute(tempOrigin) # dist = scipy.spatial.distance.euclidean(Lawn[i], tempOrigin) # assert np.isclose(distpat, dist) # if (p + dist < 1) and (p + dist > 0.7): # magLawnZ.append(((1 / m) * np.absolute(Lawn[i])) ** (1 / (p + dist))) # elif p + dist <= 0.7: # magLawnZ.append(((1 / m) * np.absolute(Lawn[i])) ** (1 / 0.7)) # else: # magLawnZ.append(((1 / m) * np.absolute(Lawn[i]))) magLawnZ.append(((1 / (m)) * np.absolute(Lawn[i]))**(1 / (p))) angLawnZ.append(np.angle(Lawn[i])) realLawnZ.append(magLawnZ[i].real * cmath.cos(angLawnZ[i].real) + xOrigin) imagLawnZ.append(magLawnZ[i].real * cmath.sin(angLawnZ[i].real) + yOrigin) waypoints = [] for i in xrange(0, len(realLawnZ) - 1): if (originalBoundaryPath.contains_point( [realLawnZ[i].real, imagLawnZ[i].real])): waypoints.append([realLawnZ[i].real, imagLawnZ[i].real]) return waypoints
from cmath import cos, pi, sin, sqrt j = sqrt(-1) print("Donner la racine nième\nTel que Z^n = 1") n = int(input("n = ")) print("Toutes les valeurs de solution de\nZ^" + str(n) + " = 1 sont :\n") for k in range(0, n): z = complex(cos((2*k*pi)/n),(sin((2*k*pi)/n))) alge = round(z.real, 1) + round(z.imag, 1) * 1j print("z" + str(k+1) + "= cos(" + str(2*k) + "pi/" + str(n) + ")+i*sin(" + str(2*k) + "pi/" + str(n) + ")\n = " + str(alge).replace("j", "i") + " \n") k += 1
def film_optical_coefficients(wavelength, thickness, n_film, n_substrate=0): """ Calculate the reflection, transmission, and absorption coefficients of a thin-film (possibly on a substrate). Parameters ---------- wavelength : float Wavelength of the incident radiation [nm]. thickness : float Thickness of the film [nm]. n_film : complex or float Complex refractive index of the film material. n_substrate : complex or float, optional Complex refractive index of the substrate material. Returns ------- R, T, A : float Reflection, transmission, and absorption coefficients, respectively. References ---------- .. [#] Tomlin, Brit. J. Appl. Phys. (J. Phys. D) ser. 2. vol. 1 1968 """ # Lengths in meters wavelength *= 10e-9 thickness *= 10e-9 n_film, n_subtrate = complex(n_film), complex(n_substrate) # Separate refractive index from absorption n0 = 1 # Vacuum n1, k1 = n_film.real, n_film.imag n2, k2 = n_substrate.real, n_substrate.imag # The following are simplifications based on a notebook by Martin R. Otto # See also Tomlin, Brit. J. Appl. Phys. (J. Phys. D) ser. 2. vol. 1 1968 g1 = (n0**2 - n1**2 - k1**2) / ((n0 + n1)**2 + k1**2) g2 = (n1**2 - n2**2 + k1**2 - k2**2) / ((n1 + n2)**2 + (k1 + k2)**2) h1 = 2 * n0 * k1 / ((n0 + n1)**2 + k1**2) h2 = 2 * (n1 * k2 - n2 * k1) / ((n1 + n2)**2 + (k1 + k2)**2) alpha1 = 2 * pi * k1 * thickness / wavelength gamma1 = 2 * pi * n1 * thickness / wavelength A = 2 * (g1 * g2 + h1 * h2) B = 2 * (g1 * h2 - g2 * h1) C1 = 2 * (g1 * g2 - h1 * h2) D1 = 2 * (g1 * h2 + g2 * h1) R = ((g1**2 + h1**2) * exp(2 * alpha1) + (g2**2 + h2**2) * exp(-2 * alpha1) + A * cos(2 * gamma1) + B * sin(2 * gamma1)) R /= (exp(2 * alpha1) + (g1**2 + h1**2) * (g2**2 + h2**2) * exp(-2 * alpha1) + C1 * cos(2 * gamma1) + D1 * sin(2 * gamma1)) R = R.real T = (n2 / n0) * ((1 + g1)**2 + h1**2) * ((1 + g2)**2 + h2**2) T /= (exp(2 * alpha1) + (g1**2 + h1**2) * (g2**2 + h2**2) * exp(-2 * alpha1) + C1 * cos(2 * gamma1) + D1 * sin(2 * gamma1)) T = T.real return R, T, 1 - R - T
def __new__(cls, argument): if isinstance(argument, (RealValue, Zero)): return FloatValue(math.cos(float(argument))) if isinstance(argument, (ComplexValue)): return ComplexValue(cmath.cos(complex(argument))) return MathFunction.__new__(cls)
def cos(x): if is_complex(x): return cmath.cos(x) return math.cos(x)