def quadratic_results(request): import math, cmath output_request = {} output_request['calculate'] = False if request.GET: temp_form = QuadraticForm(request.GET) if temp_form.is_valid(): output_request['calculate'] = True a = temp_form.cleaned_data['a'] b = temp_form.cleaned_data['b'] c = temp_form.cleaned_data['c'] output_request['D'] = b**2 - 4*a*c if output_request['D'] > 0: output_request['x1'] = float((-b + math.sqrt(output_request['D']))/(2*a)) output_request['x2'] = float((-b - math.sqrt(output_request['D']))/(2*a)) elif output_request['D'] == 0: output_request['x1'] = output_request['x2'] = float(-b / 2*a) elif output_request['D'] < 0: output_request['x1'] = complex((-b + cmath.sqrt(output_request['D']))/(2*a)) output_request['x2'] = complex((-b - cmath.sqrt(output_request['D']))/(2*a)) else: temp_form = QuadraticForm() output_request['form'] = temp_form return render(request,'quadratic/results.html',output_request)
def _n_Z(Omega, c10, Dt, loc_q, loc_ym, loc_yp, loc_alcc, loc_alss, loc_bsc, loc_bcs): arg1 = cmath.sqrt(2.0*loc_yp)/2.0/Dt/c10 arg2 = cmath.sqrt(2.0*loc_ym)/2.0/Dt/c10 return ((loc_alcc*cmath.cosh(arg1)*cmath.cosh(arg2) + loc_alss*cmath.sinh(arg1)*cmath.sinh(arg2) + loc_q)/ (loc_bsc*cmath.sinh(arg1)*cmath.cosh(arg2) + loc_bcs*cmath.cosh(arg1)*cmath.sinh(arg2)))
def soddy(triplet): """ Calcule le rayon et le centre du cercle de Soddy, en prenant en paramètre un triplet de cercle. :param triplet: list of three circles :type triplet: list :return: circle of soddy :rtype: tuple """ k1=1/triplet[0][2] k2=1/triplet[1][2] k3=1/triplet[2][2] k4=(k1+k2+k3)+(2*sqrt((k1*k2)+(k1*k3)+(k2*k3))) z1=complex(triplet[0][0], triplet[0][1]) z2=complex(triplet[1][0], triplet[1][1]) z3=complex(triplet[2][0], triplet[2][1]) z4=(z1*k1+z2*k2+z3*k3+2*cmath.sqrt(k1*k2*z1*z2+k2*k3*z2*z3+k1*k3*z1*z3))/k4 # on calcule la corbure k4 du cercle de soddy a=int(Distance(z4,z1)),int((triplet[0][2]+1/k4)),triplet[0][2] ,int(Distance(z4,z2)),int((triplet[1][2]+1/k4)),triplet[1][2],int(Distance(z4,z3)),int((triplet[2][2]+1/k4)), triplet[2][2] if int(Distance(z4,z1))==int((triplet[0][2]+1/k4)) and int(Distance(z4,z2))==int((triplet[1][2]+1/k4)) and int(Distance(z4,z3))==int((triplet[2][2]+1/k4)): return (z4.real,z4.imag,1/k4,True) else: #print(a) k1=-1/triplet[0][2] k4=(k1+k2+k3)+(2*sqrt((k1*k2)+(k1*k3)+(k2*k3))) z4=(z1*k1+z2*k2+z3*k3+2*cmath.sqrt(k1*k2*z1*z2+k2*k3*z2*z3+k1*k3*z1*z3))/k4 return (z4.real,z4.imag,1/k4,False)
def SeidelB(q2, mb, mu): """Function $A(s\equiv q^2)$ defined in eq. (30) of hep-ph/0403185v2. """ sh = q2/mb**2 z = (4 * mb**2)/q2 x1 = 1/2 + 1j/2 * sqrt(z - 1) x2 = 1/2 - 1j/2 * sqrt(z - 1) x3 = 1/2 + 1j/(2 * sqrt(z - 1)) x4 = 1/2 - 1j/(2 * sqrt(z - 1)) return ((8)/(243 * sh) * ((4 - 34 * sh - 17 * pi * 1j * sh) * log((mb**2)/(mu**2)) + 8 * sh * log((mb**2)/(mu**2))**2 + 17 * sh * log(sh) * log((mb**2)/(mu**2))) + ((2 + sh) * sqrt( z - 1))/(729 * sh) * (-48 * log((mb**2)/(mu**2)) * acot( sqrt(z - 1)) - 18 * pi * log(z - 1) + 3 * 1j * log(z - 1)**2 - 24 * 1j * li2(-x2/x1) - 5 * pi**2 * 1j + 6 * 1j * (-9 * log(x1)**2 + log(x2)**2 - 2 * log(x4)**2 + 6 * log(x1) * log(x2) - 4 * log(x1) * log(x3) + 8 * log(x1) * log(x4)) - 12 * pi * (2 * log(x1) + log(x3) + log(x4))) - (2)/(243 * sh * (1 - sh)) * (4 * sh * (-8 + 17 * sh) * (li2(sh) + log(sh) * log(1 - sh)) + 3 * (2 + sh) * (3 - sh) * log(x2/x1)**2 + 12 * pi * (-6 - sh + sh**2) * acot( sqrt(z - 1))) + (2)/(2187 * sh * (1 - sh)**2) * (-18 * sh * (120 - 211 * sh + 73 * sh**2) * log(sh) - 288 - 8 * sh + 934 * sh**2 - 692 * sh**3 + 18 * pi * 1j * sh * (82 - 173 * sh + 73 * sh**2)) - (4)/(243 * sh * (1 - sh)**3) * (-2 * sqrt( z - 1) * (4 - 3 * sh - 18 * sh**2 + 16 * sh**3 - 5 * sh**4) * acot( sqrt(z - 1)) - 9 * sh**3 * log(sh)**2 + 2 * pi * 1j * sh * (8 - 33 * sh + 51 * sh**2 - 17 * sh**3) * log( sh)) + (2)/(729 * sh * (1 - sh)**4) * (72 * (3 - 8 * sh + 2 * sh**2) * acot( sqrt(z - 1))**2 - pi**2 * (54 - 53 * sh - 286 * sh**2 + 612 * sh**3 - 446 * sh**4 + 113 * sh**5)) )
def lanczos(b, Amul, k, tol=1E-8): """Perform basic Lanczos Iteration given a starting vector 'b', a function 'Amul' representing multiplication by some matrix A, a number 'k' of iterations to perform, and a tolerance 'tol' to determine if the algorithm should stop early.""" # Some Initialization # We will use $q_0$ and $q_1$ to store the needed $q_i$ q0 = 0 q1 = b / sqrt(np.inner(b.conjugate(), b)) alpha = np.empty(k, dtype=complex) beta = np.empty(k) beta[-1] = 0. # Perform the iteration. for i in xrange(k): # z is a temporary vector to store q_{i+1} z = Amul(q1) alpha[i] = np.inner(q1.conjugate(), z) z -= alpha[i] * q1 z -= beta[i-1] * q0 beta[i] = sqrt(np.inner(z.conjugate(), z)).real # Stop if ||q_{j+1}|| is too small. if beta[i] < tol: return alpha[:i+1].copy(), beta[:i].copy() z /= beta[i] # Store new q_{i+1} and q_i on top of q0 and q1 q0, q1 = q1, z return alpha, beta[:-1]
def arnoldi(b, Amul, k, tol=1E-8): """Perform 'k' steps of the Arnoldi Iteration for sparse array 'A' and starting point 'b'with multiplicaiton function 'Amul'. Stop if the projection of a vector orthogonal to the current subspace has norm less than 'tol'.""" # Some initialization steps. # Initialize to complex arrays to avoid some errors. Q = np.empty((b.size, k+1), order='F', dtype=np.complex128) H = np.zeros((k+1, k), order='F', dtype=np.complex128) ritz_vals = [] # Set q_0 equal to b. Q[:,0] = b # Normalize q_0. Q[:,0] /= sqrt(np.inner(b.conjugate(), b)) # Perform actual iteration. for j in xrange(k): # Compute A.dot(q_j). Q[:,j+1] = Amul(Q[:,j]) # Modified Graham Schmidt for i in xrange(j+1): # Set values of $H$ H[i,j] = np.inner(Q[:,i].conjugate(), Q[:,j+1]) Q[:,j+1] -= H[i,j] * Q[:,i] # Set subdiagonel element of H. H[j+1,j] = sqrt(np.inner(Q[:,j+1].conjugate(), Q[:,j+1])) # Stop if ||q_{j+1}|| is too small. if abs(H[j+1, j]) < tol: # Here I'll copy the array to avoid excess memory usage. return np.array(H[:j,:j], order='F') # Normalize q_{j+1} Q[:,j+1] /= H[j+1, j] return H[:-1]
def find_opt_sn(source_g, sink_g, corr, mat, ts): mat_size, temp = mat[0].shape n_configs, n_types, t_size = corr.shape n_iter = 20 source = source_g sink = sink_g for n in range(n_iter): sigma2_source = np.matrix(np.zeros((mat_size, mat_size), dtype=np.complex128)) sigma2_sink = np.matrix(np.zeros((mat_size, mat_size), dtype=np.complex128)) for x in range(n_configs): c = np.matrix(np.zeros((mat_size, mat_size), dtype=np.complex128)) for y in range(n_types): c[math.floor(y/mat_size), y%mat_size] = corr[x, y, ts] sigma2_source += c * source * source.H * c.H sigma2_sink += c.H * sink * sink.H * c sigma2_source /= n_configs sigma2_sink /= n_configs inv_sigma2_source = np.linalg.inv(sigma2_source) inv_sigma2_sink = np.linalg.inv(sigma2_sink) a_source = (source.H * mat[ts].H * inv_sigma2_source * inv_sigma2_source * mat[ts] * source)[0,0] a_sink = (sink.H * mat[ts] * inv_sigma2_sink * inv_sigma2_sink * mat[ts].H * sink)[0,0] a_source = 1.0/cmath.sqrt(a_source) a_sink = 1.0/cmath.sqrt(a_sink) old_source = source old_sink = sink source = a_sink * inv_sigma2_sink * mat[ts].H * old_sink sink = a_source * inv_sigma2_source * mat[ts] * old_source # source = a_source * inv_sigma2_source * mat[ts] * old_source source /= cmath.sqrt((source.H * source)[0,0]) sink /= cmath.sqrt((sink.H * sink)[0,0]) # print('Iter '+str(n)+' '+ str((old_source.H * source)[0,0])+' '+str((old_sink.H * sink)[0,0])+' '+str((source.H * sink)[0,0])) return source, sink
def test_power_complex(self): x = blaze.array([1+2j, 2+3j, 3+4j]) assert_equal(x**0, [1., 1., 1.]) assert_equal(x**1, x) assert_almost_equal(x**2, [-3+4j, -5+12j, -7+24j]) assert_almost_equal(x**3, [(1+2j)**3, (2+3j)**3, (3+4j)**3]) assert_almost_equal(x**4, [(1+2j)**4, (2+3j)**4, (3+4j)**4]) assert_almost_equal(x**(-1), [1/(1+2j), 1/(2+3j), 1/(3+4j)]) assert_almost_equal(x**(-2), [1/(1+2j)**2, 1/(2+3j)**2, 1/(3+4j)**2]) assert_almost_equal(x**(-3), [(-11+2j)/125, (-46-9j)/2197, (-117-44j)/15625]) assert_almost_equal(x**(0.5), [cmath.sqrt(1+2j), cmath.sqrt(2+3j), cmath.sqrt(3+4j)]) norm = 1./((x**14)[0]) assert_almost_equal(x**14 * norm, [i * norm for i in [-76443+16124j, 23161315+58317492j, 5583548873 + 2465133864j]]) def assert_complex_equal(x, y): assert_array_equal(x.real, y.real) assert_array_equal(x.imag, y.imag) for z in [complex(0, np.inf), complex(1, np.inf)]: z = blaze.array([z], dshape="complex[float64]") assert_complex_equal(z**1, z) assert_complex_equal(z**2, z*z) assert_complex_equal(z**3, z*z*z)
def delay(omegaV, free): E_0 = -1.1591 E_m = [-0.8502, -0.3278, -0.1665] T = 3/0.02419 delta_m = np.zeros(np.size(E_m)) for j in (0, 1, 2): delta_m[j] = E_m[j] - E_0 optSize = np.size(omegaV) alpha1f = np.zeros(optSize, 'complex') alpha3f = np.zeros(optSize, 'complex') realFactor = np.zeros(optSize, 'complex') imagFactor = np.zeros(optSize, 'complex') T = 3 / 0.02419 for i in range(0, np.size(defs.omega_dip)-1): alpha1f[i] = dipole.constructDipole(omegaV[i], defsDipole.wf1) alpha3f[i] = dipole.constructDipole(omegaV[i], defsDipole.wf3) dawsArg1st = T*(delta_m[0] - omegaV) dawsArg3rd = T*(delta_m[1] - omegaV) realFactor = np.real((alpha1f * np.exp(-free*np.power(dawsArg1st,2.0)))\ + (alpha3f * np.exp(-np.sqrt(free)*np.power(dawsArg3rd, 2.0)))) imagFactor = (alpha1f * ((-2 * cmath.sqrt(-1))\ / (np.sqrt(np.pi))) * spcl.dawsn(free*dawsArg1st))\ + (alpha3f * ((-2 * cmath.sqrt(-1))\ / (np.sqrt(np.pi))) * spcl.dawsn(np.sqrt(free)*dawsArg3rd)) dE = np.gradient(omegaV) dIm = np.gradient(imagFactor, dE) dRe = np.gradient(realFactor, dE) derivFactor = (realFactor * dIm) - (np.imag(imagFactor * dRe)) zSquared = realFactor*realFactor + np.imag(imagFactor)*np.imag(imagFactor) ans = (realFactor * np.imag(dIm) - np.imag(imagFactor * dRe)) / zSquared return ans
def find_opt_sn(source_g, sink_g, mat, ts): n_configs, t_size, mat_size, temp = mat.shape av_mat = average(mat) n_iter = 20 source = np.matrix(source_g) sink = np.matrix(sink_g) for n in range(n_iter): sigma2_source = np.matrix(np.zeros((mat_size, mat_size), dtype=np.complex128)) sigma2_sink = np.matrix(np.zeros((mat_size, mat_size), dtype=np.complex128)) for x in range(n_configs): sigma2_source += np.matrix(mat[x, ts]) * source * source.H * np.matrix(mat[x, ts]).H sigma2_sink += np.matrix(mat[x, ts]).H * sink * sink.H * np.matrix(mat[x, ts]) sigma2_source /= float(n_configs) sigma2_sink /= float(n_configs) inv_sigma2_source = np.linalg.inv(sigma2_source) inv_sigma2_sink = np.linalg.inv(sigma2_sink) a_source = (source.H * np.matrix(av_mat[ts]).H * inv_sigma2_source * inv_sigma2_source * np.matrix(av_mat[ts]) * source)[0,0] a_sink = (sink.H * np.matrix(av_mat[ts]) * inv_sigma2_sink * inv_sigma2_sink * np.matrix(av_mat[ts]).H * sink)[0,0] a_source = 1.0/cmath.sqrt(a_source) a_sink = 1.0/cmath.sqrt(a_sink) old_source = source old_sink = sink source = a_sink * inv_sigma2_sink * np.matrix(av_mat[ts]).H * old_sink sink = a_source * inv_sigma2_source * np.matrix(av_mat[ts]) * old_source source /= cmath.sqrt((source.H * source)[0,0]) sink /= cmath.sqrt((sink.H * sink)[0,0]) # print('Iter '+str(n)+' '+ str((old_source.H * source)[0,0])+' '+str((old_sink.H * sink)[0,0])+' '+str((source.H * sink)[0,0])) return source, sink
def get_pfix_transformed(p0, x4Ns, h): """ Try to get the same result as the function in the kimura module. Change of variables according to eqn 3 of Chen et al. When I type (integral from 0 to p of exp(b*s*(x-a)**2) ) / (integral from 0 to 1 of exp(b*s*(x-a)**2) ) I get ( erfi(sqrt(b)*sqrt(s)*a) - erfi(sqrt(b)*sqrt(s)*(a-p)) ) / ( erfi(sqrt(b)*sqrt(s)*a) - erfi(sqrt(b)*sqrt(s)*(a-1)) ) @param p0: proportion of mutant alleles in the population @param x4Ns: 4Ns @return: fixation probability """ if not x4Ns: # This is the neutral case. return p0 if h == 0.5: # This is the genic case. # Checking for exact equality of 0.5 is OK. return math.expm1(-x4Ns*p0) / math.expm1(-x4Ns) b = 2.0 * h - 1.0 a = h / (2.0 * h - 1.0) q = cmath.sqrt(b) * cmath.sqrt(x4Ns) # top = kimura.erfi(q*a) - kimura.erfi(q*(a-p0)) bot = kimura.erfi(q*a) - kimura.erfi(q*(a-1)) return top / bot
def gFakeSPA(DA,E): """ An SPA thing that I worked out in Mathematica. Probably totally wrong.""" A = 1j*sqrt(1j/DA)*sqrt(E)/(sqrt(3.0*pi)*(t+0j)**(3.0/2.0)) #EQ = exp(sig*2*1j*abs(DA)*acos( -sqrt( 1 - E**2/t**2 ) ) ) return A#*EQ
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 condition_no(name): from math import sqrt h=0.001 f=[] fh=[] ab=[] conditi=[] x=list for x in nup.arange(-1,1.1,0.1): for y in nup.arange(-1,1.1,0.1): try: f.append(eval(name)) ab.append(sqrt(add(x**2,y**2))) except ValueError: pass for x in nup.arange(-1,1.1,0.1): try: x=x+h for y in nup.arange(-1,1.1,0.1): try: y=y+h fh.append(eval(name)) except ValueError: pass except ValueError: pass for num in range(0,len(f)): if f[num]!=0: D=abs(f[num])*sqrt(2)*h N=abs(fh[num]-f[num])*ab[num] conditi.append(N/D) else: conditi.append(None) return conditi
def get_pfix_transformed(p0, s_in, h): """ Try to get the same result as the function in the kimura module. Change of variables according to eqn 3 of Chen et al. When I type (integral from 0 to p of exp(b*s*(x-a)**2) ) / (integral from 0 to 1 of exp(b*s*(x-a)**2) ) I get ( erfi(sqrt(b)*sqrt(s)*a) - erfi(sqrt(b)*sqrt(s)*(a-p)) ) / ( erfi(sqrt(b)*sqrt(s)*a) - erfi(sqrt(b)*sqrt(s)*(a-1)) ) """ s = s_in * 2 b = 2.0 * h - 1.0 #XXX if not b: return float('nan') # transform h to alpha and beta, represented here by a and b a = h / (2.0 * h - 1.0) # intermediate parameter q = cmath.sqrt(b) * cmath.sqrt(s) # """ top = 2*q*cmath.exp(a*a*b*s) bot_a = kimura.erfi(q*(1-a)) bot_b = kimura.erfi(q*a) """ top = kimura.erfi(q*a) - kimura.erfi(q*(a-p0)) bot = kimura.erfi(q*a) - kimura.erfi(q*(a-1)) return top / bot
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 isqrt(c): if not isinstance(c,pol): return 1/math.sqrt(c) a0,p=c.separate(); p/=a0 lst=[1/math.sqrt(a0)] for n in range(1,c.order+1): lst.append(-lst[-1]/a0/2/n*(2*n-1)) return phorner(lst,p)
def solve_quadratic_equation(a, b, c, d=0.): c -= d D = b**2 - 4*a*c tmp = 2*a x1 = (-b - cmath.sqrt(D)) / tmp x2 = (-b + cmath.sqrt(D)) / tmp return x1, x2
def get_eigenvectors(Data, N): """ Function to get eigenvectors in LL and RR for each time or frequency ====params==== Data - Array with unpol visibilites N - Either number of frequencies or number of times on which to solve e-vec """ Gain_mat = np.zeros([n_ant, n_ant, N], np.complex128) for ant_i in range(n_ant): for ant_j in range(n_ant): if ant_i <= ant_j: Gain_mat[ant_i,ant_j,:] = Data[antmap(ant_i+1, ant_j+1, n_ant), :] Gain_mat[ant_j,ant_i,:] = np.conj(Data[antmap(ant_i+1, ant_j+1, n_ant), :]) #Should be Hermitian # Gain_mat[ant_j,ant_j,:] = 0 # Set autocorrelations to zero # Now try to find eigenvectors of 64x64 gainmatrices for all N gain_approx = np.zeros([n_ant, N, 2], np.complex128) for k in range(N): # Get the last two e-vals and e-vecs. Gain_mat should be rank 2 w, v = np.linalg.eigh(Gain_mat[:, :, k], UPLO='U') v1 = v[:,-1] / v[0,-1] v2 = v[:,-2] / v[0,-2] gain_approx[:, k, 0] = cmath.sqrt(w[-1]) * v1 / np.sqrt(abs(v1**2).sum()) gain_approx[:, k, 1] = cmath.sqrt(w[-2]) * v2 / np.sqrt(abs(v2**2).sum()) return gain_approx
def generate_quad(integer=False, real=True): if integer: root1 = random.randint(-10, 10) root2 = random.randint(-10, 10) b = root1 + root2 c = root1 * root2 return f"x^2 + {b}x + {c}" while True: b = random.randint(-25, 25) c = random.randint(-100, 100) root1 = (-b + cmath.sqrt(b**2 - 4*c)) / 2 root2 = (-b - cmath.sqrt(b**2 - 4*c)) / 2 if real and (root1.imag != 0 or root2.imag != 0): continue root1 = root1.real root2 = root2.real if abs(int(root1) - root1) < .01 or abs(int(root2) - root2) < .01: continue else: return f"x^2 + {b}x + {c}"
def calc(self): """ Surrogate model of a finite element analysis Limited to the following boundaries * wing.aspectRatio = 12. - 17. * wing.tcAVG = 0.08 - 0.13 * wing.twist = -4. - -10. * wing.phi25 = 5. - 20. * aircraft.mTOM = 60000. - 90000. * strut.etaStrut = 0.2 - 0.7 * strut.depth = 0.1 - 0.2 :Source: Boehnke, D., A Multi-Fidelity Workflow to Derive Physics-Based Conceptual Design Methods, TUHH, tbp. """ AR = self.parent.aircraft.wing.aspectRatio.getValue() S = self.parent.aircraft.wing.refArea.getValue() tc = self.parent.aircraft.wing.tcAVG.getValue() sw = self.parent.aircraft.wing.phi25.getValue() * pi / 180.0 mTOM = self.parent.aircraft.mTOM.getValue() c = self.parent.depth.getValue() eta = self.parent.etaStrut.getValue() res = ( 0.02061845578 * sw * mTOM + 87.70552679 * eta * c * sqrt(AR * S) + S * eta * c * sqrt(AR * S) - 21790.78072 * sw * tc * eta ) return self.setValueCalc(res)
def answer_question(self, event): print 'answer' red = (self.red_slider.value - self.color_entry[1]) / 255.0 green = (self.green_slider.value - self.color_entry[2]) / 255.0 blue = (self.blue_slider.value - self.color_entry[3]) / 255.0 # calculate distance from answer value distance = sqrt(red**2 + green**2 + blue**2) max_distance = sqrt(3) # calculate score score = (max_distance - distance) * sqrt(3) * 1000 / 3 self.target_score += int(score.real if score.real > 0 else 0) # schedule score increment Clock.schedule_interval(self.increment_score, 1.0/60) # show answer color and guess color with self.color_guess.canvas.before: Color(self.red_slider.value / 255.0, self.green_slider.value / 255.0, self.blue_slider.value / 255.0) Rectangle(pos=self.color_guess.pos, size=self.color_guess.size) with self.color_answer.canvas.before: Color(self.color_entry[1] / 255.0, self.color_entry[2] / 255.0, self.color_entry[3] / 255.0) Rectangle(pos=self.color_answer.pos, size=self.color_answer.size) # change answer button to next question self.guess_button.text = 'Next Question' self.guess_button.unbind(on_press=self.answer_question) self.guess_button.bind(on_press=self.create_question)
def soddy(triplet): """ Calcule le rayon et le centre du cercle de Soddy, en prenant en paramètre un triplet de cercle. :param triplet: list of three circles :type triplet: list :return: circle of soddy :rtype: tuple """ rayon = get_rayons(triplet) centre= get_centres(triplet) k2=1/rayon[1] k3=1/rayon[2] z1=complex(centre[0][0],centre[0][1]) z2=complex(centre[1][0],centre[1][1]) z3=complex(centre[2][0],centre[2][1]) # on calcule la corbure k4 du cercle de soddy if rayon[0]<rayon[1] and rayon[0]<rayon[2]: k1 = 1/rayon[0] k4 = (k1+k2+k3)+(2*sqrt((k1*k2)+(k1*k3)+(k2*k3))) # on récupére les centres des trois cercles # on calcule le centre du cercle de soddy sous forme d'un complexe z4 z4 = (z1*k1+z2*k2+z3*k3+2*cmath.sqrt(k1*k2*z1*z2+k2*k3*z2*z3+k1*k3*z1*z3))/k4 return ( z4.real, z4.imag, 1/k4) else: k1= -1/rayon[0] k4= (k1+k2+k3)+(2*sqrt((k1*k2)+(k1*k3)+(k2*k3))) # on récupére les centres des trois cercles # Idem que precedemment z4 = (z1*k1+z2*k2+z3*k3+2*cmath.sqrt(k1*k2*z1*z2+k2*k3*z2*z3+k1*k3*z1*z3))/k4 return (z4.real, z4.imag, 1/k4)
def cercle_soddy(triplet): """ Calculates the radius of the circle and the center of Soddy , taking in parameter triplet :param triplet: list of three circles (triplets) :type triplet: list :return: circle :rtype: tuple :UC: """ # on récupére les centres des trois cercles # on calcule le centre du cercle de soddy sous forme d'un complexe z4 k1 = 1 / triplet[0][2] k2 = 1 / triplet[1][2] k3 = 1 / triplet[2][2] k4 = (k1 + k2 + k3) + (2 * sqrt((k1 * k2) + (k1 * k3) + (k2 * k3))) z1 = complex(triplet[0][0], triplet[0][1]) z2 = complex(triplet[1][0], triplet[1][1]) z3 = complex(triplet[2][0], triplet[2][1]) z4 = (z1 * k1 + z2 * k2 + z3 * k3 + 2 * cmath.sqrt(k1 * k2 * z1 * z2 + k2 * k3 * z2 * z3 + k1 * k3 * z1 * z3)) / k4 # la condition verifie si la distance entre deux cercles est egale à la somme des deux rayons if ( int(Distance(z4, z1)) == int((triplet[0][2] + 1 / k4)) and int(Distance(z4, z2)) == int((triplet[1][2] + 1 / k4)) and int(Distance(z4, z3)) == int((triplet[2][2] + 1 / k4)) ): return (z4.real, z4.imag, 1 / k4) else: k1 = -1 / triplet[0][2] # la courbure du cercle qui contient les autres est negative k4 = (k1 + k2 + k3) + (2 * sqrt((k1 * k2) + (k1 * k3) + (k2 * k3))) z4 = ( z1 * k1 + z2 * k2 + z3 * k3 + 2 * cmath.sqrt(k1 * k2 * z1 * z2 + k2 * k3 * z2 * z3 + k1 * k3 * z1 * z3) ) / k4 return (z4.real, z4.imag, 1 / k4)
def P(k) : D1=D10 D2=D20 i = 1 while i < len(parlist): xi = parlist[i-1] r = k*pow(10,parlist[i]) xi1 = parlist[i+1] D1new = (D1*math.pi*(r*scipy.special.jv(1.5 + 1./xi, r/xi+0j)*scipy.special.yv(0.5 + 1./xi1, r/xi1+0j) - scipy.special.jv(0.5 + 1./xi, r/xi+0j)*((xi - xi1)*scipy.special.yv(0.5 + 1./xi1, r/xi1+0j) + r*scipy.special.yv(1.5 + 1./xi1, r/xi1+0j)))/(2*cmath.sqrt(xi*xi1)) - 1j*D2*math.pi*(-r*scipy.special.yv(1.5 + 1./xi, r/xi+0j)*scipy.special.yv(0.5 + 1./xi1, r/xi1+0j) + scipy.special.yv(0.5 + 1./xi, r/xi+0j)*((xi - xi1)*scipy.special.yv(0.5 + 1./xi1, r/xi1+0j) + r*scipy.special.yv(1.5 + 1./xi1, r/xi1+0j)))/(2*cmath.sqrt(xi*xi1))) D2new = (-1j*D1*math.pi*(-r*scipy.special.jv(1.5 + 1./xi, r/xi+0j)*scipy.special.jv(0.5 + 1./xi1, r/xi1+0j) + scipy.special.jv(0.5 + 1./xi, r/xi+0j)*((xi - xi1)*scipy.special.jv(0.5 + 1./xi1, r/xi1+0j) + r*scipy.special.jv(1.5 + 1./xi1, r/xi1+0j)))/(2*cmath.sqrt(xi*xi1)) + D2*math.pi*(r*scipy.special.jv(1.5 + 1./xi1, r/xi1+0j)*scipy.special.yv(0.5 + 1./xi, r/xi+0j) + scipy.special.jv(0.5 + 1./xi1, r/xi1+0j)*((xi - xi1)*scipy.special.yv(0.5 + 1./xi, r/xi+0j) - r*scipy.special.yv(1.5 + 1./xi, r/xi+0j)))/(2*cmath.sqrt(xi*xi1))) D1=D1new D2=D2new i+=2 # print D1,D2,xi,r,xi1 # return A * (k/k_0)**(n_s-1.) return A*pow(k,(2. - 2./xi1))*pow(abs(D2),2)
def myeig(M): """ compute eigen values and eigenvectors analytically Solve quadratic: lamba^2 - tau*lambda +/- Delta = 0 where tau = trace(M) and Delta = Determinant(M) if M = | a b | | c d | the trace is a+d and the determinant is a*d-b*c Return value is lambda1, lambda2 """ a,b = M[0,0], M[0,1] c,d = M[1,0], M[1,1] tau = a+d # the trace delta = a*d-b*c # the determinant lambda1 = (tau + cmath.sqrt(tau**2 - 4*delta))/2. lambda2 = (tau - cmath.sqrt(tau**2 - 4*delta))/2. return lambda1, lambda2
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 fib4(n): phi1 = (1+cmath.sqrt(5))/2. phi2 = (1-cmath.sqrt(5))/2. a = 1./cmath.sqrt(5) b = -1./cmath.sqrt(5) return a*(phi1**n) + b*(phi2**n)
def _get_xavier_weights(dim1, dim2, name=None, use_sigmoid=False): _high = cmath.sqrt(6) / cmath.sqrt(dim1 + dim2) _low = -_high if use_sigmoid: w = numpy.random.uniform(low=4 * _low, high=_high, size=(dim1, dim2)) else: w = numpy.random.uniform(low=_low, high=_high, size=(dim1, dim2)) return theano.shared(w.astype(DTYPE), name=name)
def middlebrook(a, b, c): try: q = math.sqrt(a*c)/b f = .5+ math.sqrt(1-4*q*q)/2 except ValueError: q = cmath.sqrt(a*c)/b f = .5+ cmath.sqrt(1-4*q*q)/2 return (-b/a)*f, -c/(b*f)
yy1=j flag=True break if(flag == True): break flag=False for i in range(GrabMat.shape[0]-1,0,-1): for j in range(GrabMat.shape[1]-1): if(GrabMat[i,j] !=0):#!=0 xx2=i yy2=j flag=True break if(flag == True): break height = cmath.sqrt((xx1-xx2)**2 + (yy1-yy2)**2) height = 0.3971*int(height.real) + 112.57# 調整比率 print('height:',height) #身高 height cv2.line(vis, (yy1, xx1), (yy2, xx2), (0,255,0)) cv2.imshow('line',vis) cv2.waitKey(1) StardredWight =( height-150)*0.6+50 #Area BodyArea =0 for i in range(GrabMat.shape[0]-1): for j in range(GrabMat.shape[1]-1): if(GrabMat[i,j] !=0):
def VecAbs(vector): return cmath.sqrt(vector[0] * vector[0] + vector[1] * vector[1] + vector[2] * vector[2]).real
def operation(num_one: str, oper: str, num_two: str) -> Union[int, float, complex]: """Takes two numbers in string format and performs specified input operation.""" try: num_one = float(num_one) except: num_one = complex(num_one) try: num_two = float(num_two) except: num_two = complex(num_two) operation_ans = 0 if oper == "^": operation_ans = num_one**num_two elif oper == "/": # Check if division by zero if div_check(num_one, num_two) == True: operation_ans = math.inf else: operation_ans = num_one / num_two elif oper == "*": operation_ans = num_one * num_two elif oper == "+": operation_ans = num_one + num_two elif oper == "-": operation_ans = num_one - num_two elif oper == "SIN": num_two = math.radians(num_two) operation_ans = round(math.sin(num_two), 7) elif oper == "COS": num_two = math.radians(num_two) operation_ans = round(math.cos(num_two), 7) elif oper == "TAN": num_two = math.radians(num_two) operation_ans = round(math.tan(num_two), 7) elif oper == "SEC": num_two = math.radians(num_two) if div_check(1, round(math.cos(num_two), 7)) == True: operation_ans = math.inf else: operation_ans = round(1 / math.cos(num_two), 7) elif oper == "CSC": num_two = math.radians(num_two) if div_check(1, round(math.sin(num_two), 7)) == True: operation_ans = math.inf else: operation_ans = round(1 / math.sin(num_two), 7) elif oper == "COT": num_two = math.radians(num_two) if div_check(1, round(math.tan(num_two), 7)) == True: operation_ans = math.inf else: operation_ans = round(1 / math.tan(num_two), 7) elif oper == "ASIN": operation_ans = math.asin(num_two) operation_ans = round(math.degrees(operation_ans), 7) elif oper == "ACOS": operation_ans = math.acos(num_two) operation_ans = round(math.degrees(operation_ans), 7) elif oper == "ATAN": operation_ans = math.atan(num_two) operation_ans = round(math.degrees(operation_ans), 7) elif oper == "ASEC": if div_check(1, num_two) == True: operation_ans = math.inf else: operation_ans = round(math.degrees(math.acos(1 / num_two)), 7) elif oper == "ACSC": if div_check(1, num_two) == True: operation_ans = math.inf else: operation_ans = round(math.degrees(math.asin(1 / num_two)), 7) elif oper == "ACOT": if div_check(1, num_two) == True: operation_ans = round(math.degrees(math.atan(math.inf)), 7) else: operation_ans = round(math.degrees(math.atan(1 / num_two)), 7) elif oper == "SINH": operation_ans = round(math.sinh(num_two), 7) elif oper == "COSH": operation_ans = round(math.cosh(num_two), 7) elif oper == "TANH": operation_ans = round(math.tanh(num_two), 7) elif oper == "SECH": if div_check(1, round(math.cosh(num_two), 7)) == True: operation_ans = math.inf else: operation_ans = round(1 / math.cosh(num_two), 7) elif oper == "CSCH": if div_check(1, round(math.sinh(num_two), 7)) == True: operation_ans = math.inf else: operation_ans = round(1 / math.sinh(num_two), 7) elif oper == "COTH": if div_check(1, round(math.tanh(num_two), 7)) == True: operation_ans = math.inf else: operation_ans = round(1 / math.tanh(num_two), 7) elif oper == "ASINH": operation_ans = round(math.asinh(num_two), 7) elif oper == "ACOSH": operation_ans = round(math.acosh(num_two), 7) elif oper == "ATANH": operation_ans = round(math.atanh(num_two), 7) elif oper == "ASECH": if div_check(1, num_two) == True: operation_ans = math.inf else: operation_ans = round(math.acosh(1 / num_two), 7) elif oper == "ACSCH": if div_check(1, num_two) == True: operation_ans = math.inf else: operation_ans = round(math.asinh(1 / num_two), 7) elif oper == "ACOTH": if div_check(1, num_two) == True: operation_ans = math.inf else: operation_ans = round(math.atanh(1 / num_two), 7) elif oper == "LN": operation_ans = math.log(num_two) elif oper == "LOG": operation_ans = math.log(num_two, num_one) elif oper == "SQRT": operation_ans = cmath.sqrt(num_two) return operation_ans
def solving_square_equation(a, b, c): x1 = (-b - cmath.sqrt(b**2 - 4 * a * c)) / 2 * a x2 = (-b + cmath.sqrt(b**2 - 4 * a * c)) / 2 * a return x1, x2
""" Original file iteration failed to function as the math sqrt function cannot handle negative values. Imported cmath to handle the problem. """ from cmath import sqrt a = 2 b = 1 c = 2 q = b**2 - 4 * a * c q_sr = sqrt(q) x1 = (-b + q_sr) / 2 * a x2 = (-b - q_sr) / 2 * a print(x1, x2)
import cmath a = int(input("Enter a value : ")) b = int(input("Enter b value : ")) c = int(input("Enter c value : ")) d = (b ** 2)-(4 * a * c) sol1 = (-b - cmath.sqrt(d) / (2*a)) sol2 = (-b + cmath.sqrt(d) / (2*c )) print("The solution is : {0} and {1} ".format(sol1,sol2))
def findSolutions(a, b, c): d = b*b - 4*a*c x1, x2 = (-b+sqrt(d))/2*a, (-b-sqrt(d))/2*a return [x1, x2] if x1 != x2 else [x1, '2-krotny']
def quadratic_eq(a, b, c): d = b**2 - 4 * a * c s1 = (b - cmath.sqrt(d)) / (2 * a) s2 = (-b - cmath.sqrt(d)) / (2 * a) return (s1, s2)
# Formula= ax^2+bx+c=0 #Code # import complex math module import cmath a = float(input('Enter a: ')) b = float(input('Enter b: ')) c = float(input('Enter c: ')) # calculate the discriminant d = (b**2) - (4*a*c) # find two solutions sol1 = (-b-cmath.sqrt(d))/(2*a) sol2 = (-b+cmath.sqrt(d))/(2*a) print('The solution are {0} and {1}'.format(sol1,sol2))
nq = 200000 prefix = 'TE'+str(tend) + '_a' + str(dx_mag) simulate = True plot = False restart = False restart_ts = 14 slow_factor = 1 ############################ Linear Analysis ################################## k2 = dx_mode**2 v2 = v**2 roots = [None,None,None,None] roots[0] = cm.sqrt(k2 * v2+ omega_p**2 + omega_p * cm.sqrt(4*k2*v2+omega_p**2)) roots[1] = cm.sqrt(k2 * v2+ omega_p**2 - omega_p * cm.sqrt(4*k2*v2+omega_p**2)) roots[2] = -cm.sqrt(k2 * v2+ omega_p**2 + omega_p * cm.sqrt(4*k2*v2+omega_p**2)) roots[3] = -cm.sqrt(k2 * v2+ omega_p**2 - omega_p * cm.sqrt(4*k2*v2+omega_p**2)) real_slope = roots[1].imag ############################ Setup and Run #################################### sim_params = {} beam1_params = {} loader1_params = {} beam2_params = {} loader2_params = {} mesh_params = {} mLoader_params = {} analysis_params = {}
print("hdhdhdh is " + repr (a) ) str(0.1) greeting='hello' greeting.count('h') print("hdhdhdh is %s " %a ) # In[254]: #复数 import cmath cmath.sqrt(-1) # In[246]: #保存并运行Python #以 .py 结尾 #运行 python hello.py #脚本首行 加上 #!/usr/bin/env python #在实际运行脚本之前,必须让脚本文件具有可执行属性 $chmod a+x hello.py # In[ ]: print str("hello world!")
theta_TM = list() theta = 0 wavelength_scan = np.linspace(0.5, 3.2, 201) ## dispersive I = np.identity(2 * num_ord + 1) indices = np.arange(-num_ord, num_ord + 1) spectra_R = [] spectra_T = [] # arrays to hold reflectivity and transmissitivity omega_p = 0.72 * np.pi * 1e15 gamma = 5e12 eps_r = eps_r.astype('complex') for wvlen in wavelength_scan: j = cmath.sqrt(-1) lam0 = wvlen k0 = 2 * np.pi / lam0 #free space wavelength in SI units omega = 2 * np.pi * 3e8 / lam0 * 1e6 epsilon_metal = 1 - omega_p**2 / (omega**2 + j * gamma * omega) #print(epsilon_metal) ## dispersive epsilon eps_r[0:border] = epsilon_metal ##construct convolution matrix E = convmat1D(eps_r, PQ) ## IMPORTANT TO NOTE: the indices for everything beyond this points are indexed from -num_ord to num_ord+1 ## FFT of 1/e; E_conv_inv = convmat1D(1 / eps_r, PQ)
def Fresn_Refl0(eps): # calculates Fresnel reflectivity at normal incidence. gamma0 = (abs((1 - cmath.sqrt(eps)) / (1 + cmath.sqrt(eps)))) ** 2 return(gamma0)
a = complex(1, 2) print(a.real) print(a.imag) print(a.conjugate()) b = 3 - 5j #a b两个复数进行运算 print(a + b) print(a * b) print(a / b) print(abs(a)) #要使用sin和cos等函数 可以引入cmath模块 import cmath print(cmath.sin(a)) print(cmath.cos(a)) print(cmath.exp(a)) print(cmath.sqrt(-1)) #使用一般无感知复数的模块 负数求平方根会直接报错 如下 import math # print(math.sqrt(-1)) #numpy模块 可以直接创建复数数组 import numpy as ny nyarr = ny.array([1 + 2j, 2 + 3j, 3 + 4j, 4 + 5j]) print(nyarr) print(nyarr + 2) print(ny.sin(nyarr))
def GSC(z): return 2.0 * (z + sqrt(1 - z**2) * (log(1 - z) - log(-1 + z)) / pi)
D = 11**2 - 4 * 28 if D < 0: print('Net korney') else: x1 = (11 + sqrt(D)) / 2 x2 = (11 - sqrt(D)) / 2 print(x1, x2, x1**2 - 11 * x1 + 28) #1.5 print('Zad 1.5') z1 = 1 / 3 * (3 - 5j) z2 = 1 + 2j print(z1 + z2, z1 * z2, z1**2 + z2**3, z1 / z2) #1.6 print('Zad 1.6') print(((2 + 1j) * (1 / 2 + 3j))**(-2), (1 - 2j) / (2 + 3j) - (3 + 1j) / 2j) #1.7 print('Zad 1.7') z1 = (1 + 1j)**15 / (1 - 1j)**9 z2 = (2 - 3j) * cmath.sqrt(-1 + 1j) z3 = (1 + 1j + 1j**2 + 1j**3)**10 print(cmath.polar(z1), cmath.polar(z2), cmath.polar(z3)) #1.8 print('Zad1.8') print(sin(1) * cmath.sin(1 + 1j) * sqrt(3) + cmath.sqrt(1 - 1j)) #1.9 print('Zad1.11') surname = input('Vvedite Familiju ') age = int(input('Vvedite Vozrast ')) mark = float(input('Vvedite ozenku ')) print('Familija:', surname, 'Vozrast:', age, 'Ozenka:', mark)
unorm = sqrt(sum([abs(u_[i])**2 for i in range(N)])) for i in range(N): u_[i] /= unorm ######################################################################### ## 开始第(2)小问 if __name__ == '__main__': x_max, dx = 2000, 0.1 Nx = int(x_max / dx) x = [dx * i for i in range(-Nx, Nx + 1)] # x的格点 # 初始化-1,0,1级对角 a = [0] + [-0.5 / dx**2 for i in range(len(x) - 1)] c = [-0.5 / dx**2 for i in range(len(x) - 1)] + [0] b = [ 1. / dx**2 - 1 / sqrt(((i - Nx) * dx)**2 + 2) + 0.48 for i in range(len(x)) ] lam, u = eigen_solver(a, b, c, [1 for i in range(len(x))]) # 求解! print('和 0.48 的偏差 ΔE = %.8f' % lam.real) unorm = sqrt(sum([abs(u[i])**2 for i in range(len(x))])) for i in range(len(x)): u[i] /= unorm u0 = u.copy() # 拷贝一下初始波函数 ## 以上是一样的内容:求初始的氢原子 1s 态波函数 ######################################################################### E0, Npulse = sqrt(1 / 3.5094448314), 18 ome = 1 T = 2 * Npulse * pi / ome
def checkIntersections(self) -> None: """ Check if any of the silkscreen intersects with pads, etc """ self.intersections = [] for graph in self.f_silk + self.b_silk: if "angle" in graph: # TODO pass elif "center" in graph: for pad in self.module.pads: padComplex = complex(pad["pos"]["x"], pad["pos"]["y"]) padOffset = 0 + 0j if "offset" in pad["drill"]: if "x" in pad["drill"]["offset"]: padOffset = complex(pad["drill"]["offset"]["x"], pad["drill"]["offset"]["y"]) edgesPad = {} edgesPad[0] = (complex(pad["size"]["x"] / 2.0, pad["size"]["y"] / 2.0) + padComplex + padOffset) edgesPad[1] = (complex(-pad["size"]["x"] / 2.0, -pad["size"]["y"] / 2.0) + padComplex + padOffset) edgesPad[2] = (complex(pad["size"]["x"] / 2.0, -pad["size"]["y"] / 2.0) + padComplex + padOffset) edgesPad[3] = (complex(-pad["size"]["x"] / 2.0, pad["size"]["y"] / 2.0) + padComplex + padOffset) vectorR = cmath.rect( 1, cmath.pi / 180 * pad["pos"]["orientation"]) for i in range(4): edgesPad[i] = (edgesPad[i] - padComplex) * vectorR + padComplex centerComplex = complex(graph["center"]["x"], graph["center"]["y"]) endComplex = complex(graph["end"]["x"], graph["end"]["y"]) radius = abs(endComplex - centerComplex) if "circle" in pad["shape"]: distance = radius + pad["size"]["x"] / 2.0 + 0.075 if abs(centerComplex - padComplex) < distance and abs( centerComplex - padComplex) > abs( -radius + pad["size"]["x"] / 2.0 + 0.075): self.intersections.append({ "pad": pad, "graph": graph }) else: # if there are edges inside and outside the circle, we have an intersection edgesInside = [] edgesOutside = [] for i in range(4): if abs(centerComplex - edgesPad[i]) < radius: edgesInside.append(edgesPad[i]) else: edgesOutside.append(edgesPad[i]) if edgesInside and edgesOutside: self.intersections.append({ "pad": pad, "graph": graph }) else: for pad in self.module.pads: # Skip checks on NPTH and Connect holes if pad["type"] in ["np_thru_hole", "connect"]: continue padComplex = complex(pad["pos"]["x"], pad["pos"]["y"]) padOffset = 0 + 0j if "offset" in pad["drill"]: if "x" in pad["drill"]["offset"]: padOffset = complex(pad["drill"]["offset"]["x"], pad["drill"]["offset"]["y"]) edgesPad = {} edgesPad[0] = (complex(pad["size"]["x"] / 2.0, pad["size"]["y"] / 2.0) + padComplex + padOffset) edgesPad[1] = (complex(-pad["size"]["x"] / 2.0, -pad["size"]["y"] / 2.0) + padComplex + padOffset) edgesPad[2] = (complex(pad["size"]["x"] / 2.0, -pad["size"]["y"] / 2.0) + padComplex + padOffset) edgesPad[3] = (complex(-pad["size"]["x"] / 2.0, pad["size"]["y"] / 2.0) + padComplex + padOffset) vectorR = cmath.rect( 1, cmath.pi / 180 * pad["pos"]["orientation"]) for i in range(4): edgesPad[i] = (edgesPad[i] - padComplex) * vectorR + padComplex startComplex = complex(graph["start"]["x"], graph["start"]["y"]) endComplex = complex(graph["end"]["x"], graph["end"]["y"]) if endComplex.imag > startComplex.imag: vector = endComplex - startComplex padComplex = padComplex - startComplex for i in range(4): edgesPad[i] = edgesPad[i] - startComplex else: vector = startComplex - endComplex padComplex = padComplex - endComplex for i in range(4): edgesPad[i] = edgesPad[i] - endComplex length = abs(vector) vectorR = cmath.rect(1, -cmath.phase(vector)) padComplex = padComplex * vectorR for i in range(4): edgesPad[i] = edgesPad[i] * vectorR if "circle" in pad["shape"]: distance = cmath.sqrt((pad["size"]["x"] / 2.0)**2 - (padComplex.imag)**2).real padMinX = padComplex.real - distance padMaxX = padComplex.real + distance else: edges = [ [0, 3], [0, 2], [2, 1], [1, 3], ] # lines of the rectangle pads x0 = [] # vector of value the x to y=0 for edge in edges: x1 = edgesPad[edge[0]].real x2 = edgesPad[edge[1]].real y1 = edgesPad[edge[0]].imag y2 = edgesPad[edge[1]].imag if y1 != y2: x = -y1 / (y2 - y1) * (x2 - x1) + x1 if x < max(x1, x2) and x > min(x1, x2): x0.append(x) if x0: padMinX = min(x0) padMaxX = max(x0) else: continue if ((padMinX < length and padMinX > 0) or (padMaxX < length and padMaxX > 0) or (padMaxX > length and padMinX < 0)): if "circle" in pad["shape"]: distance = pad["size"]["x"] / 2.0 padMin = padComplex.imag - distance padMax = padComplex.imag + distance else: padMin = min( edgesPad[0].imag, edgesPad[1].imag, edgesPad[2].imag, edgesPad[3].imag, ) padMax = max( edgesPad[0].imag, edgesPad[1].imag, edgesPad[2].imag, edgesPad[3].imag, ) try: differentSign = padMax / padMin except ZeroDivisionError: differentSign = padMin / padMax if ((differentSign < 0) or (abs(padMax) < 0.075) or (abs(padMin) < 0.075)): self.intersections.append({ "pad": pad, "graph": graph })
def matrix(self): return 1. / cmath.sqrt(2.) * np.matrix([[1, 1], [1, -1]])
def fix(self) -> None: """ Proceeds the fixing of the rule, if possible. """ module = self.module if self.check(): if self.refDesError: ref = self.module.reference if (self.checkReference() ): # @todo checkReference() does not return anything ref["value"] = "REF**" ref["layer"] = "F.SilkS" ref["font"]["width"] = KLC_TEXT_SIZE ref["font"]["height"] = KLC_TEXT_SIZE ref["font"]["thickness"] = KLC_TEXT_THICKNESS for graph in self.bad_width: graph["width"] = KLC_SILK_WIDTH for inter in self.intersections: pad = inter["pad"] graph = inter["graph"] if "angle" in graph: # TODO pass elif "center" in graph: # TODO pass else: padComplex = complex(pad["pos"]["x"], pad["pos"]["y"]) startComplex = complex(graph["start"]["x"], graph["start"]["y"]) endComplex = complex(graph["end"]["x"], graph["end"]["y"]) if endComplex.imag < startComplex.imag: startComplex, endComplex = endComplex, startComplex graph["start"]["x"] = startComplex.real graph["start"]["y"] = startComplex.imag graph["end"]["x"] = endComplex.real graph["end"]["y"] = endComplex.imag vector = endComplex - startComplex padComplex = padComplex - startComplex length = abs(vector) phase = cmath.phase(vector) vectorR = cmath.rect(1, -phase) padComplex = padComplex * vectorR distance = cmath.sqrt((pad["size"]["x"] / 2.0 + 0.226)**2 - (padComplex.imag)**2).real padMin = padComplex.real - distance padMax = padComplex.real + distance if 0 < padMin < length: if padMax > length: padComplex = (padMin + 0j) * cmath.rect( 1, phase) + startComplex graph["end"]["x"] = round(padComplex.real, 3) graph["end"]["y"] = round(padComplex.imag, 3) else: padComplex = (padMin + 0j) * cmath.rect( 1, phase) + startComplex graph2 = deepcopy(graph) graph["end"]["x"] = round(padComplex.real, 3) graph["end"]["y"] = round(padComplex.imag, 3) padComplex = (padMax + 0j) * cmath.rect( 1, phase) + startComplex graph2["start"].update( {"x": round(padComplex.real, 3)}) graph2["start"].update( {"y": round(padComplex.imag, 3)}) module.lines.append(graph2) elif padMin < 0 and 0 < padMax < length: padComplex = (padMax + 0j) * cmath.rect( 1, phase) + startComplex graph["start"]["x"] = round(padComplex.real, 3) graph["start"]["y"] = round(padComplex.imag, 3) elif padMax > length and padMin < 0: module.lines.remove(graph)
return Rvhpol[1] - 180 elif (Rvh.real > 0 and Rvh.imag < 0): return 360 - Rvhpol[1] else: return Rvhpol[1] #--------------------calculos de ejercicio------------------ r = complex(Er * (math.sin(y)), -(x * (math.sin(y)))) comp = complex(Er - (math.cos(y)**2), -x) Rv1 = ((r) - (cmath.sqrt(comp))) Rv2 = ((r) + (cmath.sqrt(comp))) Rv = (Rv1 / Rv2) Rvpol = cmath.polar(Rv) ang = correct_angle(Rv, Rvpol) rad = Rvpol[0] R1 = math.sqrt((d * 1000)**2 + (h1 - h2)**2) R2 = math.sqrt((d * 1000)**2 + (h1 + h2)**2) R2_R1 = (R2 - R1) angR = (360 / landa) * R2_R1
import numpy as np import matplotlib.pyplot as plt import cmath as cm m=int(input("enter value=")) k=int(input("enter number of samples for x[n]:")) a=[] for n in range(0,m-1): c=np.cos(2*np.pi*n/(m-1)) r=np.abs(0.54-0.5*c) a=np.append(a,r) N=1000 j=cm.sqrt(-1) X=[] w=np.linspace(-np.pi,np.pi,N) for i in range(0,N): s=0 for n in range(0,len(a)): s=s+(a[n]*np.exp(-n*w[i]*j)) X.append(s) print("X[n]=",np.abs(X)) plt.plot(w,np.abs(X)) plt.xlabel("freq(w/pi)") plt.ylabel("magnitude") plt.title("magnitude spectrum") plt.show()
print 'VTail Chord : ', AsUnit(Aircraft.VTail.Chord(0 * IN), 'in') print 'VTail Length : ', AsUnit(Aircraft.VTail.L, 'in') print print 'S&C PROPERTIES' print 'Steady state roll rate: ', AsUnit( Deriv.RollDueToAileron(15 * ARCDEG, 'Aileron'), 'deg/s') print 'Steady state pitch rate: ', Deriv.PitchResponseDueToElevator( 10 * ARCDEG, 1 * SEC, 'Elevator') * 180 / math.pi print 'Yaw Damping : ', Deriv.Np() print 'AVL Xnp : ', Deriv.Xnp, 'in' print 'Aircraft Xnp : ', AsUnit(Aircraft.Xnp(), 'in') #print 'Horizontal Tail incidence angle : ', AsUnit( Aircraft.HTail.i, 'deg' ) print print 'AVL Cma, Ma : ', Deriv.Cma, Ma print 'AVL Ma**0.5 : ', (-Ma)**0.5 print 'AVL sqrt(Ma) : ', math.sqrt(-Ma / (1 / SEC**2)) print 'AVL Cmq, Mq : ', Deriv.Cmq, Mq print 'AVL Madot : ', Madot print -((Mq + Madot) / (2 * (-Ma)**0.5)) print print 'Aircraft Cmadot : ', Aircraft.Cmadot() print 'Aircraft Cmq : ', Aircraft.Cmq() #print 'Spiral Mode: ', Deriv.SpiralMode() #print 'Spiral double time: ', Deriv.SpiralDoubleTime() #print 'AVL Clr : ', Deriv.Clr #print 'AVL Clb : ', Deriv.Clb #print 'AVL Cnr : ', Deriv.Cnr #print 'AVL Cnb : ', Deriv.Cnb endTime = time.time() # mark the end of the simulation
from matplotlib import pyplot as plt import numpy as np from cmath import sqrt #Physical constants e = 1.60217662e-19 epsilon_0 = 8.85e-12 j = sqrt(-1) k_B = 1.38064852e-23 def get_phi_scl_gaussian(x_list, mu, sigma, phi_0): return phi_0*np.exp(-np.power(x_list - mu, 2.) / (2 * np.power(sigma, 2.))) def get_second_derivative(array): array = np.diff(np.diff(array)) array = np.insert(array, 0, array[0]) array = np.append(array, array[-1]) return array/x_step_size**2 # def get_c_oh_scl(charge_density_per_formula_unit): # return charge_density_per_formula_unit + c_acc def get_c_oh_scl(gaussian_phi_scl): return c_oh_bulk*(1/np.exp((e*gaussian_phi_scl)/(k_B*T))) def get_z_scl(resistivity_scl): z_scl = [] for w in w_list: z_scl_at_w = np.sum((resistivity_scl*x_step_size)/(1 + j*w*resistivity_scl*epsilon_0*epsilon_r)) z_scl.append(z_scl_at_w)
print("ax" + SQUARED + " + bx + c = 0") a = get_float("enter a: ", False) b = get_float("enter b: ", True) c = get_float("enter c: ", True) if a%1 == 0: a = int(a) if b%1 == 0: b = int(b) if c%1 == 0: c = int(c) x1 = None x2 = None discriminant = (b ** 2) - (4 * a * c) if discriminant == 0: x1 = -(b / (2 * a)) else: if discriminant > 0: root = math.sqrt(discriminant) else: # discriminant < 0 root = cmath.sqrt(discriminant) x1 = (-b + root) / (2 * a) x2 = (-b - root) / (2 * a) equation = ("{a}x{SQUARED} {b:+}x {c:+} = 0 {ARROW} x = {x1}" .format(**locals())) if x2 is not None: equation += " or x = {0}".format(x2) print(equation) input('Press ENTER to exit')
tau = tauMin G = [] CR = [] tau_opt = 0.0 C_R_opt = 1000.0 # create file f = open("C_R.csv", 'w') f.close() # calculate C_R for different gamma values while (tau < tauMax): tmp = Lx for i in range(2, dampres + 2, 1): k[i] = cmath.sqrt((w**2) / (c**2) + (1j * w * tau * b(tmp + 0.5 * xd[i])) / ((c)**2)) tmp += xd[i] # calculate transmission and reflection coefficients for i in range( dampres, 0, -1 ): # go cell-by-cell from the end of the relaxation zone to its entrance. E.g. for 3 zones, start with zone 3, then 2, then 1. beta[i + 1] = fbeta(i + 1) Cr[i] = fCr(i) Ct[i] = fCt(i) # write reflection coefficients to file f = open("C_R.csv", 'a') f.write(str(tau * forcedEQs) + csv_file_separator + str(abs(Cr[1])) + "\n") G.append(tau * forcedEQs) CR.append(abs(Cr[1]))
def lambertw_branchpt(z): """Series for W(z, 0) around the branch point.""" a, b, c = -1.0 / 3.0, 1.0, -1.0 p = cmath.sqrt(2 * (cmath.e * z + 1)) return cevalpoly(a, b, c, 2, p)
'ord': ord, 'chr': chr, 'hex': hex, 'oct': oct, 'int': int, # direct imports 'e': math.e, 'pi': math.pi, 'atan2': math.atan2, 'fmod': math.fmod, 'frexp': math.frexp, 'hypot': math.hypot, 'ldexp': math.ldexp, 'modf': math.modf, # other nice-to-have constants 'j': cmath.sqrt(-1), # marshall between the math and cmath functions automatically 'acos': lambda x: which_call(x, math.acos, cmath.acos), 'asin': lambda x: which_call(x, math.asin, cmath.asin), 'atan': lambda x: which_call(x, math.atan, cmath.atan), 'cos': lambda x: which_call(x, math.cos, cmath.cos), 'cosh': lambda x: which_call(x, math.cosh, cmath.cosh), 'sin': lambda x: which_call(x, math.sin, cmath.sin), 'sinh': lambda x: which_call(x, math.sinh, cmath.sinh), 'tan': lambda x: which_call(x, math.tan, cmath.tan), 'tanh': lambda x: which_call(x, math.tanh, cmath.tanh), 'exp': lambda x: which_call(x, math.exp, cmath.exp), 'log10': lambda x: which_call(x, math.log10, cmath.log10, False), 'sqrt': lambda x: which_call(x, math.sqrt, cmath.sqrt, False), # functions defined here 'degrees': degrees,
[-omega**2 -3*gamma*y[0]**2 -2*eta*y[0]*y[1], -2*beta -eta*y[0]**2, p*np.cos(y[2])], [0, 0, 0]]) yd = np.array([y[1], -2*beta*y[1] -omega**2*y[0] -gamma*y[0]**3 -eta*y[0]**2*y[1] +p*np.sin(y[2]), Omega, J[0,0]*y[3] + J[0,1]*y[4] + J[0,2]*y[5], J[1,0]*y[3] + J[1,1]*y[4] + J[1,2]*y[5], J[2,0]*y[3] + J[2,1]*y[4] + J[2,2]*y[5]]) return yd #%% Parameters ### System parameters beta = 0.01 omega = sqrt(-0.5) gamma = 0.4 eta = 0.05 p = 0.2 Omega = 0.82 fn = 'Omega' + str(Omega).replace('.','_') par = [eta,gamma,p,omega,beta,Omega] parRef = ['eta','gamma','p','omega','beta','Omega'] ### Solving parameters nSys = 3 # Dimension of ODE nDiv = 100 # Cycles of 2.pi/Omega for determining time step spacing ### PERIODIC SOLUTION nSkipTransient = 300 # Cycles of transient to skip
import cmath a = int(input("Enter first factor : ")) b = int(input("Enter second factor: ")) c = int(input("Enter third factor: ")) d = b**2 - (4 * a * c) if (d < 0): print("no solution") elif (d == 0): x1 = -1 * b / (2 * a) print("Solution: " + str(x1)) else: x1 = (-1 * b - cmath.sqrt(d)) / (2 * a) x2 = (-1 * b + cmath.sqrt(d)) / (2 * a) print("Solution: " + str(x1) + ", " + str(x2))