当前位置: 首页>>代码示例>>Python>>正文


Python numpy.complex_函数代码示例

本文整理汇总了Python中numpy.complex_函数的典型用法代码示例。如果您正苦于以下问题:Python complex_函数的具体用法?Python complex_怎么用?Python complex_使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了complex_函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_init

    def test_init(self):
        import numpy as np
        import math
        import sys

        assert np.intp() == np.intp(0)
        assert np.intp("123") == np.intp(123)
        raises(TypeError, np.intp, None)
        assert np.float64() == np.float64(0)
        assert math.isnan(np.float64(None))
        assert np.bool_() == np.bool_(False)
        assert np.bool_("abc") == np.bool_(True)
        assert np.bool_(None) == np.bool_(False)
        assert np.complex_() == np.complex_(0)
        # raises(TypeError, np.complex_, '1+2j')
        assert math.isnan(np.complex_(None))
        for c in ["i", "I", "l", "L", "q", "Q"]:
            assert np.dtype(c).type().dtype.char == c
        for c in ["l", "q"]:
            assert np.dtype(c).type(sys.maxint) == sys.maxint
        for c in ["L", "Q"]:
            assert np.dtype(c).type(sys.maxint + 42) == sys.maxint + 42
        assert np.float32(np.array([True, False])).dtype == np.float32
        assert type(np.float32(np.array([True]))) is np.ndarray
        assert type(np.float32(1.0)) is np.float32
        a = np.array([True, False])
        assert np.bool_(a) is a
开发者ID:GaussDing,项目名称:pypy,代码行数:27,代码来源:test_scalar.py

示例2: fun

	def fun(self,t, args):
		"""Maximum likelihood function to be minimized.

		:param numpy_array t: t values.
		:param numpy_array args: first entry contains correlation counts, second the corresponding basis as string.
		:param numpy_array args: PSIs, all possible basis as Jones vectors.

		:return: Function value. See for further information D. F. V. James et al. Phys. Rev. A, 64, 052312 (2001).
		:rtype: numpy float
		"""
		corr_counts=args[0]
		basis=args[1]
		PSI=args[2]
		nbrOfElements=len(basis)

		rho_phys = self.rho_phys(t)

		#Estimate NormFactor
		estNormFactor=[]

		for i in range(len(corr_counts)):
			estNormFactor.append(np.dot(np.dot(np.conj(PSI[i]), rho_phys),PSI[i]))

		NormFactor=np.sum(corr_counts)/np.sum(estNormFactor)

		#Optimize density matrix
		BraRoh_physKet = np.complex_(np.zeros(nbrOfElements))

		for i in range(nbrOfElements):
			rhoket = np.array(np.dot(rho_phys,PSI[i]).flat) #Convert 2d to 1d array with flat
			BraRoh_physKet[i] = np.complex_(np.dot(np.conj(PSI[i]), rhoket))

		return np.real(np.sum((NormFactor*BraRoh_physKet-corr_counts)**2.0/(2.0*NormFactor*BraRoh_physKet)))
开发者ID:afognini,项目名称:Tomography,代码行数:33,代码来源:Tomography.py

示例3: test_init

 def test_init(self):
     import numpy as np
     import math
     import sys
     assert np.intp() == np.intp(0)
     assert np.intp('123') == np.intp(123)
     raises(TypeError, np.intp, None)
     assert np.float64() == np.float64(0)
     assert math.isnan(np.float64(None))
     assert np.bool_() == np.bool_(False)
     assert np.bool_('abc') == np.bool_(True)
     assert np.bool_(None) == np.bool_(False)
     assert np.complex_() == np.complex_(0)
     #raises(TypeError, np.complex_, '1+2j')
     assert math.isnan(np.complex_(None))
     for c in ['i', 'I', 'l', 'L', 'q', 'Q']:
         assert np.dtype(c).type().dtype.char == c
     for c in ['l', 'q']:
         assert np.dtype(c).type(sys.maxint) == sys.maxint
     for c in ['L', 'Q']:
         assert np.dtype(c).type(sys.maxint + 42) == sys.maxint + 42
     assert np.float32(np.array([True, False])).dtype == np.float32
     assert type(np.float32(np.array([True]))) is np.ndarray
     assert type(np.float32(1.0)) is np.float32
     a = np.array([True, False])
     assert np.bool_(a) is a
