本文整理汇总了Python中numpy.frexp函数的典型用法代码示例。如果您正苦于以下问题:Python frexp函数的具体用法?Python frexp怎么用?Python frexp使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了frexp函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:tatome,项目名称:bauer_et_al_2015,代码行数:27,代码来源:network.py
示例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')
开发者ID:EvanBianco,项目名称:pygeo,代码行数:25,代码来源:segyreadold.py
示例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')
开发者ID:Matterhorn-eth,项目名称:pymh,代码行数:27,代码来源:segyread.py
示例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
开发者ID:Lathomas42,项目名称:Envelope_Detection,代码行数:26,代码来源:correlations.py
示例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)
开发者ID:AlerzDev,项目名称:Brazo-Proyecto-Final,代码行数:7,代码来源:test_mixins.py
示例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")
开发者ID:healther,项目名称:astropy,代码行数:10,代码来源:test_quantity_ufuncs.py
示例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()
开发者ID:Skareeg,项目名称:pycubetools,代码行数:15,代码来源:hdr.py
示例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
开发者ID:dougmcnally,项目名称:qutip,代码行数:25,代码来源:sparse.py
示例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
开发者ID:kastnerkyle,项目名称:dask,代码行数:25,代码来源:core.py
示例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)
开发者ID:ablot,项目名称:acq4,代码行数:33,代码来源:Utility.py
示例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
开发者ID:BohdanKul,项目名称:Scripts,代码行数:32,代码来源:mexp.py
示例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])
开发者ID:AlerzDev,项目名称:Brazo-Proyecto-Final,代码行数:59,代码来源:test_half.py
示例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
开发者ID:patricktokeeffe,项目名称:veusz,代码行数:9,代码来源:utilfuncs.py
示例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)
开发者ID:RE-ID,项目名称:chainer,代码行数:9,代码来源:test_floating.py
示例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()
开发者ID:PeterZs,项目名称:create_hdri,代码行数:18,代码来源:create_hdri.py
示例16: compare_float
def compare_float(var, ref, cut_digit=1, verbose=False):
# x = mantissa * 2**exponent
if type(var) != np.ndarray: var = np.array(var)
if type(ref) != np.ndarray: ref = np.array(ref)
m_var, e_var = np.frexp(var)
m_ref, e_ref = np.frexp(ref)
num_exp_diff = np.count_nonzero(e_var != e_ref)
if num_exp_diff > 0:
try:
# check 0 and 1e-16
idxs = np.where(e_var != e_ref)
aa_equal(var[idxs], ref[idxs], 15)
return True, 15
except:
if verbose:
print("idxs : ", idxs)
print("Actual : ", var[idxs])
print("Desired: ", ref[idxs])
return False, "The exponents are not same at {} points".format(num_exp_diff)
num_man_diff = np.count_nonzero(m_var != m_ref)
if num_man_diff == 0:
return True, "exact"
digit = 17
percents = []
while(True):
try:
aa_equal(m_var, m_ref, digit-1)
return True, "{}, ({})".format(digit, ', '.join(percents))
except Exception as e:
percent = float(re.findall('mismatch (\d+.\S+)%',str(e))[0])
percents.insert(0, "{}:{:.2f}%".format(digit,percent))
#print('>>>>', digit, str(e), percent, percents)
if digit == cut_digit:
return False, "{}, ({})".format(cut_digit, ', '.join(percents))
else:
digit -= 1
开发者ID:wbkifun,项目名称:my_stuff,代码行数:43,代码来源:compare_float_array.py
示例17: test_binary_out
def test_binary_out():
args = [1,
np.ones(2),
xr.Variable(['x'], [1, 1]),
xr.DataArray([1, 1], dims='x'),
xr.Dataset({'y': ('x', [1, 1])})]
for arg in args:
actual_mantissa, actual_exponent = np.frexp(arg)
assert_identical(actual_mantissa, 0.5 * arg)
assert_identical(actual_exponent, arg)
开发者ID:edoddridge,项目名称:xarray,代码行数:10,代码来源:test_ufuncs.py
示例18: hadamard
def hadamard(n):
"""
HADAMARD Hadamard matrix.
HADAMARD(N) is a Hadamard matrix of order N, that is,
a matrix H with elements 1 or -1 such that H*H' = N*EYE(N).
An N-by-N Hadamard matrix with N>2 exists only if REM(N,4) = 0.
This function handles only the cases where N, N/12 or N/20
is a power of 2.
Reference:
S.W. Golomb and L.D. Baumert, The search for Hadamard matrices,
Amer. Math. Monthly, 70 (1963) pp. 12-17.
http://en.wikipedia.org/wiki/Hadamard_matrix
Weisstein, Eric W. "Hadamard Matrix." From MathWorld--
A Wolfram Web Resource:
http://mathworld.wolfram.com/HadamardMatrix.html
"""
f, e = np.frexp(np.array([n, n / 12., n / 20.]))
try:
# If more than one condition is satified, this will always
# pick the first one.
k = [i for i in range(3) if (f == 0.5)[i] and (e > 0)[i]].pop()
except IndexError:
raise ValueError('N, N/12 or N/20 must be a power of 2.')
e = e[k] - 1
if k == 0: # N = 1 * 2^e;
h = np.array([1])
elif k == 1: # N = 12 * 2^e;
tp = rogues.toeplitz(np.array([-1, -1, 1, -1, -1, -1, 1, 1, 1, -1, 1]),
np.array([-1, 1, -1, 1, 1, 1, -1, -1, -1, 1, -1]))
h = np.vstack((np.ones((1, 12)), np.hstack((np.ones((11, 1)), tp))))
elif k == 2: # N = 20 * 2^e;
hk = rogues.hankel(
np.array([-1, -1, 1, 1, -1, -1, -1, -1, 1,
-1, 1, -1, 1, 1, 1, 1, -1, -1, 1]),
np.array([1, -1, -1, 1, 1, -1, -1, -1, -1,
1, -1, 1, -1, 1, 1, 1, 1, -1, -1]))
h = np.vstack((np.ones((1, 20)), np.hstack((np.ones((19, 1)), hk))))
# Kronecker product construction.
mh = -1 * h
for i in range(e):
ht = np.hstack((h, h))
hb = np.hstack((h, mh))
h = np.vstack((ht, hb))
mh = -1 * h
return h
开发者ID:macd,项目名称:rogues,代码行数:55,代码来源:hadamard.py
示例19: exercise_frexp_t
def exercise_frexp_t(self, tp):
a = np.arange(5, dtype=tp)
b = np.frexp(a)
coeff = b[0]
exp = b[1]
for i in range(len(coeff)):
x = coeff[i] * pow(2, exp[i])
assert x == a[i]
开发者ID:ECain,项目名称:MissionPlanner,代码行数:11,代码来源:test_loops.py
示例20: pSpectrum
def pSpectrum(data=None, samplefreq=44100):
"""Power spectrum computation.
Compute the power spectrum of a data set using standard ffts, after padding
the data set to the next higher power of 2. Assumes data is regularly
sampled in the time domain.
Parameters
data : list or numpy array
the signal for which the power spectrume will be computed
arg2 : float
The sample frequency for the data set, in Hz
Returns
-------
(powerspectrum, frequency)
Tuple of numpy arrays with the computed power spectrum, and
the associated frequency arrays (in Hz)
"""
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) = np.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 = np.append(data, np.zeros(npad))
npts = len(padw)
sigfft = spFFT.fft(padw)
nUniquePts = int(np.ceil((npts+1)/2.0))
# print nUniquePts
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 = np.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 = np.arange(0, nUniquePts, 1.0) * (samplefreq / npts)
return(spectrum, freqAzero)
开发者ID:pbmanis,项目名称:pylibrary,代码行数:53,代码来源:Utility.py
注:本文中的numpy.frexp函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论