本文整理汇总了Python中numpy.frexp函数的典型用法代码示例。如果您正苦于以下问题:Python frexp函数的具体用法?Python frexp怎么用?Python frexp使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了frexp函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: computeActivity
def computeActivity(self, inputActivity):
logger.debug('computing activity.')
self.ensureLength(inputActivity.max())
# numpy array magic
idx = numpy.mgrid[0:self.dims[0], 0:self.dims[1], 0:self.dims[2]]
tInputActivity = numpy.tile(inputActivity, self.dims[:-1] + (1,))
factors = 2 * self.counts[idx[0],idx[1],idx[2],tInputActivity] / numpy.sum(self.counts, axis=3)
mans,exps = numpy.frexp(factors)
mantissas, exponents = numpy.frexp(numpy.prod(mans, axis=2))
exponents += exps.sum(axis=2)
if self.maxexp is not None:
maxexp = self.maxexp
else:
maxexp = exponents.max()
exponents -= maxexp
logger.debug("Maximum exponent: %d", maxexp)
activity = mantissas * numpy.exp2(exponents)
if self.p != 0:
conscience = (self.coff / self.con)**self.p
activity *= conscience
activity *= numpy.prod(activity.shape) / activity.sum()
return activity
示例2: _detectEndian
def _detectEndian (self):
if (self.endian != 'Auto'):
self._maybePrint('%s endian specified... Not autodetecting.'%(self.endian,))
if (self.endian != self.mendian):
self._maybePrint('%s endian != %s endian, therefore Foreign.'%(self.endian,self.mendian))
self.endian = 'Foreign'
else:
self._maybePrint('Auto endian specified... Trying to autodetect data endianness.')
for i in xrange(1, self.ntr+1):
locar = self.readTraces(i)
if ((not abs(locar).sum() == 0.) and (not _np.isnan(locar.mean()))):
nexp = abs(_np.frexp(locar.mean())[1])
locar = locar.newbyteorder()
fexp = abs(_np.frexp(locar.mean())[1])
if (fexp > nexp):
self.endian = 'Native'
else:
self.endian = 'Foreign'
self._maybePrint('Scanned %d trace(s). Endian appears to be %s.'%(i, self.endian))
break
if (self.endian == 'Foreign'):
self._maybePrint('Will attempt to convert to %s endian when traces are read.\n'%(self.mendian,))
elif (self.endian == 'Auto'):
self._maybePrint('Couldn\'t find any non-zero traces to test!\nAssuming Native endian.\n')
示例3: _detectFileEndian
def _detectFileEndian (self):
if (self.endian != 'Auto'):
self._maybePrint('%s endian specified... Not autodetecting.'%(self.endian,))
if (self.endian != self.mendian):
self._maybePrint('%s endian != %s endian, therefore Foreign.'%(self.endian,self.mendian))
self.endian = 'Foreign'
else:
self._maybePrint('Auto endian specified... Trying to autodetect data endianness.')
with warnings.catch_warnings():
warnings.simplefilter('ignore')
for i in xrange(self.ntr):
locar = self[i]
if ((not abs(locar).sum() == 0.) and (not np.isnan(locar.mean()))):
nexp = abs(np.frexp(locar.astype(np.float64)**2)[1]).mean()
locar = locar.newbyteorder()
fexp = abs(np.frexp(locar.astype(np.float64)**2)[1]).mean()
if (fexp > nexp):
self.endian = 'Native'
else:
self.endian = 'Foreign'
self._maybePrint('Scanned %d trace(s). Endian appears to be %s.'%(i, self.endian))
break
if (self.endian == 'Foreign'):
self._maybePrint('Will attempt to convert to %s endian when traces are read.\n'%(self.mendian,))
elif (self.endian == 'Auto'):
self._maybePrint('Couldn\'t find any non-zero traces to test!\nAssuming Native endian.\n')
示例4: nextpow2
def nextpow2(n):
"""Return the next power of 2 such as 2^p >= n.
Notes
-----
Infinite and nan are left untouched, negative values are not allowed."""
if np.any(n < 0):
raise ValueError("n should be > 0")
if np.isscalar(n):
f, p = np.frexp(n)
if f == 0.5:
return p-1
elif np.isfinite(f):
return p
else:
return f
else:
f, p = np.frexp(n)
res = f
bet = np.isfinite(f)
exa = (f == 0.5)
res[bet] = p[bet]
res[exa] = p[exa] - 1
return res
示例5: test_ufunc_two_outputs
def test_ufunc_two_outputs(self):
mantissa, exponent = np.frexp(2 ** -3)
expected = (ArrayLike(mantissa), ArrayLike(exponent))
_assert_equal_type_and_value(
np.frexp(ArrayLike(2 ** -3)), expected)
_assert_equal_type_and_value(
np.frexp(ArrayLike(np.array(2 ** -3))), expected)
示例6: test_frexp_invalid_units
def test_frexp_invalid_units(self):
# Can't use prod() with non-dimensionless quantities
with pytest.raises(TypeError) as exc:
np.frexp(3.0 * u.m / u.s)
assert exc.value.args[0] == ("Can only apply 'frexp' function to " "unscaled dimensionless quantities")
# also does not work on quantities that can be made dimensionless
with pytest.raises(TypeError) as exc:
np.frexp(np.array([2.0, 3.0, 6.0]) * u.m / (6.0 * u.cm))
assert exc.value.args[0] == ("Can only apply 'frexp' function to " "unscaled dimensionless quantities")
示例7: saveArray
def saveArray(filename, data):
# https://gist.github.com/edouardp/3089602
f = open(filename, "wb")
f.write("#?RADIANCE\n# Made with Python & Numpy\nFORMAT=32-bit_rle_rgbe\n\n")
f.write("-Y {0} +X {1}\n".format(data.shape[0], data.shape[1]))
brightest = np.maximum(np.maximum(data[...,0], data[...,1]), data[...,2])
exp = np.zeros_like(brightest)
man = np.zeros_like(brightest)
np.frexp(brightest, man, exp)
scman = np.nan_to_num(man * 256.0 / brightest)
rgbe = np.zeros((data.shape[0], data.shape[1], 4), dtype=np.uint8)
rgbe[...,0:3] = np.minimum(np.maximum(np.around(data[...,0:3] * scman[...,None]), 0), 255)
rgbe[...,3] =np.minimum(np.maximum(np.around(exp + 128), 0), 255)
rgbe.flatten().tofile(f)
f.close()
示例8: _sp_expm
def _sp_expm(qo):
"""
Sparse matrix exponential of a quantum operator.
Called by the Qobj expm method.
"""
A = qo.data.tocsc() # extract Qobj data (sparse matrix)
m_vals = np.array([3, 5, 7, 9, 13])
theta = np.array([0.01495585217958292, 0.2539398330063230,
0.9504178996162932, 2.097847961257068,
5.371920351148152], dtype=float)
normA = _sp_one_norm(qo)
if normA <= theta[-1]:
for ii in range(len(m_vals)):
if normA <= theta[ii]:
F = _pade(A, m_vals[ii])
break
else:
t, s = np.frexp(normA / theta[-1])
s = s - (t == 0.5)
A = A / 2.0 ** s
F = _pade(A, m_vals[-1])
for i in range(s):
F = F * F
return F
示例9: frexp
def frexp(x):
tmp = elemwise(np.frexp, x)
left = next(names)
right = next(names)
ldsk = dict(((left,) + key[1:], (getitem, key, 0))
for key in core.flatten(tmp._keys()))
rdsk = dict(((right,) + key[1:], (getitem, key, 1))
for key in core.flatten(tmp._keys()))
if x._dtype is not None:
a = np.empty((1,), dtype=x._dtype)
l, r = np.frexp(a)
ldt = l.dtype
rdt = r.dtype
else:
ldt = None
rdt = None
L = Array(merge(tmp.dask, ldsk), left, blockdims=tmp.blockdims,
dtype=ldt)
R = Array(merge(tmp.dask, rdsk), right, blockdims=tmp.blockdims,
dtype=rdt)
return L, R
示例10: pSpectrum
def pSpectrum(data=None, samplefreq=44100):
npts = len(data)
# we should window the data here
if npts == 0:
print "? no data in pSpectrum"
return
# pad to the nearest higher power of 2
(a,b) = numpy.frexp(npts)
if a <= 0.5:
b = b = 1
npad = 2**b -npts
if debugFlag:
print "npts: %d npad: %d npad+npts: %d" % (npts, npad, npad+npts)
padw = numpy.append(data, numpy.zeros(npad))
npts = len(padw)
sigfft = spFFT.fft(padw)
nUniquePts = numpy.ceil((npts+1)/2.0)
sigfft = sigfft[0:nUniquePts]
spectrum = abs(sigfft)
spectrum = spectrum / float(npts) # scale by the number of points so that
# the magnitude does not depend on the length
# of the signal or on its sampling frequency
spectrum = spectrum**2 # square it to get the power
spmax = numpy.amax(spectrum)
spectrum = spectrum + 1e-12*spmax
# multiply by two (see technical document for details)
# odd nfft excludes Nyquist point
if npts % 2 > 0: # we've got odd number of points fft
spectrum[1:len(spectrum)] = spectrum[1:len(spectrum)] * 2
else:
spectrum[1:len(spectrum) -1] = spectrum[1:len(spectrum) - 1] * 2 # we've got even number of points fft
freqAzero = numpy.arange(0, nUniquePts, 1.0) * (samplefreq / npts)
return(spectrum, freqAzero)
示例11: expm
def expm(A):
# EXPM Matrix exponential.
# EXPM(X) is the matrix exponential of X. EXPM is computed using
# a scaling and squaring algorithm with a Pade approximation.
#
# Julia implementation closely based on MATLAB code by Nicholas Higham
#
# Initialization
m_vals, theta = expmchk()
normA = 0
if issparse(A): normA = np.amax((A.multiply(A.sign())).sum(0))
else: normA = nlin.norm(A,1)
if normA <= theta[-1]:
# no scaling and squaring is required.
for i in range(len(m_vals)):
if normA <= theta[i]:
F = PadeApproximantOfDegree(A, m_vals[i])
break
else:
t,s = frexp(normA/float(theta[-1]))
s = s - (t == 0.5) # adjust s if normA/theta(end) is a power of 2.
A = A/(2.0**s) # Scaling
F = PadeApproximantOfDegree(A, m_vals[-1])
for i in range(s):
if issparse(A): F = F*F
else: F = np.dot(F,F)
return F
示例12: test_half_ufuncs
def test_half_ufuncs(self):
"""Test the various ufuncs"""
a = np.array([0, 1, 2, 4, 2], dtype=float16)
b = np.array([-2, 5, 1, 4, 3], dtype=float16)
c = np.array([0, -1, -np.inf, np.nan, 6], dtype=float16)
assert_equal(np.add(a, b), [-2, 6, 3, 8, 5])
assert_equal(np.subtract(a, b), [2, -4, 1, 0, -1])
assert_equal(np.multiply(a, b), [0, 5, 2, 16, 6])
assert_equal(np.divide(a, b), [0, 0.199951171875, 2, 1, 0.66650390625])
assert_equal(np.equal(a, b), [False, False, False, True, False])
assert_equal(np.not_equal(a, b), [True, True, True, False, True])
assert_equal(np.less(a, b), [False, True, False, False, True])
assert_equal(np.less_equal(a, b), [False, True, False, True, True])
assert_equal(np.greater(a, b), [True, False, True, False, False])
assert_equal(np.greater_equal(a, b), [True, False, True, True, False])
assert_equal(np.logical_and(a, b), [False, True, True, True, True])
assert_equal(np.logical_or(a, b), [True, True, True, True, True])
assert_equal(np.logical_xor(a, b), [True, False, False, False, False])
assert_equal(np.logical_not(a), [True, False, False, False, False])
assert_equal(np.isnan(c), [False, False, False, True, False])
assert_equal(np.isinf(c), [False, False, True, False, False])
assert_equal(np.isfinite(c), [True, True, False, False, True])
assert_equal(np.signbit(b), [True, False, False, False, False])
assert_equal(np.copysign(b, a), [2, 5, 1, 4, 3])
assert_equal(np.maximum(a, b), [0, 5, 2, 4, 3])
x = np.maximum(b, c)
assert_(np.isnan(x[3]))
x[3] = 0
assert_equal(x, [0, 5, 1, 0, 6])
assert_equal(np.minimum(a, b), [-2, 1, 1, 4, 2])
x = np.minimum(b, c)
assert_(np.isnan(x[3]))
x[3] = 0
assert_equal(x, [-2, -1, -np.inf, 0, 3])
assert_equal(np.fmax(a, b), [0, 5, 2, 4, 3])
assert_equal(np.fmax(b, c), [0, 5, 1, 4, 6])
assert_equal(np.fmin(a, b), [-2, 1, 1, 4, 2])
assert_equal(np.fmin(b, c), [-2, -1, -np.inf, 4, 3])
assert_equal(np.floor_divide(a, b), [0, 0, 2, 1, 0])
assert_equal(np.remainder(a, b), [0, 1, 0, 0, 2])
assert_equal(np.divmod(a, b), ([0, 0, 2, 1, 0], [0, 1, 0, 0, 2]))
assert_equal(np.square(b), [4, 25, 1, 16, 9])
assert_equal(np.reciprocal(b), [-0.5, 0.199951171875, 1, 0.25, 0.333251953125])
assert_equal(np.ones_like(b), [1, 1, 1, 1, 1])
assert_equal(np.conjugate(b), b)
assert_equal(np.absolute(b), [2, 5, 1, 4, 3])
assert_equal(np.negative(b), [2, -5, -1, -4, -3])
assert_equal(np.positive(b), b)
assert_equal(np.sign(b), [-1, 1, 1, 1, 1])
assert_equal(np.modf(b), ([0, 0, 0, 0, 0], b))
assert_equal(np.frexp(b), ([-0.5, 0.625, 0.5, 0.5, 0.75], [2, 3, 1, 3, 2]))
assert_equal(np.ldexp(b, [0, 1, 2, 4, 2]), [-2, 10, 4, 64, 12])
示例13: nextfloat
def nextfloat(fin):
"""Return (approximately) next float value (for f>0)."""
d = 2**-52
split = N.frexp(fin)
while True:
fout = N.ldexp(split[0] + d, split[1])
if fin != fout:
return fout
d *= 2
示例14: test_frexp
def test_frexp(self, dtype):
numpy_a = numpy.array([-300, -20, -10, -1, 0, 1, 10, 20, 300], dtype=dtype)
numpy_b, numpy_c = numpy.frexp(numpy_a)
cupy_a = cupy.array(numpy_a)
cupy_b, cupy_c = cupy.frexp(cupy_a)
testing.assert_allclose(cupy_b, numpy_b)
testing.assert_array_equal(cupy_c, numpy_c)
示例15: write_hdr
def write_hdr(filename, image):
'''Writes a HDR image into disk. Assumes you have a np.array((height,width,3), dtype=float)
as your HDR image'''
f = open(filename, "wb")
f.write("#?RADIANCE\n# Made with Python & Numpy\nFORMAT=32-bit_rle_rgbe\n\n")
f.write("-Y {0} +X {1}\n".format(image.shape[0], image.shape[1]))
brightest = np.maximum(np.maximum(image[...,0], image[...,1]), image[...,2])
mantissa = np.zeros_like(brightest)
exponent = np.zeros_like(brightest)
np.frexp(brightest, mantissa, exponent)
scaled_mantissa = mantissa * 256.0 / brightest
rgbe = np.zeros((image.shape[0], image.shape[1], 4), dtype=np.uint8)
rgbe[..., 0:3] = np.around(image[..., 0:3] * scaled_mantissa[..., None])
rgbe[..., 3] = np.around(exponent + 128)
rgbe.flatten().tofile(f)
f.close()