当前位置: 首页>>代码示例>>Python>>正文


Python math.copysign方法代码示例

本文整理汇总了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 
开发者ID:JoaoFelipe,项目名称:apted,代码行数:22,代码来源:apted.py

示例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]) 
开发者ID:ryfeus,项目名称:lambda-packs,代码行数:24,代码来源:_trustregion.py

示例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)) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:24,代码来源:test_complex.py

示例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) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:22,代码来源:test_formatting.py

示例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 
开发者ID:JianGoForIt,项目名称:YellowFin_Pytorch,代码行数:24,代码来源:yellowfin_backup.py

示例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: 
开发者ID:nojanath,项目名称:SublimeKSP,代码行数:8,代码来源:simple_eval.py

示例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 
开发者ID:Naman-ntc,项目名称:3D-HourGlass-Network,代码行数:14,代码来源:Inflate.py

示例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) 
开发者ID:AndyGrant,项目名称:OpenBench,代码行数:7,代码来源:stats.py

示例9: _sign

# 需要导入模块: import math [as 别名]
# 或者: from math import copysign [as 别名]
def _sign(x):
    return int(copysign(1, x))

# vim:ts=4:sw=4:et 
开发者ID:MediaBrowser,项目名称:plugin.video.emby,代码行数:6,代码来源:relativedelta.py

示例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]) 
开发者ID:irmen,项目名称:Pyro5,代码行数:11,代码来源:test_serialize.py

示例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 
开发者ID:ryfeus,项目名称:lambda-packs,代码行数:39,代码来源:common.py

示例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 
开发者ID:ryfeus,项目名称:lambda-packs,代码行数:34,代码来源:_multivariate.py

示例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))) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:7,代码来源:test_float.py

示例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) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:17,代码来源:test_float.py

示例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)) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:11,代码来源:test_float.py


注:本文中的math.copysign方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。