开发者ID:abhinavthomas,项目名称:pypy,代码行数:26,代码来源:test_scalar.py

示例4: fft_deriv

def fft_deriv ( var ):
    #on_error, 2
                 
    n = numpy.size(var)

    F = old_div(numpy.fft.fft(var),n)  #different definition between IDL - python
                 
    imag = numpy.complex(0.0, 1.0)
    imag = numpy.complex_(imag)

    F[0] = 0.0
          
                
    if (n % 2) == 0 :
      # even number
        for i in range (1, old_div(n,2)) :
          a = imag*2.0*numpy.pi*numpy.float(i)/numpy.float(n)
          F[i] = F[i] * a         # positive frequencies
          F[n-i] = - F[n-i] * a   # negative frequencies
           
        F[old_div(n,2)] = F[old_div(n,2)] * (imag*numpy.pi)
    else:
      # odd number
        for i in range (1, old_div((n-1),2)+1) :
          a = imag*2.0*numpy.pi*numpy.float(i)/numpy.float(n)
          F[i] = F[i] * a
          F[n-i] = - F[n-i] * a 
        
    

    result = numpy.fft.ifft(F)*n  #different definition between IDL - python
    
      
    return result 
开发者ID:JosephThomasParker,项目名称:BOUT-dev,代码行数:34,代码来源:fft_deriv.py

示例5: test_gamma

	def test_gamma(self,gamma):
		"""Test if :math:`\Gamma_i, {i=1,...,16}` matrices are properly defined.

		:param array GAMMA: Gamma matrices.

		Test for:

			:math:`\mathrm{Tr}(\Gamma_i\Gamma_j)= \delta_{i,j}`

		:return: True if equation fullfilled for all gamma matrices, False otherwise.
		:rtype: bool
		"""

		#initialize empty test matrix
		test_matrix = np.complex_(np.zeros((16,16)))

		for i in range(len(gamma)):
			for j in range(len(gamma)):
				test_matrix[i,j] = np.trace(np.dot(gamma[i], gamma[j]))

		diag_matrix = np.diag(np.ones(16))


		test_result = np.einsum('ij,ij',test_matrix - diag_matrix, test_matrix - diag_matrix)-16

		if np.abs(test_result) < 10**-6:
			return True
		else:
			False
开发者ID:afognini,项目名称:Tomography,代码行数:29,代码来源:Tomography.py

示例6: __new__

 def __new__(cls, x=0):
     if isinstance(x, afnumpy.ndarray):
         return x.astype(cls)
     elif isinstance(x, numbers.Number):
         return numpy.complex_(x)
     else:
         return afnumpy.array(x).astype(cls)
开发者ID:Brainiarc7,项目名称:afnumpy,代码行数:7,代码来源:dtypes.py

示例7: test_against_cmath

    def test_against_cmath(self):
        import cmath, sys

        # cmath.asinh is broken in some versions of Python, see
        # http://bugs.python.org/issue1381
        broken_cmath_asinh = False
        if sys.version_info < (2, 6):
            broken_cmath_asinh = True

        points = [-1 - 1j, -1 + 1j, +1 - 1j, +1 + 1j]
        name_map = {
            "arcsin": "asin",
            "arccos": "acos",
            "arctan": "atan",
            "arcsinh": "asinh",
            "arccosh": "acosh",
            "arctanh": "atanh",
        }
        atol = 4 * np.finfo(np.complex).eps
        for func in self.funcs:
            fname = func.__name__.split(".")[-1]
            cname = name_map.get(fname, fname)
            try:
                cfunc = getattr(cmath, cname)
            except AttributeError:
                continue
            for p in points:
                a = complex(func(np.complex_(p)))
                b = cfunc(p)

                if cname == "asinh" and broken_cmath_asinh:
                    continue

                assert_(abs(a - b) < atol, "%s %s: %s; cmath: %s" % (fname, p, a, b))
开发者ID:jarrodmillman,项目名称:numpy,代码行数:34,代码来源:test_umath.py

