# Python math.copysign() Examples

The following are 30 code examples for showing how to use math.copysign(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module , or try the search function .

Example 1
 Project: apted   Author: JoaoFelipe   File: apted.py    License: MIT License 6 votes  ```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 ```
Example 2
 Project: lambda-packs   Author: ryfeus   File: _trustregion.py    License: MIT License 6 votes  ```def get_boundaries_intersections(self, z, 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]) ```
Example 3
 Project: ironpython2   Author: IronLanguages   File: test_complex.py    License: Apache License 2.0 6 votes  ```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)) ```
Example 4
 Project: ironpython2   Author: IronLanguages   File: test_formatting.py    License: Apache License 2.0 6 votes  ```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) ```
Example 5
 Project: BinderFilter   Author: dxwu   File: test_complex.py    License: MIT License 6 votes  ```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)) ```
Example 6
 Project: oss-ftp   Author: aliyun   File: test_complex.py    License: MIT License 6 votes  ```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)) ```
Example 7
 Project: GraphicDesignPatternByPython   Author: Relph1119   File: _trustregion.py    License: MIT License 6 votes  ```def get_boundaries_intersections(self, z, 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]) ```
Example 8
 Project: YellowFin_Pytorch   Author: JianGoForIt   File: yellowfin_backup.py    License: Apache License 2.0 6 votes  ```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 ```
Example 9
 Project: SublimeKSP   Author: nojanath   File: simple_eval.py    License: GNU General Public License v3.0 5 votes  ```def kontakt_divide(a, b):
return(int(math.copysign(abs(a) // abs(b), a / b)))

########################################
# Defaults for the evaluator: ```
Example 10
 Project: 3D-HourGlass-Network   Author: Naman-ntc   File: Inflate.py    License: MIT License 5 votes  ```def inflateconv(conv3d, conv):
tempSize = conv3d.conv.weight.data.size()
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 ```
Example 11
 Project: OpenBench   Author: AndyGrant   File: stats.py    License: GNU General Public License v3.0 5 votes  ```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) ```
Example 12
 Project: plugin.video.emby   Author: MediaBrowser   File: relativedelta.py    License: GNU General Public License v3.0 5 votes  ```def _sign(x):
return int(copysign(1, x))

# vim:ts=4:sw=4:et ```
Example 13
 Project: recruit   Author: Frank-qlu   File: relativedelta.py    License: Apache License 2.0 5 votes  ```def _sign(x):
return int(copysign(1, x))

# vim:ts=4:sw=4:et ```
Example 14
 Project: Pyro5   Author: irmen   File: test_serialize.py    License: MIT License 5 votes  ```def testWeirdFloats(self):
ser = Pyro5.serializers.serializers[config.SERIALIZER]
p = ser.dumps([float("+inf"), float("-inf"), float("nan")])
assert math.isinf(s2)
assert math.copysign(1, s2) == 1.0
assert math.isinf(s2)
assert math.copysign(1, s2) == -1.0
assert math.isnan(s2) ```
Example 15
 Project: lambda-packs   Author: ryfeus   File: common.py    License: MIT License 5 votes  ```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 ```
Example 16
 Project: lambda-packs   Author: ryfeus   File: _multivariate.py    License: MIT License 5 votes  ```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 
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 ```
Example 17
 Project: ironpython2   Author: IronLanguages   File: test_float.py    License: Apache License 2.0 5 votes  ```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))) ```
Example 18
 Project: ironpython2   Author: IronLanguages   File: test_float.py    License: Apache License 2.0 5 votes  ```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) ```
Example 19
 Project: ironpython2   Author: IronLanguages   File: test_float.py    License: Apache License 2.0 5 votes  ```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)) ```
Example 20
 Project: ironpython2   Author: IronLanguages   File: test_math.py    License: Apache License 2.0 5 votes  ```def testCopysign(self):
self.assertEqual(math.copysign(1, 42), 1.0)
self.assertEqual(math.copysign(0., 42), 0.0)
self.assertEqual(math.copysign(1., -42), -1.0)
self.assertEqual(math.copysign(3, 0.), 3.0)
self.assertEqual(math.copysign(4., -0.), -4.0)

self.assertRaises(TypeError, math.copysign)
# copysign should let us distinguish signs of zeros
self.assertEqual(math.copysign(1., 0.), 1.)
self.assertEqual(math.copysign(1., -0.), -1.)
self.assertEqual(math.copysign(INF, 0.), INF)
self.assertEqual(math.copysign(INF, -0.), NINF)
self.assertEqual(math.copysign(NINF, 0.), INF)
self.assertEqual(math.copysign(NINF, -0.), NINF)
# and of infinities
self.assertEqual(math.copysign(1., INF), 1.)
self.assertEqual(math.copysign(1., NINF), -1.)
self.assertEqual(math.copysign(INF, INF), INF)
self.assertEqual(math.copysign(INF, NINF), NINF)
self.assertEqual(math.copysign(NINF, INF), INF)
self.assertEqual(math.copysign(NINF, NINF), NINF)
self.assertTrue(math.isnan(math.copysign(NAN, 1.)))
self.assertTrue(math.isnan(math.copysign(NAN, INF)))
self.assertTrue(math.isnan(math.copysign(NAN, NINF)))
self.assertTrue(math.isnan(math.copysign(NAN, NAN)))
# copysign(INF, NAN) may be INF or it may be NINF, since
# we don't know whether the sign bit of NAN is set on any
# given platform.
self.assertTrue(math.isinf(math.copysign(INF, NAN)))
# similarly, copysign(2., NAN) could be 2. or -2.
self.assertEqual(abs(math.copysign(2., NAN)), 2.) ```
Example 21
 Project: ironpython2   Author: IronLanguages   File: test_math.py    License: Apache License 2.0 5 votes  ```def testTanh(self):
self.assertRaises(TypeError, math.tanh)
self.ftest('tanh(0)', math.tanh(0), 0)
self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0)
self.ftest('tanh(inf)', math.tanh(INF), 1)
self.ftest('tanh(-inf)', math.tanh(NINF), -1)
self.assertTrue(math.isnan(math.tanh(NAN)))
# check that tanh(-0.) == -0. on IEEE 754 systems
if float.__getformat__("double").startswith("IEEE"):
self.assertEqual(math.tanh(-0.), -0.)
self.assertEqual(math.copysign(1., math.tanh(-0.)),
math.copysign(1., -0.)) ```
Example 22
 Project: ironpython2   Author: IronLanguages   File: test_getargs2.py    License: Apache License 2.0 5 votes  ```def assertEqualWithSign(self, actual, expected):
self.assertEqual(actual, expected)
self.assertEqual(math.copysign(1, actual), math.copysign(1, expected)) ```
Example 23
 Project: WonderPy   Author: playi   File: wwMath.py    License: MIT License 5 votes  ```def sqrt_signed(a):
return math.copysign(math.sqrt(math.fabs(a))) ```
Example 24
 Project: polyline   Author: hicsail   File: codec.py    License: MIT License 5 votes  ```def _py2_round(self, x):
# The polyline algorithm uses Python 2's way of rounding
return int(math.copysign(math.floor(math.fabs(x) + 0.5), x)) ```
Example 25
 Project: netutils-linux   Author: strizhechenko   File: rate_math.py    License: MIT License 5 votes  ```def round_(value, precision=0):
"""
:param value: float value
:param precision: how much digits after ',' we need
:return: rounded float value
"""
precision = 10 ** precision
return float(math.floor((value * precision) + math.copysign(0.5, value))) / precision ```
Example 26
 Project: pysat   Author: pysathq   File: lbx.py    License: MIT License 5 votes  ```def _map_extlit(self, l):
"""
Map an external variable to an internal one if necessary.

This method is used when new clauses are added to the formula
incrementally, which may result in introducing new variables
clashing with the previously used *clause selectors*. The method
makes sure no clash occurs, i.e. it maps the original variables
used in the new problem clauses to the newly introduced auxiliary

Given an integer literal, a fresh literal is returned. The returned
integer has the same sign as the input literal.

:param l: literal to map
:type l: int

:rtype: int
"""

v = abs(l)

if v in self.vmap.e2i:
return int(copysign(self.vmap.e2i[v], l))
else:
self.topv += 1

self.vmap.e2i[v] = self.topv
self.vmap.i2e[self.topv] = v

return int(copysign(self.topv, l)) ```
Example 27
 Project: pysat   Author: pysathq   File: mcsls.py    License: MIT License 5 votes  ```def _map_extlit(self, l):
"""
Map an external variable to an internal one if necessary.

This method is used when new clauses are added to the formula
incrementally, which may result in introducing new variables
clashing with the previously used *clause selectors*. The method
makes sure no clash occurs, i.e. it maps the original variables
used in the new problem clauses to the newly introduced auxiliary

Given an integer literal, a fresh literal is returned. The returned
integer has the same sign as the input literal.

:param l: literal to map
:type l: int

:rtype: int
"""

v = abs(l)

if v in self.vmap.e2i:
return int(copysign(self.vmap.e2i[v], l))
else:
self.topv += 1

self.vmap.e2i[v] = self.topv
self.vmap.i2e[self.topv] = v

return int(copysign(self.topv, l)) ```
Example 28
 Project: pysat   Author: pysathq   File: rc2.py    License: MIT License 5 votes  ```def _map_extlit(self, l):
"""
Map an external variable to an internal one if necessary.

This method is used when new clauses are added to the
formula incrementally, which may result in introducing new
variables clashing with the previously used *clause
selectors*. The method makes sure no clash occurs, i.e. it
maps the original variables used in the new problem
clauses to the newly introduced auxiliary variables (see

Given an integer literal, a fresh literal is returned. The
returned integer has the same sign as the input literal.

:param l: literal to map
:type l: int

:rtype: int
"""

v = abs(l)

if v in self.vmap.e2i:
return int(copysign(self.vmap.e2i[v], l))
else:
self.topv += 1

self.vmap.e2i[v] = self.topv
self.vmap.i2e[self.topv] = v

return int(copysign(self.topv, l))

#
#============================================================================== ```
Example 29
 Project: pysat   Author: pysathq   File: card.py    License: MIT License 5 votes  ```def _update_vids(cls, cnf, vpool):
"""
Update variable ids in the given formula and id pool.

:param cnf: a list of literals in the sum.
:param vpool: the value of bound :math:`k`.

:type cnf: :class:`.formula.CNFPlus`
:type vpool: :class:`.formula.IDPool`
"""

top, vmap = vpool.top, {}  # current top and variable mapping

# creating a new variable mapping, taking into
# account variables marked as "occupied"
while top < cnf.nv:
top += 1
vpool.top += 1

while vpool._occupied and vpool.top >= vpool._occupied:
if vpool.top <= vpool._occupied + 1:
vpool.top = vpool._occupied + 1

vpool._occupied.pop(0)

vmap[top] = vpool.top

# updating the clauses
for cl in cnf.clauses:
cl[:] = map(lambda l: int(math.copysign(vmap[abs(l)], l)) if abs(l) in vmap else l, cl)

# updating the number of variables
cnf.nv = vpool.top ```
Example 30
 Project: faces   Author: skarlekar   File: relativedelta.py    License: GNU General Public License v2.0 5 votes  ```def _sign(x):
return int(copysign(1, x))

# vim:ts=4:sw=4:et ```