本文整理汇总了Python中math.copysign方法的典型用法代码示例。如果您正苦于以下问题:Python math.copysign方法的具体用法?Python math.copysign怎么用?Python math.copysign使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类math
的用法示例。
在下文中一共展示了math.copysign方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_strategy_path_type
# 需要导入模块: import math [as 别名]
# 或者: from math import copysign [as 别名]
def get_strategy_path_type(self, strategy_path_id, size1, current):
"""Decodes the path from the optimal strategy to its type.
Params:
strategy_path_id: raw path id from strategy array.
size1: offset used to distinguish between paths in the source and
destination trees.
it: node indexer
current: current subtree processed in tree decomposition phase
Return type of the strategy path: LEFT, RIGHT, INNER"""
# pylint: disable=no-self-use
if math.copysign(1, strategy_path_id) == -1:
return LEFT
path_id = abs(strategy_path_id) - 1
if path_id >= size1:
path_id = path_id - size1
if path_id == (current.pre_ltr + current.size - 1):
return RIGHT
return INNER
示例2: get_boundaries_intersections
# 需要导入模块: import math [as 别名]
# 或者: from math import copysign [as 别名]
def get_boundaries_intersections(self, z, d, trust_radius):
"""
Solve the scalar quadratic equation ||z + t d|| == trust_radius.
This is like a line-sphere intersection.
Return the two values of t, sorted from low to high.
"""
a = np.dot(d, d)
b = 2 * np.dot(z, d)
c = np.dot(z, z) - trust_radius**2
sqrt_discriminant = math.sqrt(b*b - 4*a*c)
# The following calculation is mathematically
# equivalent to:
# ta = (-b - sqrt_discriminant) / (2*a)
# tb = (-b + sqrt_discriminant) / (2*a)
# but produce smaller round off errors.
# Look at Matrix Computation p.97
# for a better justification.
aux = b + math.copysign(sqrt_discriminant, b)
ta = -aux / (2*a)
tb = -2*c / aux
return sorted([ta, tb])
示例3: assertFloatsAreIdentical
# 需要导入模块: import math [as 别名]
# 或者: from math import copysign [as 别名]
def assertFloatsAreIdentical(self, x, y):
"""assert that floats x and y are identical, in the sense that:
(1) both x and y are nans, or
(2) both x and y are infinities, with the same sign, or
(3) both x and y are zeros, with the same sign, or
(4) x and y are both finite and nonzero, and x == y
"""
msg = 'floats {!r} and {!r} are not identical'
if isnan(x) or isnan(y):
if isnan(x) and isnan(y):
return
elif x == y:
if x != 0.0:
return
# both zero; check that signs match
elif copysign(1.0, x) == copysign(1.0, y):
return
else:
msg += ': zeros have different signs'
self.fail(msg.format(x, y))
示例4: test_format_testfile
# 需要导入模块: import math [as 别名]
# 或者: from math import copysign [as 别名]
def test_format_testfile(self):
"""the following is borrowed from stdlib"""
import math
format_testfile = 'formatfloat_testcases.txt'
with open(os.path.join(self.test_dir, format_testfile)) as testfile:
for line in testfile:
print line
if line.startswith('--'):
continue
line = line.strip()
if not line:
continue
lhs, rhs = map(str.strip, line.split('->'))
fmt, arg = lhs.split()
arg = float(arg)
self.assertEqual(fmt % arg, rhs)
if not math.isnan(arg) and math.copysign(1.0, arg) > 0.0:
print("minus")
self.assertEqual(fmt % -arg, '-' + rhs)
示例5: get_cubic_root
# 需要导入模块: import math [as 别名]
# 或者: from math import copysign [as 别名]
def get_cubic_root(self):
# We have the equation x^2 D^2 + (1-x)^4 * C / h_min^2
# where x = sqrt(mu).
# We substitute x, which is sqrt(mu), with x = y + 1.
# It gives y^3 + py = q
# where p = (D^2 h_min^2)/(2*C) and q = -p.
# We use the Vieta's substution to compute the root.
# There is only one real solution y (which is in [0, 1] ).
# http://mathworld.wolfram.com/VietasSubstitution.html
# eps in the numerator is to prevent momentum = 1 in case of zero gradient
p = (self._dist_to_opt + eps)**2 * (self._h_min + eps)**2 / 2 / (self._grad_var + eps)
w3 = (-math.sqrt(p**2 + 4.0 / 27.0 * p**3) - p) / 2.0
w = math.copysign(1.0, w3) * math.pow(math.fabs(w3), 1.0/3.0)
y = w - p / 3.0 / (w + eps)
x = y + 1
if DEBUG:
logging.debug("p %f, den %f", p, self._grad_var + eps)
logging.debug("w3 %f ", w3)
logging.debug("y %f, den %f", y, w + eps)
return x
示例6: kontakt_divide
# 需要导入模块: import math [as 别名]
# 或者: from math import copysign [as 别名]
def kontakt_divide(a, b):
return(int(math.copysign(abs(a) // abs(b), a / b)))
########################################
# Defaults for the evaluator:
示例7: inflateconv
# 需要导入模块: import math [as 别名]
# 或者: from math import copysign [as 别名]
def inflateconv(conv3d, conv):
tempSize = conv3d.conv.weight.data.size()[2]
center = (tempSize-1)//2
if scheme==1:
factor = torch.FloatTensor([copysign(mult**abs(center-i), center-i) for i in range(tempSize)]).unsqueeze(0).unsqueeze(0).unsqueeze(-1).unsqueeze(-1).expand_as(conv3d.conv.weight).cuda()
conv3d.conv.weight.data = conv.weight.data[:,:,None,:,:].expand_as(conv3d.conv.weight).clone() * factor
elif scheme==3:
conv3d.conv.weight.data = conv.weight.data[:,:,None,:,:].expand_as(conv3d.conv.weight).clone() * (1./tempSize)
conv3d.conv.bias.data = conv.bias.data
conv3d.conv.weight.data = conv3d.conv.weight.data.contiguous()
conv3d.conv.bias.data = conv3d.conv.bias.data.contiguous()
return
示例8: erf_inv
# 需要导入模块: import math [as 别名]
# 或者: from math import copysign [as 别名]
def erf_inv(x):
a = 8*(math.pi-3)/(3*math.pi*(4-math.pi))
y = math.log(1-x*x)
z = 2/(math.pi*a) + y/2
return math.copysign(math.sqrt(math.sqrt(z*z - y/a) - z), x)
示例9: _sign
# 需要导入模块: import math [as 别名]
# 或者: from math import copysign [as 别名]
def _sign(x):
return int(copysign(1, x))
# vim:ts=4:sw=4:et
示例10: testWeirdFloats
# 需要导入模块: import math [as 别名]
# 或者: from math import copysign [as 别名]
def testWeirdFloats(self):
ser = Pyro5.serializers.serializers[config.SERIALIZER]
p = ser.dumps([float("+inf"), float("-inf"), float("nan")])
s2 = ser.loads(p)
assert math.isinf(s2[0])
assert math.copysign(1, s2[0]) == 1.0
assert math.isinf(s2[1])
assert math.copysign(1, s2[1]) == -1.0
assert math.isnan(s2[2])
示例11: intersect_trust_region
# 需要导入模块: import math [as 别名]
# 或者: from math import copysign [as 别名]
def intersect_trust_region(x, s, Delta):
"""Find the intersection of a line with the boundary of a trust region.
This function solves the quadratic equation with respect to t
||(x + s*t)||**2 = Delta**2.
Returns
-------
t_neg, t_pos : tuple of float
Negative and positive roots.
Raises
------
ValueError
If `s` is zero or `x` is not within the trust region.
"""
a = np.dot(s, s)
if a == 0:
raise ValueError("`s` is zero.")
b = np.dot(x, s)
c = np.dot(x, x) - Delta**2
if c > 0:
raise ValueError("`x` is not within the trust region.")
d = np.sqrt(b*b - a*c) # Root from one fourth of the discriminant.
# Computations below avoid loss of significance, see "Numerical Recipes".
q = -(b + copysign(d, b))
t1 = q / a
t2 = c / q
if t1 < t2:
return t1, t2
else:
return t2, t1
示例12: _givens_to_1
# 需要导入模块: import math [as 别名]
# 或者: from math import copysign [as 别名]
def _givens_to_1(self, aii, ajj, aij):
"""Computes a 2x2 Givens matrix to put 1's on the diagonal for the input matrix.
The input matrix is a 2x2 symmetric matrix M = [ aii aij ; aij ajj ].
The output matrix g is a 2x2 anti-symmetric matrix of the form [ c s ; -s c ];
the elements c and s are returned.
Applying the output matrix to the input matrix (as b=g.T M g)
results in a matrix with bii=1, provided tr(M) - det(M) >= 1
and floating point issues do not occur. Otherwise, some other
valid rotation is returned. When tr(M)==2, also bjj=1.
"""
aiid = aii - 1.
ajjd = ajj - 1.
if ajjd == 0:
# ajj==1, so swap aii and ajj to avoid division by zero
return 0., 1.
dd = math.sqrt(max(aij**2 - aiid*ajjd, 0))
# The choice of t should be chosen to avoid cancellation [1]
t = (aij + math.copysign(dd, aij)) / ajjd
c = 1. / math.sqrt(1. + t*t)
if c == 0:
# Underflow
s = 1.0
else:
s = c*t
return c, s
示例13: assertEqualAndEqualSign
# 需要导入模块: import math [as 别名]
# 或者: from math import copysign [as 别名]
def assertEqualAndEqualSign(self, a, b):
# fail unless a == b and a and b have the same sign bit;
# the only difference from assertEqual is that this test
# distinguishes -0.0 and 0.0.
self.assertEqual((a, copysign(1.0, a)), (b, copysign(1.0, b)))
示例14: test_format_testfile
# 需要导入模块: import math [as 别名]
# 或者: from math import copysign [as 别名]
def test_format_testfile(self):
with open(format_testfile) as testfile:
for line in open(format_testfile):
if line.startswith('--'):
continue
line = line.strip()
if not line:
continue
lhs, rhs = map(str.strip, line.split('->'))
fmt, arg = lhs.split()
arg = float(arg)
self.assertEqual(fmt % arg, rhs)
if not math.isnan(arg) and copysign(1.0, arg) > 0.0:
self.assertEqual(fmt % -arg, '-' + rhs)
示例15: identical
# 需要导入模块: import math [as 别名]
# 或者: from math import copysign [as 别名]
def identical(self, x, y):
# check that floats x and y are identical, or that both
# are NaNs
if isnan(x) or isnan(y):
if isnan(x) == isnan(y):
return
elif x == y and (x != 0.0 or copysign(1.0, x) == copysign(1.0, y)):
return
self.fail('%r not identical to %r' % (x, y))