示例8: halo_transform

def halo_transform(image):

    na=image.shape[0]
    nb=image.shape[1]
    ko= 5.336
    delta = (2.*np.sqrt(-2.*np.log(.75)))/ko

    x=np.arange(nb)
    y=np.arange(na)
    x,y=np.meshgrid(x,y)
    if (nb % 2) == 0:
        x=(1.*x - (nb)/2.)/nb
        shiftx = (nb)/2.
    else:
       x= (1.*x - (nb-1)/2.)/nb 
       shiftx=(nb-1.)/2.+1

    if (na % 2) == 0:
        y=(1.*y-(na/2.))/na
        shifty=(na)/2.
    else:
        y= (1.*y - (na-1)/2.)/ na
        shifty=(na-1.)/2.+1

    #--------------Spectral Logarithm--------------------
    M=int(np.log(nb)/delta)
    a2= np.zeros(M)
    a2[0]=np.log(nb)

    for i in range(M-1):
        a2[i+1]=a2[i]-delta

    a2=np.exp(a2)
    tab_k = 1. / (a2)
    wt= np.complex_(np.zeros(((na,nb,M))))


    a= ko*a2

    imageFT= np.fft.fft2(image)
    #imageFT=np.fft.fftshift(image)
    imageFT= np.roll(imageFT,int( shiftx), axis=1)
    imageFT= np.roll(imageFT,int(shifty), axis=0)

    for j in range(M):
        uv = 0

        uv=np.exp(-0.5*((abs(a[j]*np.sqrt(x**2.+y**2.))**2.  - abs(ko))**2.))

        uv = uv * a[j]

        W1FT=imageFT*(uv)
        W1F2=np.roll(W1FT,int(shiftx), axis =1)
        W1F2=np.roll(W1F2,int(shifty),axis=0)
       #W1F2=np.fft.ifftshift(W1FT)
        W1=np.fft.ifft2(W1F2)
        wt[:,:,j]=wt[:,:,j]+ W1

    return wt, tab_k
开发者ID:ArloParker,项目名称:SummerProject2016,代码行数:59,代码来源:halo_transform.py

示例9: test_params_to_array_inconsistent_types

 def test_params_to_array_inconsistent_types(self):
     """
     Tests if an assertion error is raised when parameters of different
     types are passed in
     """
     guess_params_adj = self.guess_params
     guess_params_adj[-1] = np.complex_(guess_params_adj[-1])
     self.assertRaises(AssertionError, self.affine_obj.params_to_array,
                       guess_params_adj)
开发者ID:bartbkr,项目名称:affine,代码行数:9,代码来源:test_model.py

示例10: test_opt_gen_pred_coef_complex

 def test_opt_gen_pred_coef_complex(self):
     """
     Tests if complex values are return properly
     """
     # DOC: Need to make sure that the arrays are also np.complex
     guess_params = [np.complex_(el) for el in self.guess_params]
     params = self.affine_obj.params_to_array(guess_params)
     arrays_gpc = self.affine_obj.opt_gen_pred_coef(*params)
     for array in arrays_gpc:
         self.assertEqual(array.dtype, np.complex_)
开发者ID:bartbkr,项目名称:affine,代码行数:10,代码来源:test_model.py

示例11: imdct

    def imdct(self,y,i):
        """imdct: inverse mdct
            y(np.array) -> mdct signal
            i -> index frame size
        """
        # frame size
        L = self.sizes[i]
        # signal size
        N = y.size
        # Number of frequency channels
        K = L/2
        # Number of frames
        P = N/K

        # Reshape y
        tmp = y.reshape(P,K)
        y = np.zeros( (P,L) )
        y[:,:K] = tmp

        # Pre-twidle
        y = np.complex_(y)
        y *= np.tile(np.exp(1j*2.*np.pi*np.arange(L)*(L/2+1)/2./L), (P,1))

        # IFFT
        x = np.fft.ifft(y);

        # Post-twidle
        x *= np.tile(np.exp((1./2.)*1j*2*np.pi*(np.arange(L)+((L/2+1)/2.))/L),(P,1));

        # Windowing
        win = self.window(np.arange(L))
        winL = np.copy(win)
        winL[:L/4] = 0
        winL[L/4:L/2] = 1
        winR = np.copy(win)
        winR[L/2:3*L/4] = 1
        winR[3*L/4:] = 0
        x[0,:] *= winL
        x[1:-1,:] *= np.tile(win,(P-2,1))
        x[-1,:] *= winR

        # Real part & scaling
        x = np.sqrt(2./K)*L*x.real

        # Overlap and add
        b = np.repeat(np.arange(P),L)
        a = np.tile(np.arange(L),P) + b*K
        x = sparse.coo_matrix((x.ravel(),(b,a)),shape=(P,N+K)).sum(axis=0).A1

        # Cut edges
        return x[K/2:-K/2]
