def calDCG(self, simM, label): print "calculate DCG ..." nCase = simM.shape[0] DCG = 0 for i in range(nCase) : labelI = label[i, 0] nLabeI = np.where(label == labelI)[0].size sortM = np.sort(simM[i, :]) index = [np.where(k == simM[i, :])[0].tolist()[0] for k in sortM] G = [] [G.append(int(k == labelI)) for k in label[index,0]] G = [G[j+1]*1.0/cmath.log(j+2, 2) for j, k in enumerate(G[1:])] DCGI = reduce(lambda x,y :x+y, G, 1) temp = [1.0/cmath.log(k,2) for k in range(2, nLabeI+1)] DCGZ = reduce(lambda x,y : x+y, temp, 1) DCG = DCG + DCGI*1.0/DCGZ DCG = DCG*1.0/nCase return DCG.real
def __init__(self, error_rate, elementNum): # 计算所需要的bit数 self.bit_num = -1 * elementNum * cmath.log(error_rate) / (cmath.log(2.0) * cmath.log(2.0)) # 四字节对齐 self.bit_num = self.align_4byte(self.bit_num.real) # 分配内存 self.bit_array = BitVector(size=self.bit_num) # 计算hash函数个数 self.hash_num = cmath.log(2) * self.bit_num / elementNum self.hash_num = self.hash_num.real # 向上取整 self.hash_num = int(self.hash_num) + 1 # 产生hash函数种子 self.hash_seeds = self.generate_hashseeds(self.hash_num)
def __init__(self, error_rate, elementNum): #计算所需要的 bit 数 self.bit_num = (-1) * elementNum * cmath.log(error_rate) / (cmath.log(2.0)) #四字节对齐 self.bit_num = self.align_4byte(self.bit_num.real) #chxfan: CBF needs 4 times that BF need self.bit_num = 4*self.bit_num print ('bit_num = %d' % self.bit_num) #分配内存 self.bit_array = BitVector(size=self.bit_num) #计算 hash 函数个数, only effected by error_rate self.hash_num = cmath.log(2) * self.bit_num / elementNum self.hash_num = self.hash_num.real #向上取整 self.hash_num = int(self.hash_num) + 1 print ('hash_num = %d' % self.hash_num) #产生 hash 函数种子 self.hash_seeds = self.generate_hashseeds(self.hash_num)
def fieldValue(self, z): temp = (z-self.z1)*exp(-self.theta*1j) x = self.length/temp v1 = np.conjugate(-1.0j/2/pi*((1.0/x - 1)*log(1-x) + 1))*exp(self.theta*1j) v2 = np.conjugate(1.0j/2/pi*((1.0/x)*log(1-x) + 1))*exp(self.theta*1j) return (v1*self.strength1 + v2*self.strength2)
def matAValue(self, z): temp = (z-self.z1)*exp(-self.theta*1j) x = self.length/temp v1 = -1.0j/2/pi*((1.0/x - 1)*log(1-x) + 1) v1 = (v1.imag) v2 = 1.0j/2/pi*((1.0/x)*log(1-x) + 1) v2 = (v2.imag) return v1+v2
def etaSm(self, z, escTime, itr,c): escTime = abs(escTime + 1 - (cmath.log( cmath.log(abs(z)) / cmath.log(2) ) / cmath.log(2))) return self.interpolate(escTime.real)
def test_logn(self): import math, cmath # log and log10 are tested in math (1:1 from rcomplex) from numpy import log2, array, log1p inf = float('inf') ninf = -float('inf') nan = float('nan') cmpl = complex log_2 = math.log(2) a = [cmpl(-5., 0), cmpl(-5., -5.), cmpl(-5., 5.), cmpl(0., -5.), cmpl(0., 0.), cmpl(0., 5.), cmpl(-0., -5.), cmpl(-0., 0.), cmpl(-0., 5.), cmpl(-0., -0.), cmpl(inf, 0.), cmpl(inf, 5.), cmpl(inf, -0.), cmpl(ninf, 0.), cmpl(ninf, 5.), cmpl(ninf, -0.), cmpl(ninf, inf), cmpl(inf, inf), cmpl(ninf, ninf), cmpl(5., inf), cmpl(5., ninf), cmpl(nan, 5.), cmpl(5., nan), cmpl(nan, nan), ] for c,rel_err in (('complex128', 2e-15), ('complex64', 1e-7)): b = log2(array(a,dtype=c)) for i in range(len(a)): try: _res = cmath.log(a[i]) res = cmpl(_res.real / log_2, _res.imag / log_2) except OverflowError: res = cmpl(inf, nan) except ValueError: res = cmpl(ninf, math.atan2(a[i].imag, a[i].real) / log_2) msg = 'result of log2(%r(%r)) got %r expected %r\n ' % \ (c,a[i], b[i], res) # cast untranslated boxed results to float, # does no harm when translated t1 = float(res.real) t2 = float(b[i].real) self.rAlmostEqual(t1, t2, rel_err=rel_err, msg=msg) t1 = float(res.imag) t2 = float(b[i].imag) self.rAlmostEqual(t1, t2, rel_err=rel_err, msg=msg) for c,rel_err in (('complex128', 2e-15), ('complex64', 1e-7)): b = log1p(array(a,dtype=c)) for i in range(len(a)): try: #be careful, normal addition wipes out +-0j res = cmath.log(cmpl(a[i].real+1, a[i].imag)) except OverflowError: res = cmpl(inf, nan) except ValueError: res = cmpl(ninf, 0) msg = 'result of log1p(%r(%r)) got %r expected %r\n ' % \ (c,a[i], b[i], res) # cast untranslated boxed results to float, # does no harm when translated t1 = float(res.real) t2 = float(b[i].real) self.rAlmostEqual(t1, t2, rel_err=rel_err, msg=msg) t1 = float(res.imag) t2 = float(b[i].imag) self.rAlmostEqual(t1, t2, rel_err=rel_err, msg=msg)
def test_faux_float(self): class Foo: def __float__(self): return 1.0 class Bar(object): def __float__(self): return 1.0 self.assertEqual(cmath.log(Foo()), 0.0) self.assertEqual(cmath.log(Bar()), 0.0)
def test_faux_complex(self): class Foo: def __complex__(self): return 1.0j class Bar(object): def __complex__(self): return 1.0j self.assertEqual(cmath.log(Foo()), cmath.log(1.0j)) self.assertEqual(cmath.log(Bar()), cmath.log(1.0j))
def unitary_lerp(u1, u2, t): """ Continuously interpolates between 2x2 unitary matrices, with unitary intermediates. :param u1: The initial unitary operation, used at t=0. :param u2: The final unitary operation, used at t=1. :param t: The interpolation factor, ranging from 0 to 1. >>> np.sum(np.abs((unitary_lerp(np.mat([[1, 0], [0, 1]]), np.mat([[1, 0], [0, 1]]) * 1j, 0.5) \ - np.mat([[1, 0], [0, 1]]) * trig_tau.expi(1/8)))) < 0.000001 True >>> (unitary_lerp(Rotation(x=0.5).as_pauli_operation(), Rotation(z=0.5).as_pauli_operation(), 0.5) \ == np.mat([[1,1],[1,-1]])/math.sqrt(2)).all() True >>> (unitary_lerp(Rotation(x=0.5).as_pauli_operation(), Rotation(x=0.5).as_pauli_operation(), 0.5) \ == Rotation(x=0.5).as_pauli_operation()).all() True >>> np.sum(np.abs(unitary_lerp(Rotation().as_pauli_operation(), Rotation(x=-0.25).as_pauli_operation(), 0.5) \ - Rotation(x=-0.125).as_pauli_operation())) < 0.000001 True >>> np.sum(np.abs(unitary_lerp(Rotation().as_pauli_operation(), Rotation(x=0.75).as_pauli_operation(), 0.5) \ - Rotation(x=-0.125).as_pauli_operation())) < 0.000001 True >>> np.sum(np.abs(unitary_lerp(Rotation().as_pauli_operation(), Rotation(x=0.25).as_pauli_operation(), 0.5) \ - Rotation(x=0.125).as_pauli_operation())) < 0.000001 True >>> np.sum(np.abs(unitary_lerp(Rotation().as_pauli_operation(), Rotation(x=0.5).as_pauli_operation(), 0.5) \ - Rotation(x=0.25).as_pauli_operation())) < 0.000001 True >>> np.sum(np.abs(unitary_lerp(Rotation(x=0.5).as_pauli_operation(), Rotation(x=0.75).as_pauli_operation(), 0.5) \ - Rotation(x=0.625).as_pauli_operation())) < 0.000001 True """ t1, x1, y1, z1, p1 = unitary_breakdown(u1) t2, x2, y2, z2, p2 = unitary_breakdown(u2) n1 = u1/p1 n2 = u2/p2 # Spherical interpolation of rotation part dot = Quaternion(t1, x1, y1, z1).dot(Quaternion(t2, x2, y2, z2)) if dot < 0: p2 *= -1 n2 *= -1 dot *= -1 theta = trig_tau.acos(max(min(dot, 1), -1)) c1 = trig_tau.sin_scale_ratio(theta, 1-t) c2 = trig_tau.sin_scale_ratio(theta, t) n3 = (n1*c1 + n2*c2) # Angular interpolation of phase part phase_angle_1 = cmath.log(p1).imag phase_angle_2 = cmath.log(p2).imag phase_drift = (phase_angle_2 - phase_angle_1 + math.pi) % trig_tau.tau - math.pi phase_angle_3 = phase_angle_1 + phase_drift * t p3 = cmath.exp(phase_angle_3 * 1j) return n3 * p3
def _lanczos(z): from cmath import pi, sin, log, exp if z.real < 0: return pi*z / (sin(pi*z) * _lanczos(-z)) else: x = _lanczos_coef[0] for i in range(1, 9): x += _lanczos_coef[i]/(z+i) logw = 0.91893853320467267+(z+0.5)*log(z+7.5)+log(x)-z-7.5 return exp(logw)
def __pow__(self, val): ad_funcs = [self, to_auto_diff(val)] # list(map(to_auto_diff, (self, val))) x = ad_funcs[0].x y = ad_funcs[1].x ######################################## # Nominal value of the constructed ADF: f = x**y ######################################## variables = self._get_variables(ad_funcs) if not variables or isinstance(f, bool): return f ######################################## # Calculation of the derivatives with respect to the arguments # of f (ad_funcs): if x.imag or y.imag: if abs(x)>0 and ad_funcs[1].d(ad_funcs[1])!=0: lc_wrt_args = [y*x**(y - 1), x**y*cmath.log(x)] qc_wrt_args = [y*(y - 1)*x**(y - 2), x**y*(cmath.log(x))**2] cp_wrt_args = x**(y - 1)*(y*cmath.log(x) + 1)/x else: lc_wrt_args = [y*x**(y - 1), 0.] qc_wrt_args = [y*(y - 1)*x**(y - 2), 0.] cp_wrt_args = 0. else: x = x.real y = y.real if x>0 and ad_funcs[1].d(ad_funcs[1])!=0: lc_wrt_args = [y*x**(y - 1), x**y*math.log(x)] qc_wrt_args = [y*(y - 1)*x**(y - 2), x**y*(math.log(x))**2] cp_wrt_args = x**y*(y*math.log(x) + 1)/x else: lc_wrt_args = [y*x**(y - 1), 0.] qc_wrt_args = [y*(y - 1)*x**(y - 2), 0.] cp_wrt_args = 0. ######################################## # Calculation of the derivative of f with respect to all the # variables (Variable) involved. lc_wrt_vars, qc_wrt_vars, cp_wrt_vars = _apply_chain_rule( ad_funcs, variables, lc_wrt_args, qc_wrt_args, cp_wrt_args) # The function now returns an ADF object: return ADF(f, lc_wrt_vars, qc_wrt_vars, cp_wrt_vars)
def droste_effect(zoom_center_pixel_coords, zoom_factor, zoom_cutoff, source_image_filename, out_x_size = None, twist = False, zoom_loop_value = 0.0, save_filename = "sphere_transforms_test.png"): """produces a zooming Droste effect image from an equirectangular source image""" # The source image should be a composite of the original image together with a zoomed version, # fit inside a picture frame or similar in the original image source_image = Image.open(source_image_filename) s_im = source_image.load() in_x_size, in_y_size = source_image.size M_rot = rotate_pixel_coords_p_to_q(zoom_center_pixel_coords, (0,0), x_size = in_x_size) M_rot_inv = matrix2_inv(M_rot) if out_x_size == None: out_x_size, out_y_size = source_image.size else: out_y_size = out_x_size/2 out_image = Image.new("RGB", (out_x_size, out_y_size)) o_im = out_image.load() droste_factor = ( cmath.log(zoom_factor) + complex(0, 2*pi) ) / complex(0, 2*pi) # used if twisting for i in range(out_x_size): for j in range(out_y_size): pt = (i,j) pt = angles_from_pixel_coords(pt, x_size = out_x_size) pt = sphere_from_angles(pt) pt = CP1_from_sphere(pt) pt = matrix_mult_vector(M_rot, pt) # if ever you don't know how to do some operation in complex projective coordinates, it's almost certainly # safe to just switch back to ordinary complex numbers by pt = pt[0]/pt[1]. The only danger is if pt[1] == 0, # or is near enough to cause floating point errors. In this application, you are probably fine unless you # make some very specific choices of where to zoom to etc. pt = pt[0]/pt[1] pt = cmath.log(pt) if twist: # otherwise straight zoom pt = droste_factor * pt # zoom_loop_value is between 0 and 1, vary this from 0.0 to 1.0 to animate frames zooming into the droste image pt = complex(pt.real + log(zoom_factor) * zoom_loop_value, pt.imag) # zoom_cutoff alters the slice of the input image that we use, so that it covers mostly the original image, together with # some of the zoomed image that was composited with the original. The slice needs to cover the seam between the two # (i.e. the picture frame you are using, but should cover as little as possible of the zoomed version of the image. pt = complex((pt.real + zoom_cutoff) % log(zoom_factor) - zoom_cutoff, pt.imag) pt = cmath.exp(pt) pt = [pt, 1] #back to projective coordinates pt = matrix_mult_vector(M_rot_inv, pt) pt = sphere_from_CP1(pt) pt = angles_from_sphere(pt) pt = pixel_coords_from_angles(pt, x_size = in_x_size) o_im[i,j] = get_interpolated_pixel_colour(pt, s_im, in_x_size) out_image.save(save_filename)
def fieldEffect(self,pos): """Velocity field due to this sheet on a pos""" z1=complex(self.x1[0],self.x1[1]) z2=complex(self.x2[0],self.x2[1]) zd=complex(pos[0],pos[1]) if (abs(z1-zd)<NODETOL) or (abs(z2-zd)<NODETOL): return(numpy.array([0.,0.])) z=(zd-z1)*(math.e**(-1j*self.theta)) pa1=self.gamma1*((((z/self.lemda)-1)*cmath.log((z-self.lemda)/z))+1) pa2=self.gamma2*((z/self.lemda*cmath.log((z-self.lemda)/z))+1) vel=1.j/2./math.pi*(pa1-pa2) vel=vel*(math.e**(-1j*self.theta)) return(numpy.array([vel.real,-vel.imag]))
def h(s, mq, mu): """Fermion loop function as defined e.g. in eq. (11) of hep-ph/0106067v2.""" if mq == 0.: return 8/27. + (4j*pi)/9. + (8 * log(mu))/9. - (4 * log(s))/9. if s == 0.: return -4/9. * (1 + log(mq**2/mu**2)) z = 4 * mq**2/s if z > 1: A = atan(1/sqrt(z-1)) else: A = log((1+sqrt(1-z))/sqrt(z)) - 1j*pi/2. return (-4/9. * log(mq**2/mu**2) + 8/27. + 4/9. * z -4/9. * (2 + z) * sqrt(abs(z - 1)) * A)
def arcinv(self, z, escTime, itr, c): z = (cmath.log( cmath.log(z) / cmath.log(2) ) / cmath.log(2)) r = abs(z.real) g = abs(z.imag) b = abs(z) rgb = [i for i in [r,g,b]] self.CSpace.setRGB(rgb) self.CSpace.rgb2hsv() self.CSpace.hsv[2] = sum(rgb)-self.CSpace.hsv[2] return [int(255*(2-i)/2)%256 for i in self.CSpace.hsv2rgb()]
def plot_log(nor_distribution): ''' Using normalized distribution to plot log/log graph ''' degree_list = sorted(nor_distribution.keys())[1:] value_list = [] for degree in degree_list: value_list.append(nor_distribution[degree]) degree_x = [log(item) for item in degree_list] value_y = [log(item) for item in value_list] plt.plot(degree_x, value_y, 'ro') plt.ylabel('log(distribution)') plt.xlabel('log(degree)') plt.show()
def __init__(self, error_rate, elementNum): self.bit_num = -1 * elementNum * cmath.log(error_rate) / (cmath.log(2.0) * cmath.log(2.0)) self.bit_num = self.align_4byte(self.bit_num.real) self.bit_array = BitVector(size=self.bit_num) self.hash_num = cmath.log(2) * self.bit_num / elementNum self.hash_num = self.hash_num.real self.hash_num = int(self.hash_num) + 1 self.hash_seeds = self.generate_hashseeds(self.hash_num)
def __init__(self, amount = 1 << 26): self.containerSize = (-1) * amount * cmath.log(0.001) / (cmath.log(2) * cmath.log(2)) #计算最佳空间大小 self.containerSize = int(self.containerSize.real) #取整 self.hashAmount = cmath.log(2) * (self.containerSize) / (amount) self.hashAmount = int(self.hashAmount.real) self.container = BitVector.BitVector(size = int(self.containerSize)) #分配内存 self.hashSeeds = find_prime(self.hashAmount) self.hash = [] for i in range(int(self.hashAmount)): #生成哈希函数 self.hash.append(SimpleHash(self.containerSize, self.hashSeeds[i])) return
def arg(complexe): if isinstance(complexe, (int, complex, long, float)): return _cmath.log(complexe).imag elif isinstance(complexe, _sympy.Basic): return _sympy.arg(complexe) else: return _numpy.imag(_numpy.log(complex))
def calcmsf(self, alpha, beta, transients=5, final=4000): """MSF ausrechnen. """ le = 0 self.params['alpha'] = alpha self.params['beta'] = beta system = neteqns(self.groups, self.H, self.T, self.eqns, params=self.params, coupling=self.coupling) system.update(neteqns(self.groups, self.H, self.T, self.vareqns, params=self.params, coupling=self.coupling, var=True)) # print system # debug for i in range(final): sdde = dde23(eqns=system, params=self.params, debug=False) sdde.set_sim_params(tfinal=self.params['tau']) if i==0: sdde.hist_from_arrays(self.__fillinitdict(self.transient, sdde.hist)) else: norm = self.__calcnorm(linsol) if i > transients: le += log(norm) sdde.hist_from_arrays(self.__renormalized(linsol, norm)) sdde.run() sol = sdde.sol linsol = sdde.sol_spl(self.resarray) exponent = le/((i-transients)*self.params['tau']) return exponent.real
def argand(base,save): screen=pygame.display.set_mode([xsize,ysize]) if base.imag==0: absv=int(abs(base.real)+0.5) else: absv= int(abs(base.real)**2+0.5) + int(abs(base.imag)**2+0.5) if absv>96: return if absv==1: raise Exception("No support for Base 1.") limit=int(absv**(int(cmath.log(2**19,absv).real))) checklist=[] screen.fill((0,0,0)) maxlen=len(decToBase(limit,absv)) for n in range(0,limit): oddBase=decToBase(n,absv) new=baseToDec(oddBase,base) #if new in checklist: # raise Exception('Too many digits! Repeated at %s'%new) #checklist+=[new] #print("%s \t = %s"%(oddBase, new)) l=len(decToBase(n,absv)) x,y=int(new.real), int(new.imag) cRatio=int((l+0.0)/maxlen*200)+55 screen.set_at((1*x+xsize/2,-1*y+ysize/2), (0,cRatio,cRatio)) new = "%s \t %s"%(new.real,new.imag) pygame.display.flip() if save: pygame.image.save(screen, "<%s + %si>[0,%s^%s].jpeg"%(base.real, base.imag, absv,cmath.log(limit,absv).real))
def clngamma(z): """The logarithm of the gamma function for a complex argument """ z = complex(z) # common case optimization n = floor(z.real) if n == z: if n <= 0: return complex(1.0 / 0.0) # Infinity elif n <= len(__factorial): return complex(__factorial[int(n) - 1]) zz = z if z.real < 0.5: zz = 1 - z g = __lanczos_gamma c = __lanczos_coefficients zz = zz - 1. zh = zz + 0.5 zgh = zh + g zp = zgh ** (zh * 0.5) # trick for avoiding FP overflow above z=141 ss = 0.0 for k in range(len(c) - 1, 0, -1): ss += c[k] / (zz + k) f = (sqrt_2pi * (c[0] + ss)) * ((zp * cm.exp(-zgh)) * zp) if z.real < 0.5: f = pi / (cm.sin(pi * z) * f) return cm.log(f)
def argand(base,save): screen=pygame.display.set_mode([xsize,ysize]) if base.imag==0: absv=int(abs(base.real)) else: absv=int( base.real**2 + base.imag**2 ) if absv>96: return limit=int(abs(absv**(int(cmath.log(2**16,absv).real)))) checklist=[] screen.fill((0,0,0)) maxlen=len(decToBase(limit,absv)) for n in range(limit): oddBase=decToBase(n,absv) new=baseToDec(oddBase,base) #print("%s: %s"%(oddBase,new)) #if new in checklist: # raise Exception("Two many digits") #checklist+=[new] l=len(decToBase(n,absv)) x,y=int(new.real), int(new.imag) #Represent complex point as 2x2 box on argand diagram pygame.draw.rect(screen,[0,int((l+0.0)/maxlen*200)+55,int((l+0.0)/maxlen*200)+55],[2*x+xsize/2,-2*y+ysize/2,2,2],0) new = "%s \t %s"%(new.real,new.imag) pygame.display.flip() if save: pygame.image.save(screen, "<%s + %si>[0,%s^%s].jpeg"%(base.real, base.imag, absv,cmath.log(limit,absv).real))
def cdigamma(z) : """Digamma function with complex arguments""" z = complex(z) g = __lanczos_gamma c = __lanczos_coefficients zz = z if z.real < 0.5 : zz = 1 -z n=0. d=0. for k in range(len(c)-1,0,-1): dz =1./(zz+(k+1)-2); dd =c[k] * dz d = d + dd n = n - dd * dz d = d + c[0] gg = zz + g - 0.5 f = cm.log(gg) + (n/d - g/gg) if z.real<0.5 : f -= pi / cm.tan( pi * z) return f
def log(a, b=math.e): if not is_num(a) or not is_num(b): raise BadTypeCombinationError(".l", a, b) if a < 0: return cmath.log(a, b) return math.log(a, b)
def Hestf(phi, kappa, theta, sigma, rho, v0, r, T, s0, Type, q): r = r-q if (Type == 1): u = 0.5 b = kappa - rho*sigma else: u = -0.5 b = kappa a = kappa*theta x = cm.log(s0) d = cm.sqrt((rho*sigma*phi*1j-b)**2-sigma**2*(2*u*phi*1j-phi**2)) g = (b-rho*sigma*phi*1j + d)/(b-rho*sigma*phi*1j - d) C = r*phi*1j*T + a/sigma**2*((b- rho*sigma*phi*1j + d)*T - 2*cm.log((1-g*cm.exp(d*T))/(1-g))) D = (b-rho*sigma*phi*1j + d)/sigma**2*((1-cm.exp(d*T))/(1-g*cm.exp(d*T))) return cm.exp(C + D*v0 + 1j*phi*x)
def log1p(x): if x == -1: return -inf elif isinstance(x, complex) or x < -1: return cmath.log(1 + x) else: return math.log1p(x)
def KL(a, b): if len(a) != len(b): return None result = 0 for x, y in zip(a, b): result += x * cmath.log(x/y) return result
def average(readings): base = e ** (1j * tau / 360) total = 0 for r in readings: total += r[1] * base ** r[0] result = total / len(readings) return (log(result, base).real, abs(result))
def root(n, x): if n == 0: return math.nan if x == 0 and n < 0: return math.nan if x < 0 and n % 2 == 0: return math.nan if x < 0: result = cmath.exp((1/n) * cmath.log(x) ) r = math.sqrt(round(math.pow(result.real, 2.0) + math.pow(result.imag, 2.0))) return -round(r) else: return math.pow(x, 1/n)
def do_func(self, funcstr, x): return eval( funcstr, { "x": x, "e": cmath.e, "pi": cmath.pi, "i": 1j, "exp": cmath.exp, "sin": cmath.sin, "cos": cmath.cos, "tan": cmath.tan, "sinh": cmath.sinh, "cosh": cmath.cosh, "tanh": cmath.tanh, "sec": lambda x: 1 / cmath.cos(x), "csc": lambda x: 1 / cmath.sin(x), "cot": lambda x: cmath.cos(x) / cmath.sin(x), "sech": lambda x: 1 / cmath.cosh(x), "csch": lambda x: 1 / cmath.sinh(x), "coth": lambda x: cmath.cosh(x) / cmath.sinh(x), "arcsin": cmath.asin, "arccos": cmath.acos, "arctan": cmath.atan, "arsinh": cmath.asinh, "arcosh": cmath.acosh, "artanh": cmath.atanh, "arcsec": lambda x: cmath.acos(1 / x), "arccsc": lambda x: cmath.asin(1 / x), "arccot": lambda x: cmath.atan(1 / x), "arsech": lambda x: cmath.acosh(1 / x), "arcsch": lambda x: cmath.asinh(1 / x), "arcoth": lambda x: cmath.atanh(1 / x), "abs": abs, "sgn": sign, "arg": cmath.phase, "cis": lambda x: cmath.cos(x) + 1j * cmath.sin(x), "pow": pow, "sqrt": cmath.sqrt, "nrt": lambda x, n: x**(1 / n), "log": cmath.log, "ln": lambda x: cmath.log(x), "floor": math.floor, "ceil": math.ceil, "trunc": math.trunc, "round": round, "gamma": math_gamma, "weierstrauss": math_weierstrauss, "choose": math_choose, "max": max, "min": min }, {})
def main(): start_clock = time.perf_counter() delta = 0.1 Z2 = 0 # Z2数 for kx in np.arange(-pi, 0, delta): print(kx) for ky in np.arange(-pi, pi, delta): H = hamiltonian(kx, ky) eigenvalue, eigenvector = np.linalg.eig(H) vector = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 价带波函数1 vector2 = eigenvector[:, np.argsort(np.real(eigenvalue))[1]] # 价带波函数2 H_delta_kx = hamiltonian(kx+delta, ky) eigenvalue, eigenvector = np.linalg.eig(H_delta_kx) vector_delta_kx = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离kx的波函数1 vector_delta_kx2 = eigenvector[:, np.argsort(np.real(eigenvalue))[1]] # 略偏离kx的波函数2 H_delta_ky = hamiltonian(kx, ky+delta) eigenvalue, eigenvector = np.linalg.eig(H_delta_ky) vector_delta_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离ky的波函数1 vector_delta_ky2 = eigenvector[:, np.argsort(np.real(eigenvalue))[1]] # 略偏离ky的波函数2 H_delta_kx_ky = hamiltonian(kx+delta, ky+delta) eigenvalue, eigenvector = np.linalg.eig(H_delta_kx_ky) vector_delta_kx_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离kx和ky的波函数1 vector_delta_kx_ky2 = eigenvector[:, np.argsort(np.real(eigenvalue))[1]] # 略偏离kx和ky的波函数2 Ux = dot_and_det(vector, vector_delta_kx, vector2, vector_delta_kx2) Uy = dot_and_det(vector, vector_delta_ky, vector2, vector_delta_ky2) Ux_y = dot_and_det(vector_delta_ky, vector_delta_kx_ky, vector_delta_ky2, vector_delta_kx_ky2) Uy_x = dot_and_det(vector_delta_kx, vector_delta_kx_ky, vector_delta_kx2, vector_delta_kx_ky2) F = np.imag(cmath.log(Ux*Uy_x*np.conj(Ux_y)*np.conj(Uy))) A = np.imag(cmath.log(Ux))+np.imag(cmath.log(Uy_x))+np.imag(cmath.log(np.conj(Ux_y)))+np.imag(cmath.log(np.conj(Uy))) Z2 = Z2 + (A-F)/(2*pi) print('Z2 = ', Z2) # Z2数 end_clock = time.perf_counter() print('CPU执行时间(min)=', (end_clock-start_clock)/60)
def average(readings): base = e ** (1j * tau / 360) total = 0 for r in readings: v = r[1] * base ** r[0] total += v arrow(0, 0, v.real, v.imag, head_width=0.05, head_length=0.05, fc='r', ec='r') result = total / len(readings) arrow(0, 0, result.real, result.imag, head_width=0.05, head_length=0.05, fc='b', ec='b') xlim((-1.5, 1.5)) ylim((-1.5, 1.5)) ylabel('Imaginary') xlabel('Real') return (cmath.log(result, base).real, abs(result))
def log(self, base=math.e): # TODO: is this correct? if not self.front: raise ValueError('cannot take log of 0') if self.leading < 0: raise ValueError('cannot take log of infinite') elif self.leading > 0: raise ValueError('cannot take log of infinitesimal') if isinstance(base, LeviCivitaBase): return self.log() / base.log() if base != math.e: return self.log() / cmath.log(base) series = (i * -1**(i - 1) for i in itertools.count()) return self._MATH.log(self.front) + self.eps_part().expand(series)
def _logarithmic_func(self) -> None: number: Union[float, complex] = self._number_on_screen self._operation_str_var.set("ln(x)") if isinstance(number, complex): self._number_screen.set(cmath.log(number)) else: if number > 0: self._number_screen.set(math.log(number)) else: self._number_screen.set("USE ONLY POSITIVE NUMBERS") self._reset_screen = True
def test10_math_explog(): for i in range(-5, 5): for j in range(-5, 5): if i != 0 or j != 0: a = ek.log(C(i, j)) b = C(cmath.log(complex(i, j))) assert ek.allclose(a, b) a = ek.log2(C(i, j)) b = C(cmath.log(complex(i, j)) / cmath.log(2)) assert ek.allclose(a, b) a = ek.exp(C(i, j)) b = C(cmath.exp(complex(i, j))) assert ek.allclose(a, b) a = ek.exp2(C(i, j)) b = C(cmath.exp(complex(i, j) * cmath.log(2))) assert ek.allclose(a, b) a = ek.pow(C(2, 3), C(i, j)) b = C(complex(2, 3)**complex(i, j)) assert ek.allclose(a, b)
def __init__(self, error_rate=0.001, elementNum=10000000, lock=None): #计算所需要的bit数 self.bit_num = -1 * elementNum * cmath.log(error_rate) / (cmath.log(2.0) * cmath.log(2.0)) #四字节对齐 self.bit_num = self.align_4byte(self.bit_num.real) #分配内存 self.bit_array = BitVector(size=self.bit_num) #计算hash函数个数 self.hash_num = cmath.log(2) * self.bit_num / elementNum self.hash_num = self.hash_num.real #向上取整 self.hash_num = int(self.hash_num) + 1 #产生hash函数种子 self.hash_seeds = self.generate_hashseeds(self.hash_num) #锁 self.lock = lock
def BM25(index, nfiles, docName, QueryWords, AVG_L, LD): score = 0 docName = str(docName) k1 = 1.2 b = 0.75 for word in QueryWords: if word not in index or docName not in index[word]: continue tf = len(index[word][docName]) df = len(index[word]) w = cmath.log(2, (nfiles - df + 0.5) / (df + 0.5)).real s = (k1 * tf * w) / (tf + k1 * (1 - b + b * LD[docName] / AVG_L)) score += s return score
def calcShannonent(dataSet): num_entyies = len(dataSet) labelCounts = {} for featvec in dataSet: currentLabel = featvec[-1] if currentLabel not in labelCounts.keys(): labelCounts[currentLabel] = 0 labelCounts[currentLabel] += 1 print(labelCounts) shannonEnt = 0.0 for key in labelCounts: prob = float(labelCounts[key]) / num_entyies shannonEnt -= prob * log(prob, 2) # log base 2 return shannonEnt
def testRLGCExtract(self): return sp = si.sp.SParameterFile('cableForRLGC.s2p') Z0 = 50 Tdest = 2.24e-9 fList = sp.m_f[1:] S11 = sp.Response(1, 1)[1:] S12 = sp.Response(1, 2)[1:] ra = [(s11 * s11 + 1 - s12 * s12) / (2 * s11) for (s11, s12) in zip(S11, S12)] rb = [ cmath.sqrt(s11 * s11 * s11 * s11 - 2 * s11 * s11 - 2 * s11 * s11 * s12 * s12 + 1 - 2 * s12 * s12 + s12 * s12 * s12 * s12) / (2 * s11) for (s11, s12) in zip(S11, S12) ] rho = [ra - rb for (ra, rb) in zip(ra, rb)] la = [(r * r - 1) / (2 * s12 * r * r) for (r, s12) in zip(rho, S12)] lb = [ cmath.sqrt(1 - 2 * r * r + r * r * r * r + 4 * s12 * s12 * r * r) / (2 * s12 * r * r) for (r, s12) in zip(rho, S12) ] Ls = [la + lb for (la, lb) in zip(la, lb)] Zc = [-Z0 * (r + 1) / (r - 1) for r in rho] gamma = [ -(cmath.log(l * cmath.exp(1j * 2 * math.pi * f * Tdest)) - 1j * 2 * math.pi * f * Tdest) for (l, f) in zip(Ls, fList) ] Y = [g / zc for (g, zc) in zip(gamma, Zc)] Z = [g * zc for (g, zc) in zip(gamma, Zc)] Rr = [abs(z.real) for z in Z] L = [z.imag / (2. * math.pi * f) for (z, f) in zip(Z, fList)] Gr = [abs(y.real) for y in Y] C = [y.imag / (2. * math.pi * f) for (y, f) in zip(Y, fList)] print(Zc) import matplotlib.pyplot as plt plt.clf() plt.title('s-parameter compare') plt.xlabel('frequency (GHz)') plt.ylabel('amplitude') plt.semilogy([f / 1e9 for f in fList], C, label='C') plt.semilogy([f / 1e9 for f in fList], L, label='L') plt.semilogy([f / 1e9 for f in fList], Rr, label='R') plt.semilogy([f / 1e9 for f in fList], Gr, label='G') plt.legend(loc='upper right') plt.grid(True) plt.show() (Rx, Rsex, Lx) = (matrix([[1., math.sqrt(f), 1j * 2 * math.pi * f] for f in fList]).getI() * matrix([[z] for z in Z])).tolist() print((Rx[0].real, Rsex[0].real, Lx[0].real))
def Heston_CharacteristicFunctionLogPrice(t, omega, S0, v0, r, kappa, theta, ksi, rho): alpha = complex(-omega**2 / 2, -omega / 2) beta = complex(kappa, -rho * ksi * omega) gamma = ksi**2 / 2 h = (beta**2 - 4 * alpha * gamma)**0.5 r_m = (beta - h) / ksi**2 r_p = (beta + h) / ksi**2 g = r_m / r_p C = kappa * (r_m * t - 2 * cpx.log( (1 - g * cpx.exp(-h * t)) / (1 - g)) / ksi**2) D = r_m * ((1 - cpx.exp(-h * t)) / (1 - g * cpx.exp(-h * t))) return cpx.exp( complex(C * theta + D * v0, omega * np.log(S0 * np.exp(r * t))))
def test_cmath_matches_math(self): # check that corresponding cmath and math functions are equal # for floats in the appropriate range # test_values in (0, 1) test_values = [0.01, 0.1, 0.2, 0.5, 0.9, 0.99] # test_values for functions defined on [-1., 1.] unit_interval = test_values + [-x for x in test_values] + \ [0., 1., -1.] # test_values for log, log10, sqrt positive = test_values + [1.] + [1. / x for x in test_values] nonnegative = [0.] + positive # test_values for functions defined on the whole real line real_line = [0.] + positive + [-x for x in positive] test_functions = { 'acos': unit_interval, 'asin': unit_interval, 'atan': real_line, 'cos': real_line, 'cosh': real_line, 'exp': real_line, 'log': positive, 'log10': positive, 'sin': real_line, 'sinh': real_line, 'sqrt': nonnegative, 'tan': real_line, 'tanh': real_line } for fn, values in test_functions.items(): float_fn = getattr(math, fn) complex_fn = getattr(cmath, fn) for v in values: z = complex_fn(v) if not due_to_ironpython_bug( "http://ironpython.codeplex.com/workitem/28352"): self.rAssertAlmostEqual(float_fn(v), z.real) self.assertEqual(0., z.imag) # test two-argument version of log with various bases for base in [0.5, 2., 10.]: for v in positive: z = cmath.log(v, base) self.rAssertAlmostEqual(math.log(v, base), z.real) self.assertEqual(0., z.imag)
def addNewEntry(position, isZero): entry = RootListEntry(entryFrame) entry.label.bind("<Button-1>", entrySelect) entry.pairButton.bind("<Button-1>", entryPair) entry.removeButton.bind("<Button-1>", entryRemove) # organize existing list of entries for entryIndex in range(0, len(entryFrame.winfo_children())): entryFrame.winfo_children()[entryIndex].grid(row = entryIndex) if (isZero): entryRoot = Zero(position) zPlaneRoot = DrawableZero(zPlaneComplex, entryRoot.getPosition()) sPlaneRoot = DrawableZero(sPlaneComplex, cmath.log(entryRoot.getPosition())) else: entryRoot = Pole(position) zPlaneRoot = DrawablePole(zPlaneComplex, entryRoot.getPosition()) sPlaneRoot = DrawablePole(sPlaneComplex, cmath.log(entryRoot.getPosition())) entry.label.config(text=repr(entryRoot.getPosition())) key = id(entry) entryDictionary[key] = EntryElements(zPlaneRoot, sPlaneRoot, entryRoot)
def poly_num_roots(f, Df, circle, N): '''poly_num_roots(f, f', A->B->.., N) == residue(f'/f, A->B->.., N) bug: if circle not convex or outside roots too near we can cut the z-plane into strikes by R+y*i for some real R. note that each root contribute to +/-pi over such line. sadly, log is not continue over all plane, we have to do numerial integrate. how to trace the change of angle???????????????? ''' Df_f = lambda z: Df(z) / f(z) circle = list(circle) i = 1 while i < len(circle): if circle[i - 1] != circle[i]: break i += 1 circle = circle[i - 1:] res = round(residue(Df_f, circle, N)) path = circle + circle[:1] # watch the change of angle of f(z), that is imag of log(f(z)) ss = [] for a, b in zip(path, path[1:]): L = b - a dL = L / N s = (f(a + L * t / N) for t in range(1, N + 1)) angles = (cmath.log(v).imag for v in s) ss.extend(angles) # angle counts ss.append(ss[0]) if ss[0] == 0 or ss[0] == 2 * math.pi: if len(circle) > 2 or len(circle) == 2 and N > 1: ss.append(ss[1]) #print('ss.append') #print('angles[0]=={}'.format(ss[0])) print('angles[:10]=={}'.format(ss[:10])) #print('angles[-10:]=={}'.format(ss[-10:])) num_roots1 = sum(a > b for a, b in zip(ss, ss[1:])) num_roots2 = len(ss) - num_roots1 num_roots = min(num_roots1, num_roots2) #num_roots = num_roots1 if num_roots != res: print('num_roots != res', num_roots, res) assert abs(num_roots - res) < 2 return num_roots
def F_87(Lmu, sh): """Function $F_8^{(7)}$ giving the contribution of $O_7$ to the matrix element of $O_8$, as given in eq. (40) of hep-ph/0312063. - `sh` is $\hat s=q^2/m_b^2$, """ flavio.citations.register("Asatrian:2003vq") if sh == 0.: return (-4 * (33 + 24 * Lmu + 6j * pi - 2 * pi**2)) / 27. return (-32 / 9. * Lmu + 8 / 27. * pi**2 - 44 / 9. - 8 / 9. * 1j * pi + (4 / 3. * pi**2 - 40 / 3.) * sh + (32 / 9. * pi**2 - 316 / 9.) * sh**2 + (200 / 27. * pi**2 - 658 / 9.) * sh**3 - 8 / 9. * log(sh) * (sh + sh**2 + sh**3))
def updateEntryPosition(entry, position): position = round(position.real, 5) + round(position.imag, 5) * 1j key = id(entry) entryDictionary[key].complexRoot.setPosition(position) position = entryDictionary[key].complexRoot.getPosition() zPlanePoint = position sPlanePoint = cmath.log(position) entryDictionary[key].zPlaneDrawable.setPosition(zPlanePoint) entryDictionary[key].sPlaneDrawable.setPosition(sPlanePoint) entry.label.config(text=repr(position))
def get_velocity(self, location): res = 0 for i in range(len(self.panel_points) - 1): p1 = self.panel_points[i] p2 = self.panel_points[i + 1] relative_vector = p2.location - p1.location t = (relative_vector) / abs(relative_vector) tc = t.conjugate() z = (location - p1.location) * tc uiv = (1j * p1.gamma * cmath.log(1 - (abs(relative_vector) / z))) / (2 * np.pi) uiv = uiv.conjugate() uiv = uiv * t res += uiv return res
def calcShannonEnt(dataSet): numEntries = len(dataSet) #数据集的个数 labelCounts = {} #存储每一类标签和出现的次数,为后面计算香农熵 for fentVec in dataSet: currentLabel = fentVec[-1] #最后一列作为标签 #labelCounts[currentLabel] = labelCounts.get(currentLabel,0) + 1 #这行代码可以由以下三行代替 if currentLabel not in labelCounts.keys(): labelCounts[currentLabel] = 0 labelCounts[currentLabel] += 1 shannonEnt = 0.0 #初始化香农熵 for key in labelCounts: prob = float(labelCounts[key] / numEntries) #每一类标签出现的概率 shannonEnt -= prob * (log(prob, 2)).real #计算信息熵 ,log函数返回的是实数+虚数的格式,2表示以2为底 return shannonEnt #熵越高混合的数据就越多
def complex_potential(self, z: complex) -> complex: """ Well's complex potential at location <z>. Return the well's contribution to the complex potential, Omega(z) [L^3/T], evaluated at location <z>. Arguments: z (complex): 'little z' world coordinate location [L]. Returns: complex: complex potential at location <z> [L^3/T]. Notes: - If the location <z> is inside the radius of the well, the complex potential at the radius of the well is returned. """ zz = z - self.z if abs(zz) >= self.r: Omega = self.Q / (2 * cmath.pi) * cmath.log(zz) else: Omega = self.Q / (2 * cmath.pi) * cmath.log(self.r) return Omega
def LogLikelihood(para, x_array): """ para: an array of Meixner parameters x_array: your observation array """ n = len(x_array) #number of your observation meixner = [Meixner(para, x_array[i]) for i in range(n)] #log likelihood function #LL=cmath.log(np.multiply.reduce(meixner)) #this may cause overflow single_LL = [cmath.log(i) for i in meixner if i.real > 0] LL = sum(single_LL) #LL=np.multiply.reduce(meixner) return -LL.real
def makeLocalExpansion(self, box): """Lemma 4.7 (Conversion of a multipole expansion into a local expansion)""" zo = (box.x-self.x) + (box.y-self.y)*1j # Equation 4.18 - calculating b0 self.bl[0] += box.ak[0]*log(-1.0*zo) for k in range(1,self.p): self.bl[0] += box.ak[k]*((-1.0)**k)/(zo**k) # Equation 4.19 - calculation bl for l in range(1,self.p): self.bl[l] += -1.0*box.ak[0]/(l*(zo**l)) tmp = 0.0 for k in range(1,self.p): tmp += ((box.ak[k])/(zo**k))*((-1.0)**k)*bincoeff(l+k-1,k-1) self.bl[l] += (1/(zo**l))*tmp return None
def calc(self): ''' Within this calculation the bypass ratio of the engine is determined from the engine diameter and the takeoff thurst of the engine. It is questionable whether this is a suitable approach as it probably breaks with the underlying statistic. :Source: Aircraft Design: A Conceptual Approach, D. P. Raymer, AIAA Education Series, 1992, Second Edition, p. 198, Eq. 10.6 ''' Tto = self.parent.thrustTO.getValue() d = self.parent.dEngine.getValue() return self.setValueCalc(0.25 * (log(d / Tto) + 5.351)) ################################################################################################### #EOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFE# ###################################################################################################
def ewlc(inp, p0, p1, p2, p3): # p0=Lk p1=Ks p2=Ns p3=Lc output_E = [] for f in inp: extension1 = p2 * (Lplanar / (np.exp(-deltaG / kT) + 1) + Lhelical / (np.exp(deltaG / kT) + 1)) * ( coth(p0 * f / kT) - kT / (p0 * f)) + p2 * f / p1 Q = 1 + f / K P = f / K + Lp * f / kT + 1 / 4 l = -2 * Q - P u = (-1 / 9) * (Lp * f / kT - 3 / 4)**2 v = (-1 / 27) * (Lp * f / kT - 3 / 4)**3 + (1 / 8) + 0.0000000000001 if (v**2 + u**3) < 0: theta = np.arccos(np.sqrt(-1 * v**2 / u**3)) if v < 0: result = extension1 + ( 2 * np.sqrt(-u) * np.cos(theta / 3 + 2 * np.pi / 3) - l / 3) * p3 else: result = extension1 + ( -2 * np.sqrt(-u) * np.cos(theta / 3 - 6 * np.pi / 3) - l / 3) * p3 else: A = cmath.exp( (1 / 3) * cmath.log(-v + np.sqrt(1 / 64 - 1 / 4 * complex( np.power((Lp * f / kT - 3 / 4) / 3, 3), 0)))) B = cmath.exp( (1 / 3) * cmath.log(-v - np.sqrt(1 / 64 - 1 / 4 * complex( np.power((Lp * f / kT - 3 / 4) / 3, 3), 0)))) E = -np.abs((A + B)) - l / 3 result = extension1 + E * p3 output_E.append(result) return output_E
def forward(self, x): with torch.no_grad(): def wf(psi, x): (a, b) = psi.forward(x) return cmath.exp(complex(a, b)) avg_psi = np.mean(np.array([wf(psi, x) for psi in self._machines])) avg_log_psi = cmath.log(avg_psi) x = torch.tensor( [avg_log_psi.real, avg_log_psi.imag], dtype=torch.float32, requires_grad=False, ) return x
def main(): start_clock = time.perf_counter() delta = 0.005 chern_number = 0 # 陈数初始化 # 几个坐标中常出现的项 a = 1/sqrt(3) aa1 = 4*sqrt(3)*pi/9/a aa2 = 2*sqrt(3)*pi/9/a bb1 = 2*pi/3/a hamiltonian0 = functools.partial(hamiltonian, M=2/3, t1=1, t2=1/3, phi=pi/4, a=a) # 使用偏函数,固定一些参数 for kx in np.arange(-aa1, aa1, delta): print(kx) for ky in np.arange(-bb1, bb1, delta): if (-aa2<=kx<=aa2) or (kx>aa2 and -(aa1-kx)*tan(pi/3)<=ky<=(aa1-kx)*tan(pi/3)) or (kx<-aa2 and -(kx-(-aa1))*tan(pi/3)<=ky<=(kx-(-aa1))*tan(pi/3)): # 限制在六角格子布里渊区内 H = hamiltonian0(kx, ky) eigenvalue, eigenvector = np.linalg.eig(H) vector = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 价带波函数 H_delta_kx = hamiltonian0(kx+delta, ky) eigenvalue, eigenvector = np.linalg.eig(H_delta_kx) vector_delta_kx = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离kx的波函数 H_delta_ky = hamiltonian0(kx, ky+delta) eigenvalue, eigenvector = np.linalg.eig(H_delta_ky) vector_delta_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离ky的波函数 H_delta_kx_ky = hamiltonian0(kx+delta, ky+delta) eigenvalue, eigenvector = np.linalg.eig(H_delta_kx_ky) vector_delta_kx_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离kx和ky的波函数 Ux = np.dot(np.conj(vector), vector_delta_kx)/abs(np.dot(np.conj(vector), vector_delta_kx)) Uy = np.dot(np.conj(vector), vector_delta_ky)/abs(np.dot(np.conj(vector), vector_delta_ky)) Ux_y = np.dot(np.conj(vector_delta_ky), vector_delta_kx_ky)/abs(np.dot(np.conj(vector_delta_ky), vector_delta_kx_ky)) Uy_x = np.dot(np.conj(vector_delta_kx), vector_delta_kx_ky)/abs(np.dot(np.conj(vector_delta_kx), vector_delta_kx_ky)) F = cmath.log(Ux*Uy_x*(1/Ux_y)*(1/Uy)) # 陈数(chern number) chern_number = chern_number + F chern_number = chern_number/(2*pi*1j) print('Chern number = ', chern_number) end_clock = time.perf_counter() print('CPU执行时间(min)=', (end_clock-start_clock)/60)
def laguer(coef, m, x): # Returns a single coefficient MAXIT = 80 MT = 10 EPSS = 1.0e-7 frac = [0.0, 0.5, 0.25, 0.75, 0.13, 0.38, 0.62, 0.88, 1.0] for iter in range(1, MAXIT+1): b = coef[m] err = abs(b) d = 0+0j f = 0+0j abx = abs(x) for j in range(m-1, -1, -1): f = d + x*f d = b + x*d b = coef[j] + x*b err = abs(b) + abx*err err *= EPSS if abs(b) <= err: return x g = d / b g2 = g * g h = g2 - 2.0*(f/b) sq = cmath.sqrt(float(m-1)*(m*h - g2)) gp = g + sq gm = g - sq abp = abs(gp) abm = abs(gm) if (abp < abm): gp = gm if max(abp, abm) > 0.0: dx = (m+0.0j) / gp else: dx = cmath.exp(cmath.log(1+abx)) * complex(math.cos(float(iter)), math.sin(float(iter))) x1 = x - dx if x.real == x1.real and x.imag == x1.imag: return x if iter % MT: x = x1 else: x = x - frac[iter/MT] * dx print "too many iterations in laguerre" return x
def cbrt(x): """cube root of x; does not return negative numbers Examples: ------------ >>> cbrt(-8) -2.0 >>> cbrt(8) 2.0 """ if isinstance(x, Real): return copysign(pow(abs(x), 1/3), x.real) elif isinstance(x, complex): return exp((1/3)*log(x)) else: raise TypeError('x must be a number')
def _get_complex_log_weight(self): """ Get the log weight even in cases where the determinant of the covariance matrix is negative. In such cases the log_weight no longer corresponds to the integral and the log of the weight will have a imaginary component. Computing the complex log-weight can however still be useful: it is used, for example, in the (experimental) Gaussian mixture division function (_gm_division_m2). :return: The potentially complex log weight :rtype: complex """ self._update_canform() cov = np.linalg.inv(self.prec) mean = cov @ self.h_vec ut_prec_u = (mean.T @ self.prec @ mean).astype(complex) log_weight = self.g_val + 0.5 * ut_prec_u + 0.5 * cmath.log(np.linalg.det(2.0 * np.pi * cov)) return log_weight
def find_z(p, q): #print(p,q) P = p**3 / 27 Q = q**2 / 4 R = Q + P if (abs(Q and R/Q or R)) < 1e-13: R = 0 if R < 0: # z^3 is complex, so z will be too (conjugate pair) z = exp(log(-q/2 + sqrt(R)) / 3) return z, z.conjugate() if R == 0: z = cuberoot(-q/2) return z, z rR = sqrt(R).real return cuberoot(-q/2+rR), cuberoot(-q/2-rR)