本文整理汇总了Python中numpy.trunc方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.trunc方法的具体用法?Python numpy.trunc怎么用?Python numpy.trunc使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.trunc方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: RQGA
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trunc [as 别名]
def RQGA(n, string_num):
psi_=psi(string_num)
H=hadamard(n)
psi_=np.dot(H,psi_)
print(psi_)
print()
iter=np.trunc(maxiter(n))
iter=int(round(iter))
for i in range (1,iter):
U_O=U_Oracle(n)
print(U_O)
print()
psi_=np.dot(U_O,psi_)
print(psi_)
print()
D=ia(n)
psi_=np.dot(D,psi_)
print(psi_)
#########################################################
# #
# MAIN PROGRAM #
# #
#########################################################
示例2: test_adjust_gamma_less_one
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trunc [as 别名]
def test_adjust_gamma_less_one(self):
"""Verifying the output with expected results for gamma
correction with gamma equal to half"""
with self.test_session():
x_np = np.arange(0, 255, 4, np.uint8).reshape(8,8)
y = image_ops.adjust_gamma(x_np, gamma=0.5)
y_tf = np.trunc(y.eval())
y_np = np.array([[ 0, 31, 45, 55, 63, 71, 78, 84],
[ 90, 95, 100, 105, 110, 115, 119, 123],
[127, 131, 135, 139, 142, 146, 149, 153],
[156, 159, 162, 165, 168, 171, 174, 177],
[180, 183, 186, 188, 191, 194, 196, 199],
[201, 204, 206, 209, 211, 214, 216, 218],
[221, 223, 225, 228, 230, 232, 234, 236],
[238, 241, 243, 245, 247, 249, 251, 253]], dtype=np.float32)
self.assertAllClose(y_tf, y_np, 1e-6)
示例3: test_adjust_gamma_greater_one
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trunc [as 别名]
def test_adjust_gamma_greater_one(self):
"""Verifying the output with expected results for gamma
correction with gamma equal to two"""
with self.test_session():
x_np = np.arange(0, 255, 4, np.uint8).reshape(8,8)
y = image_ops.adjust_gamma(x_np, gamma=2)
y_tf = np.trunc(y.eval())
y_np = np.array([[ 0, 0, 0, 0, 1, 1, 2, 3],
[ 4, 5, 6, 7, 9, 10, 12, 14],
[ 16, 18, 20, 22, 25, 27, 30, 33],
[ 36, 39, 42, 45, 49, 52, 56, 60],
[ 64, 68, 72, 76, 81, 85, 90, 95],
[100, 105, 110, 116, 121, 127, 132, 138],
[144, 150, 156, 163, 169, 176, 182, 189],
[196, 203, 211, 218, 225, 233, 241, 249]], dtype=np.float32)
self.assertAllClose(y_tf, y_np, 1e-6)
示例4: check_for_quench
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trunc [as 别名]
def check_for_quench(self, wait=5, threshold=0.95, repetitions=1000):
'''
Checks the magent for quench
Input:
wait (float) : waiting time in sec, default=5
threshold (float) : maximum voltage in volts, default=0.95
repetitions (int) : number of times quenching is checked, default=1000
Output:
None
'''
logging.debug(__name__ + 'check_for_quench()')
for i in range(repetitions):
time.sleep(wait)
voltage = self.do_get_voltage()
current = self.do_get_current()
print "V=" + str(np.trunc(voltage * 1000) / 1000.) + "V, I=" + str(
np.trunc(current * 1000) / 1000.) + "A, R=" + str(int(np.trunc(voltage / current * 1000))) + "mOhm"
if voltage > threshold:
print "WARNING! Magnet quench!! ramping down the coil..."
self.ramp_current(0., 2e-3, wait=0.2, showvalue=True)
return
示例5: numpy_math
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trunc [as 别名]
def numpy_math(x):
# **Trigonometric functions**
a = np.sin(x) # Trigonometric sine, element-wise.
a = np.cos(x) # Cosine elementwise.
a = np.tan(x) # Compute tangent element-wise.
a = np.arcsin(x) #Inverse sine, element-wise.
a = np.arccos(x) #Trigonometric inverse cosine, element-wise.
a = np.arctan(x) #Trigonometric inverse tangent, element-wise.
# **Hyperbolic functions**
a = np.sinh(x) # Hyperbolic sine, element-wise.
a = np.cosh(x) # Hyperbolic cosine, element-wise.
a = np.tanh(x) # Compute hyperbolic tangent element-wise.
# **Miscellaneous**
a = np.exp(x) # Calculate the exponential of all elements in the input array.
a = np.sum(x) # Return the sum of array elements.
a = np.sqrt(x) # Return the positive square-root of an array, element-wise.
a = np.ceil(x) # Return the ceiling of the input, element-wise.
a = np.floor(x) # Return the floor of the input, element-wise.
a = np.trunc(x) # Return the truncated value of the input, element-wise.
a = np.fabs(x) # Compute the absolute values element-wise
a = np.pi # Returns the pi constant
示例6: test_unary_identity
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trunc [as 别名]
def test_unary_identity():
for op, ref in [(relay.zeros_like, np.zeros_like),
(relay.ones_like, np.ones_like),
(relay.ceil, np.ceil),
(relay.floor, np.floor),
(relay.trunc, np.trunc),
(relay.round, np.round),
(relay.abs, np.abs),
(relay.copy, None), # np.copy
(relay.negative, np.negative),
(relay.sign, np.sign)]:
shape = (8, 9, 4)
x = relay.var("x", relay.TensorType(shape, "float32"))
y = op(x)
yy = run_infer_type(y)
assert yy.checked_type == relay.TensorType(shape, "float32")
if ref is not None:
data = np.random.rand(*shape).astype('float32')
intrp = create_executor()
op_res = intrp.evaluate(y, { x: relay.const(data) })
ref_res = ref(data)
np.testing.assert_allclose(op_res.asnumpy(), ref_res, rtol=0.01)
示例7: idl_round
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trunc [as 别名]
def idl_round(x):
"""
Round to the *nearest* integer, half-away-from-zero.
Parameters
----------
x : array-like
Number or array to be rounded
Returns
-------
r_rounded : array-like
note that the returned values are floats
Notes
-----
IDL ``ROUND`` rounds to the *nearest* integer (commercial rounding),
unlike numpy's round/rint, which round to the nearest *even*
value (half-to-even, financial rounding) as defined in IEEE-754
standard.
"""
return np.trunc(x + np.copysign(0.5, x))
示例8: get_native_grids
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trunc [as 别名]
def get_native_grids(lat_min, lon_min, lat_max, lon_max):
"""
Returns the latitude and longitude grid at native SRTM30 resolution
that are included in the given rectangle.
Args:
lat_min: The latitude coordinate of the lower left corner.
lon_min: The longitude coordinate of the lower left corner.
lat_max: The latitude coordinate of the upper right corner.
lon_max: The latitude coordinate of the upper right corner.
Returns:
Tuple :code:`(lats, lons)` of 1D-arrays containing the latitude
and longitude coordinates of the SRTM30 data points within the
given rectangle.
"""
i = (90 - lat_max) / SRTM30._dlat
i_max = np.trunc(i)
if not i_max < i:
i_max = i_max + 1
i = (90 - lat_min) / SRTM30._dlat
i_min = np.trunc(i)
lat_grid = 90 + 0.5 * SRTM30._dlat - np.arange(i_max, i_min + 1) * SRTM30._dlat
j = (lon_max + 180) / SRTM30._dlon
j_max = np.trunc((lon_max + 180.0) / SRTM30._dlon)
if not j_max < j:
j_max = j_max - 1
j_min = np.trunc((lon_min + 180.0) / SRTM30._dlon)
lon_grid = -180 + 0.5 * SRTM30._dlon
lon_grid += np.arange(j_min, j_max + 1) * SRTM30._dlon
return lat_grid, lon_grid
示例9: __trunc__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trunc [as 别名]
def __trunc__(self):
"""trunc(self): Truncates self to an Integral.
Returns an Integral i such that:
* i>0 iff self>0;
* abs(i) <= abs(self);
* for any Integral j satisfying the first two conditions,
abs(i) >= abs(j) [i.e. i has "maximal" abs among those].
i.e. "truncate towards 0".
"""
raise NotImplementedError
##############################################
示例10: trunc
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trunc [as 别名]
def trunc(x, out=None, where=None, **kwargs):
"""
Return the truncated value of the input, element-wise.
The truncated value of the scalar `x` is the nearest integer `i` which
is closer to zero than `x` is. In short, the fractional part of the
signed number `x` is discarded.
Parameters
----------
x : array_like
Input data.
out : Tensor, None, or tuple of Tensor and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated tensor is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
Values of True indicate to calculate the ufunc at that position, values
of False indicate to leave the value in the output alone.
**kwargs
Returns
-------
y : Tensor or scalar
The truncated value of each element in `x`.
See Also
--------
ceil, floor, rint
Examples
--------
>>> import mars.tensor as mt
>>> a = mt.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> mt.trunc(a).execute()
array([-1., -1., -0., 0., 1., 1., 2.])
"""
op = TensorTrunc(**kwargs)
return op(x, out=out, where=where)
示例11: test_numpy_method
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trunc [as 别名]
def test_numpy_method():
# This type of code is used frequently by PyMC3 users
x = tt.dmatrix('x')
data = np.random.rand(5, 5)
x.tag.test_value = data
for fct in [np.arccos, np.arccosh, np.arcsin, np.arcsinh,
np.arctan, np.arctanh, np.ceil, np.cos, np.cosh, np.deg2rad,
np.exp, np.exp2, np.expm1, np.floor, np.log,
np.log10, np.log1p, np.log2, np.rad2deg,
np.sin, np.sinh, np.sqrt, np.tan, np.tanh, np.trunc]:
y = fct(x)
f = theano.function([x], y)
utt.assert_allclose(np.nan_to_num(f(data)),
np.nan_to_num(fct(data)))
示例12: impl
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trunc [as 别名]
def impl(self, x):
return numpy.trunc(x)
示例13: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trunc [as 别名]
def __init__(self, n, k):
"""
K-Folds cross validation iterator:
Provides train/test indexes to split data in train test sets
Parameters
----------
n: int
Total number of elements
k: int
number of folds
Examples
--------
>>> from scikits.learn import cross_val
>>> X = [[1, 2], [3, 4], [1, 2], [3, 4]]
>>> y = [1, 2, 3, 4]
>>> kf = cross_val.KFold(4, k=2)
>>> for train_index, test_index in kf:
... print "TRAIN:", train_index, "TEST:", test_index
... X_train, X_test, y_train, y_test = cross_val.split(train_index, test_index, X, y)
TRAIN: [False False True True] TEST: [ True True False False]
TRAIN: [ True True False False] TEST: [False False True True]
Notes
-----
All the folds have size trunc(n/k), the last one has the complementary
"""
assert k>0, ValueError('cannot have k below 1')
assert k<n, ValueError('cannot have k=%d greater than %d'% (k, n))
self.n = n
self.k = k
示例14: _compute_hommel_value
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trunc [as 别名]
def _compute_hommel_value(z_vals, alpha, verbose=False):
"""Compute the All-Resolution Inference hommel-value"""
if alpha < 0 or alpha > 1:
raise ValueError('alpha should be between 0 and 1')
z_vals_ = - np.sort(- z_vals)
p_vals = norm.sf(z_vals_)
n_samples = len(p_vals)
if len(p_vals) == 1:
return p_vals[0] > alpha
if p_vals[0] > alpha:
return n_samples
slopes = (alpha - p_vals[: - 1]) / np.arange(n_samples, 1, -1)
slope = np.max(slopes)
hommel_value = np.trunc(n_samples + (alpha - slope * n_samples) / slope)
if verbose:
try:
from matplotlib import pyplot as plt
except ImportError:
warnings.warn('"verbose" option requires the package Matplotlib.'
'Please install it using `pip install matplotlib`.')
else:
plt.figure()
plt.plot(p_vals, 'o')
plt.plot([n_samples - hommel_value, n_samples], [0, alpha])
plt.plot([0, n_samples], [0, 0], 'k')
plt.show(block=False)
return np.minimum(hommel_value, n_samples)
示例15: truncate
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trunc [as 别名]
def truncate(values, decs=2):
return np.trunc(values*10**decs)/(10**decs)