开发者ID:vince91,项目名称:audiofingerprint,代码行数:51,代码来源:mdct.py

示例12: construct_b_matrix

	def construct_b_matrix(self, PSI, GAMMA):
		"""Construct B matrix as in D. F. V. James et al. Phys. Rev. A, 64, 052312 (2001).

		:param array PSI: :math:`\psi_\\nu` vector with :math:`\\nu=1,...,16`, computed in __init__
		:param array GAMMA: :math:`\Gamma` matrices, computed in __init__

		:return: :math:`B_{\\nu,\mu} = \\langle \psi_\\nu \\rvert  \Gamma_\mu  \\lvert \psi_\\nu \\rangle`
		:rtype: numpy array
		"""

		B = np.complex_(np.zeros((16,16)))

		for i in range(16):
			for j in range(16):
				B[i,j] = np.dot(np.conj(PSI[i]) , np.dot(GAMMA[j], PSI[i]))
		return B
开发者ID:afognini,项目名称:Tomography,代码行数:16,代码来源:Tomography.py

示例13: from_csv

	def from_csv(cls, csv, delimiter="\t"):
		'''Constructs class instance from the given csv table. Is used in testing mode. Method is able to construct only 2d space. Is supposed to read tables produced by 'to_csv' method
		
			csv string: path to csv table
			delimiter string: csv table delimiter
			
			Return Grid: class instance
		'''		
		def _converter(l):
			a = l.strip().split(delimiter)
			a = [x.replace("|", "+") + "j" for x in a]
			return delimiter.join(a);
			
		array = np.genfromtxt((_converter(x) for x in open(csv)), dtype=str, delimiter=delimiter)
		array = np.complex_(array)
		encoding_table = [dict([(x,x) for x in range(array.shape[0])]), dict([(x,x) for x in range(array.shape[1])])]
		return cls(array, encoding_table);
开发者ID:afilipch,项目名称:nrlbio,代码行数:17,代码来源:LRGFDR.py

示例14: besselj

def besselj(n, z):
    """Bessel function of first kind of order n at kr.
    Wraps scipy.special.jn(n, z).

    Parameters
    ----------
    n : array_like
       Order
    z: array_like
       Argument

    Returns
    -------
    J : array_like
       Values of Bessel function of order n at position z
    """
    return scy.jv(n, _np.complex_(z))
开发者ID:QULab,项目名称:sound_field_analysis-py,代码行数:17,代码来源:sph.py

示例15: test_against_cmath

    def test_against_cmath(self):
        import cmath, sys

        points = [-1-1j, -1+1j, +1-1j, +1+1j]
        name_map = {'arcsin': 'asin', 'arccos': 'acos', 'arctan': 'atan',
                    'arcsinh': 'asinh', 'arccosh': 'acosh', 'arctanh': 'atanh'}
        atol = 4*np.finfo(np.complex).eps
        for func in self.funcs:
            fname = func.__name__.split('.')[-1]
            cname = name_map.get(fname, fname)
            try:
                cfunc = getattr(cmath, cname)
            except AttributeError:
                continue
            for p in points:
                a = complex(func(np.complex_(p)))
                b = cfunc(p)
                assert_(abs(a - b) < atol, "%s %s: %s; cmath: %s"%(fname, p, a, b))
开发者ID:Fematich,项目名称:article_browser,代码行数:18,代码来源:test_umath.py


注:本文中的numpy.complex_函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。