Python math.copysign() Examples

The following are code examples for showing how to use math.copysign(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: test_complex.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
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 2
Project: UR5_Controller   Author: tsinghua-rll   File: quaternion.py    MIT License 6 votes vote down vote up
def to_euler(q):
    # rpy
    sinr = 2.0 * (q[0] * q[1] + q[2] * q[3])
    cosr = 1.0 - 2.0 * (q[1] * q[1] + q[2] * q[2])
    roll = math.atan2(sinr, cosr)

    sinp = 2.0 * (q[0] * q[2] - q[3] * q[1])
    if math.fabs(sinp) >= 1.:
        pitch = math.copysign(np.pi / 2., sinp)
    else:
        pitch = math.asin(sinp)

    siny = 2.0 * (q[0] * q[3] + q[1] * q[2])
    cosy = 1.0 - 2.0 * (q[2] * q[2] + q[3] * q[3])
    yaw = math.atan2(siny, cosy)

    return np.asarray((roll, pitch, yaw), np.float32) 
Example 3
Project: apted   Author: JoaoFelipe   File: apted.py    MIT License 6 votes vote down vote up
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 4
Project: NiujiaoDebugger   Author: MrSrc   File: test_cmath.py    GNU General Public License v3.0 6 votes vote down vote up
def assertFloatIdentical(self, x, y):
        """Fail unless 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 math.isnan(x) or math.isnan(y):
            if math.isnan(x) and math.isnan(y):
                return
        elif x == y:
            if x != 0.0:
                return
            # both zero; check that signs match
            elif math.copysign(1.0, x) == math.copysign(1.0, y):
                return
            else:
                msg += ': zeros have different signs'
        self.fail(msg.format(x, y)) 
Example 5
Project: NiujiaoDebugger   Author: MrSrc   File: test_complex.py    GNU General Public License v3.0 6 votes vote down vote up
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: FX-RER-Value-Extraction   Author: tsKenneth   File: _trustregion.py    MIT License 6 votes vote down vote up
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]) 
Example 7
Project: PySail-426   Author: j3b4   File: SimulazioneRegata300.py    GNU General Public License v3.0 6 votes vote down vote up
def calcolaventogeostrofico(lat,GradientePressione,R):
    omega=2*math.pi/(24*3600)#rotazione terrestre
    f=2*omega*math.sin(lat)#parametro di coriolis
    densitaaria=1.2#kgm/mc vale per T=20gradi
    R=R*1853.0#curvatura isobare espressa in m
    GradientePressione=GradientePressione*100.0/1853.0#Gradiente espresso in Pa/m
    segno=GradientePressione/math.copysign(GradientePressione,1)
    a=segno/R
    b=-f
    c=math.copysign(GradientePressione,1)/densitaaria
    discriminante=(b**2-4*a*c)
    if discriminante >0:
        tws=(-b-discriminante**0.5)/(2*a)
        tws=tws*3600.0/1853.0#converte tws in knts
    else:
        tws=0.0#caso del centro di alta pressione
    return tws 
Example 8
Project: PySail-426   Author: j3b4   File: SimulazioneRegata300.py    GNU General Public License v3.0 6 votes vote down vote up
def interno(poligono,pto):
    #poligono orientato in senso orario
    somma=0
    for i in range(0,len(poligono)-1):
        v1=poligono[i]
        v2=poligono[i+1]
        rlv1=math.atan2((v1[1]-pto[1]),(v1[0]-pto[0]))
        if rlv1<0:rlv1=2*math.pi+rlv1
        rlv2=math.atan2((v2[1]-pto[1]),(v2[0]-pto[0]))
        if rlv2<0:rlv2=2*math.pi+rlv2
        angolo=math.copysign(rlv2-rlv1,1)
        if angolo>math.pi:
            angolo=2*math.pi-angolo
        somma=somma+angolo
    if somma<2*math.pi:
        Interno=False
    else:
        Interno=True
    return Interno 
Example 9
Project: PySail-426   Author: j3b4   File: ModuloBarca01.py    GNU General Public License v3.0 6 votes vote down vote up
def Randa(self):
        aw=self.AW()
        awa=aw[1]
        randa=[]
        #if math.copysign(awa,1)<math.radians(25):
        if self.Speed()<=0:
            randa=[(0,35.0),(0,-75.0)]
        else:
            if awa>math.pi/2:
                awa=math.pi/2
            if awa<-math.pi/2:
                awa=-math.pi/2
            segno=awa/math.copysign(awa,1)
            bezier=Bezier([(0,35),
                           (-40*math.sin(awa+segno*math.radians(30)),35-40*math.cos(awa+segno*math.radians(30))),
                           (-110*math.sin(awa-segno*math.radians(25)),35-110*math.cos(awa-segno*math.radians(25)))])
            for i in range(0,11):
                i=i*0.1
                randa.append(bezier.calcolavalore(i)) 
        return randa


#FUNZIONI 
Example 10
Project: PySail-426   Author: j3b4   File: SimulazioneRegata316.py    GNU General Public License v3.0 6 votes vote down vote up
def ventogeostrofico(lat,GradientePressione,R):
    if R==0.0 or GradientePressione==0.0:
        tws=0
    else:
        omega=2*math.pi/(24*3600)#rotazione terrestre
        f=2*omega*math.sin(lat)#parametro di coriolis
        densitaaria=1.2#kgm/mc vale per T=20gradi
        R=R*1853.0#raggio di curvatura isobare espressa in m
        GradientePressione=GradientePressione*100.0/1853.0#Gradiente espresso in Pa/m
        segno=GradientePressione/math.copysign(GradientePressione,1)
        a=segno/R
        b=-f
        c=math.copysign(GradientePressione,1)/densitaaria
        discriminante=(b**2-4*a*c)
        if discriminante >0:
            tws=(-b-discriminante**0.5)/(2*a)
            tws=tws*3600.0/1853.0#converte tws in knts
        else:
            tws=0.0#caso del centro di alta pressione
    return tws 
Example 11
Project: PySail-426   Author: j3b4   File: SimulazioneRegata316.py    GNU General Public License v3.0 6 votes vote down vote up
def ventogeostroficoCentroAzione(PCentroAzione,LatCentroAzione,LonCentroAzione,extension,lat,lon):
    #campo di pressione: P=0.5*(PCentro-1013)*cos(pi/extension*r)+(PCentro+1013)*0.5, per r<=extension, P=1013 per r >extension
    #r distanza dal centro d'azione e raggio curvatura isobara
    losso=lossodromica(LatCentroAzione,LonCentroAzione,lat,lon)
    r=losso[0]
    brg=losso[1]
    tws=0
    twd=0
    segno=0
    exp=0
    if r<extension:
        if PCentroAzione>1013:
            segno=1
        else:
            segno=-1
        #GradientePressione=-0.5*(PCentroAzione-1013)*math.pi/extension*math.sin(math.pi/extension*r)
        GradientePressione=0.5*(PCentroAzione-1013)*math.pi/extension*math.sin(math.pi/extension*r)
        GradientePressione=math.copysign(GradientePressione,1)
        tws=ventogeostrofico(LatCentroAzione,segno*GradientePressione,r)
        if LatCentroAzione>0:
            twd=riduci360(brg-segno*math.radians(100))#emisfero Nord
        else:
            twd=riduci360(brg+segno*math.radians(100))#emisfero Sud
    return tws,twd 
Example 12
Project: PySail-426   Author: j3b4   File: SimulazioneRegata316.py    GNU General Public License v3.0 6 votes vote down vote up
def interno(poligono,pto):
    #poligono orientato in senso orario
    somma=0
    for i in range(0,len(poligono)-1):
        v1=poligono[i]
        v2=poligono[i+1]
        rlv1=math.atan2((v1[1]-pto[1]),(v1[0]-pto[0]))
        if rlv1<0:rlv1=2*math.pi+rlv1
        rlv2=math.atan2((v2[1]-pto[1]),(v2[0]-pto[0]))
        if rlv2<0:rlv2=2*math.pi+rlv2
        angolo=math.copysign(rlv2-rlv1,1)
        if angolo>math.pi:
            angolo=2*math.pi-angolo
        somma=somma+angolo
    if somma<1.99*math.pi:
        Interno=False
    else:
        Interno=True
    return Interno 
Example 13
Project: pyblish-win   Author: pyblish   File: decimal.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def from_float(cls, f):
        """Converts a float to a decimal number, exactly.

        Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
        Since 0.1 is not exactly representable in binary floating point, the
        value is stored as the nearest representable value which is
        0x1.999999999999ap-4.  The exact equivalent of the value in decimal
        is 0.1000000000000000055511151231257827021181583404541015625.

        >>> Decimal.from_float(0.1)
        Decimal('0.1000000000000000055511151231257827021181583404541015625')
        >>> Decimal.from_float(float('nan'))
        Decimal('NaN')
        >>> Decimal.from_float(float('inf'))
        Decimal('Infinity')
        >>> Decimal.from_float(-float('inf'))
        Decimal('-Infinity')
        >>> Decimal.from_float(-0.0)
        Decimal('-0')

        """
        if isinstance(f, (int, long)):        # handle integer inputs
            return cls(f)
        if _math.isinf(f) or _math.isnan(f):  # raises TypeError if not a float
            return cls(repr(f))
        if _math.copysign(1.0, f) == 1.0:
            sign = 0
        else:
            sign = 1
        n, d = abs(f).as_integer_ratio()
        k = d.bit_length() - 1
        result = _dec_from_triple(sign, str(n*5**k), -k)
        if cls is Decimal:
            return result
        else:
            return cls(result) 
Example 14
Project: pyblish-win   Author: pyblish   File: test_float.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
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 15
Project: pyblish-win   Author: pyblish   File: test_float.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
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 16
Project: pyblish-win   Author: pyblish   File: test_float.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
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 17
Project: pyblish-win   Author: pyblish   File: test_math.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
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 18
Project: UR5_Controller   Author: tsinghua-rll   File: quaternion.py    MIT License 5 votes vote down vote up
def from_matrix_to_q(mat):
    qw = math.sqrt(max(0, 1 + mat[0][0] + mat[1][1] + mat[2][2])) / 2.0
    qi = math.copysign(math.sqrt(max(0, 1 + mat[0][0] - mat[1][1] - mat[2][2])) / 2.0, mat[2][1] - mat[1][2])
    qj = math.copysign(math.sqrt(max(0, 1 - mat[0][0] + mat[1][1] - mat[2][2])) / 2.0, mat[0][2] - mat[2][0])
    qk = math.copysign(math.sqrt(max(0, 1 - mat[0][0] - mat[1][1] + mat[2][2])) / 2.0, mat[1][0] - mat[0][1])
    return np.asarray((qw, qi, qj, qk), dtype=np.float32) 
Example 19
Project: AshsSDK   Author: thehappydinoa   File: relativedelta.py    MIT License 5 votes vote down vote up
def _sign(x):
    return int(copysign(1, x))

# vim:ts=4:sw=4:et 
Example 20
Project: RLBotPack   Author: RLBot   File: util.py    MIT License 5 votes vote down vote up
def Range(value, max_value):
    """Constrains value to [-max_value, max_value] range"""
    if abs(value) > max_value:
        value = math.copysign(max_value, value)
    return value 
Example 21
Project: RLBotPack   Author: RLBot   File: Util.py    MIT License 5 votes vote down vote up
def Range(v, r, n=0):
    if abs(v) > r:
        v = math.copysign(r, v)
    if abs(v) < n:
        v = math.copysign(n, v)
    return v 
Example 22
Project: RLBotPack   Author: RLBot   File: Util.py    MIT License 5 votes vote down vote up
def curve3(x):
    s = abs(x)**0.25 * math.copysign(1, x)
    return Range(s, 1) 
Example 23
Project: RLBotPack   Author: RLBot   File: Util.py    MIT License 5 votes vote down vote up
def larg(v, l):
    if abs(v) < l:
        v = math.copysign(l, v)
    return v 
Example 24
Project: RLBotPack   Author: RLBot   File: util.py    MIT License 5 votes vote down vote up
def Range(value, max_value):
    """Constrains value to [-max_value, max_value] range"""
    if abs(value) > max_value:
        value = math.copysign(max_value, value)
    return value 
Example 25
Project: SublimeKSP   Author: nojanath   File: simple_eval.py    GNU General Public License v3.0 5 votes vote down vote up
def kontakt_divide(a, b):
    return(int(math.copysign(abs(a) // abs(b), a / b)))


########################################
# Defaults for the evaluator: 
Example 26
Project: python-minifier   Author: dflook   File: expressions.py    MIT License 5 votes vote down vote up
def Num(draw) -> ast.AST:
    def to_node(n) -> ast.AST:
        if isinstance(n, int):
            return ast.Num(n) if n >= 0 else ast.UnaryOp(ast.USub(), ast.Num(abs(n)))
        elif isinstance(n, float):
            return ast.Num(n) if math.copysign(1.0, n) > 0.0 else ast.UnaryOp(ast.USub(), ast.Num(abs(n)))
        elif isinstance(n, complex):
            node = ast.parse(str(n), mode='eval')
            return node.body

        raise ValueError(n)

    return to_node(draw(integers() | floats(allow_nan=False) | complex_numbers(allow_infinity=True, allow_nan=False))) 
Example 27
Project: jawfish   Author: war-and-code   File: decimal.py    MIT License 5 votes vote down vote up
def from_float(cls, f):
        """Converts a float to a decimal number, exactly.

        Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
        Since 0.1 is not exactly representable in binary floating point, the
        value is stored as the nearest representable value which is
        0x1.999999999999ap-4.  The exact equivalent of the value in decimal
        is 0.1000000000000000055511151231257827021181583404541015625.

        >>> Decimal.from_float(0.1)
        Decimal('0.1000000000000000055511151231257827021181583404541015625')
        >>> Decimal.from_float(float('nan'))
        Decimal('NaN')
        >>> Decimal.from_float(float('inf'))
        Decimal('Infinity')
        >>> Decimal.from_float(-float('inf'))
        Decimal('-Infinity')
        >>> Decimal.from_float(-0.0)
        Decimal('-0')

        """
        if isinstance(f, int):                # handle integer inputs
            return cls(f)
        if not isinstance(f, float):
            raise TypeError("argument must be int or float.")
        if _math.isinf(f) or _math.isnan(f):
            return cls(repr(f))
        if _math.copysign(1.0, f) == 1.0:
            sign = 0
        else:
            sign = 1
        n, d = abs(f).as_integer_ratio()
        k = d.bit_length() - 1
        result = _dec_from_triple(sign, str(n*5**k), -k)
        if cls is Decimal:
            return result
        else:
            return cls(result) 
Example 28
Project: clacker   Author: wez   File: matrix.py    GNU General Public License v2.0 5 votes vote down vote up
def placeCollision(self, x, y, k):
        ''' collision; find an alternate position.  We do this by
            walking the matrix and looking for the closest candidate
            position. '''
        best = None
        limit_x, limit_y = self._getMaxBounds()
        grow = self._allowGrowing()
        for x2 in range(0, limit_x + 1):
            for y2 in range(0, limit_y + 1):
                if (self.rows[y2] is None) or (self.rows[y2][x2] is None):
                    dy = y2 - y
                    if y2 == limit_y:
                        ''' make it more expensive to create a new row '''
                        if not grow:
                            continue
                        dy += math.copysign(10, y2)
                    dx = x2 - x
                    if x2 == limit_x:
                        ''' make it more expensive to create a new col '''
                        if not grow:
                            continue
                        dx += math.copysign(10, x2)
                    distance = (dx * dx) + (dy * dy)

                    #print('candidate ', x2, y2, ' has distance ', distance, dx, dy)

                    if (best is None) or (distance < best[0]):
                        best = (distance, x2, y2)
                        #print('best so far: ', x2, y2, distance, dx, dy)

        x2 = best[1]
        y2 = best[2]
        #print('resolved to ', x2, y2)

        if self.rows[y2] is None:
            self.rows[y2] = SparseList()

        self.rows[y2][x2] = k
        self.maxCols = max(x2, self.maxCols) 
Example 29
Project: 3D-HourGlass-Network   Author: Naman-ntc   File: Inflate.py    MIT License 5 votes vote down vote up
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 
Example 30
Project: LaserTOF   Author: kyleuckert   File: ticker.py    MIT License 5 votes vote down vote up
def _compute_offset(self):
        locs = self.locs
        if locs is None or not len(locs):
            self.offset = 0
            return
        # Restrict to visible ticks.
        vmin, vmax = sorted(self.axis.get_view_interval())
        locs = np.asarray(locs)
        locs = locs[(vmin <= locs) & (locs <= vmax)]
        if not len(locs):
            self.offset = 0
            return
        lmin, lmax = locs.min(), locs.max()
        # Only use offset if there are at least two ticks and every tick has
        # the same sign.
        if lmin == lmax or lmin <= 0 <= lmax:
            self.offset = 0
            return
        # min, max comparing absolute values (we want division to round towards
        # zero so we work on absolute values).
        abs_min, abs_max = sorted([abs(float(lmin)), abs(float(lmax))])
        sign = math.copysign(1, lmin)
        # What is the smallest power of ten such that abs_min and abs_max are
        # equal up to that precision?
        # Note: Internally using oom instead of 10 ** oom avoids some numerical
        # accuracy issues.
        oom_max = np.ceil(math.log10(abs_max))
        oom = 1 + next(oom for oom in itertools.count(oom_max, -1)
                       if abs_min // 10 ** oom != abs_max // 10 ** oom)
        if (abs_max - abs_min) / 10 ** oom <= 1e-2:
            # Handle the case of straddling a multiple of a large power of ten
            # (relative to the span).
            # What is the smallest power of ten such that abs_min and abs_max
            # are no more than 1 apart at that precision?
            oom = 1 + next(oom for oom in itertools.count(oom_max, -1)
                           if abs_max // 10 ** oom - abs_min // 10 ** oom > 1)
        # Only use offset if it saves at least _offset_threshold digits.
        n = self._offset_threshold - 1
        self.offset = (sign * (abs_max // 10 ** oom) * 10 ** oom
                       if abs_max // 10 ** oom >= 10**n
                       else 0) 
Example 31
Project: LaserTOF   Author: kyleuckert   File: ticker.py    MIT License 5 votes vote down vote up
def scale_range(vmin, vmax, n=1, threshold=100):
    dv = abs(vmax - vmin)  # > 0 as nonsingular is called before.
    meanv = (vmax + vmin) / 2
    if abs(meanv) / dv < threshold:
        offset = 0
    else:
        offset = math.copysign(10 ** (math.log10(abs(meanv)) // 1), meanv)
    scale = 10 ** (math.log10(dv / n) // 1)
    return scale, offset 
Example 32
Project: LaserTOF   Author: kyleuckert   File: common.py    MIT License 5 votes vote down vote up
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 33
Project: LaserTOF   Author: kyleuckert   File: _multivariate.py    MIT License 5 votes vote down vote up
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 
Example 34
Project: RouteOptimization   Author: andre-le   File: geomath.py    MIT License 5 votes vote down vote up
def copysign(x, y):
    """return x with the sign of y (missing from python 2.5.2)"""

    if sys.version_info > (2, 6):
      return math.copysign(x, y)

    return math.fabs(x) * (-1 if y < 0 or (y == 0 and 1/y < 0) else 1) 
Example 35
Project: OpenBench   Author: AndyGrant   File: utils.py    GNU General Public License v3.0 5 votes vote down vote up
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 36
Project: NiujiaoDebugger   Author: MrSrc   File: test_float.py    GNU General Public License v3.0 5 votes vote down vote up
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 37
Project: NiujiaoDebugger   Author: MrSrc   File: test_float.py    GNU General Public License v3.0 5 votes vote down vote up
def test_inf_signs(self):
        self.assertEqual(copysign(1.0, float('inf')), 1.0)
        self.assertEqual(copysign(1.0, float('-inf')), -1.0) 
Example 38
Project: NiujiaoDebugger   Author: MrSrc   File: test_float.py    GNU General Public License v3.0 5 votes vote down vote up
def test_nan_signs(self):
        # When using the dtoa.c code, the sign of float('nan') should
        # be predictable.
        self.assertEqual(copysign(1.0, float('nan')), 1.0)
        self.assertEqual(copysign(1.0, float('-nan')), -1.0) 
Example 39
Project: NiujiaoDebugger   Author: MrSrc   File: test_float.py    GNU General Public License v3.0 5 votes vote down vote up
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 40
Project: NiujiaoDebugger   Author: MrSrc   File: test_math.py    GNU General Public License v3.0 5 votes vote down vote up
def testTanhSign(self):
        # check that tanh(-0.) == -0. on IEEE 754 systems
        self.assertEqual(math.tanh(-0.), -0.)
        self.assertEqual(math.copysign(1., math.tanh(-0.)),
                         math.copysign(1., -0.)) 
Example 41
Project: NiujiaoDebugger   Author: MrSrc   File: test_statistics.py    GNU General Public License v3.0 5 votes vote down vote up
def sign(x):
    """Return -1.0 for negatives, including -0.0, otherwise +1.0."""
    return math.copysign(1, x) 
Example 42
Project: NiujiaoDebugger   Author: MrSrc   File: test_statistics.py    GNU General Public License v3.0 5 votes vote down vote up
def test_float_zeroes(self):
        nzero = math.copysign(0.0, -1)
        self.assertTrue(approx_equal(nzero, 0.0, tol=0.1, rel=0.1)) 
Example 43
Project: NiujiaoDebugger   Author: MrSrc   File: test_decimal.py    GNU General Public License v3.0 5 votes vote down vote up
def test_nan_to_float(self):
        # Test conversions of decimal NANs to float.
        # See http://bugs.python.org/issue15544
        Decimal = self.decimal.Decimal
        for s in ('nan', 'nan1234', '-nan', '-nan2468'):
            f = float(Decimal(s))
            self.assertTrue(math.isnan(f))
            sign = math.copysign(1.0, f)
            self.assertEqual(sign, -1.0 if s.startswith('-') else 1.0) 
Example 44
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: ticker.py    MIT License 5 votes vote down vote up
def _compute_offset(self):
        locs = self.locs
        # Restrict to visible ticks.
        vmin, vmax = sorted(self.axis.get_view_interval())
        locs = np.asarray(locs)
        locs = locs[(vmin <= locs) & (locs <= vmax)]
        if not len(locs):
            self.offset = 0
            return
        lmin, lmax = locs.min(), locs.max()
        # Only use offset if there are at least two ticks and every tick has
        # the same sign.
        if lmin == lmax or lmin <= 0 <= lmax:
            self.offset = 0
            return
        # min, max comparing absolute values (we want division to round towards
        # zero so we work on absolute values).
        abs_min, abs_max = sorted([abs(float(lmin)), abs(float(lmax))])
        sign = math.copysign(1, lmin)
        # What is the smallest power of ten such that abs_min and abs_max are
        # equal up to that precision?
        # Note: Internally using oom instead of 10 ** oom avoids some numerical
        # accuracy issues.
        oom_max = np.ceil(math.log10(abs_max))
        oom = 1 + next(oom for oom in itertools.count(oom_max, -1)
                       if abs_min // 10 ** oom != abs_max // 10 ** oom)
        if (abs_max - abs_min) / 10 ** oom <= 1e-2:
            # Handle the case of straddling a multiple of a large power of ten
            # (relative to the span).
            # What is the smallest power of ten such that abs_min and abs_max
            # are no more than 1 apart at that precision?
            oom = 1 + next(oom for oom in itertools.count(oom_max, -1)
                           if abs_max // 10 ** oom - abs_min // 10 ** oom > 1)
        # Only use offset if it saves at least _offset_threshold digits.
        n = self._offset_threshold - 1
        self.offset = (sign * (abs_max // 10 ** oom) * 10 ** oom
                       if abs_max // 10 ** oom >= 10**n
                       else 0) 
Example 45
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: ticker.py    MIT License 5 votes vote down vote up
def scale_range(vmin, vmax, n=1, threshold=100):
    dv = abs(vmax - vmin)  # > 0 as nonsingular is called before.
    meanv = (vmax + vmin) / 2
    if abs(meanv) / dv < threshold:
        offset = 0
    else:
        offset = math.copysign(10 ** (math.log10(abs(meanv)) // 1), meanv)
    scale = 10 ** (math.log10(dv / n) // 1)
    return scale, offset 
Example 46
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: common.py    MIT License 5 votes vote down vote up
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 47
Project: dwasm   Author: bloodstalker   File: execute.py    GNU General Public License v3.0 5 votes vote down vote up
def run_copysign(self, opcodeint, immediates):
        val2 = self.machinestate.Stack_Omni.pop()
        val1 = self.machinestate.Stack_Omni.pop()
        if opcodeint == 152 or opcodeint == 166:
            self.machinestate.Stack_Omni.append(math.copysign(val1, val2))
        else:
            raise Exception(Colors.red + 'invalid max instruction' + Colors.ENDC) 
Example 48
Project: recruit   Author: Frank-qlu   File: relativedelta.py    Apache License 2.0 5 votes vote down vote up
def _sign(x):
    return int(copysign(1, x))

# vim:ts=4:sw=4:et 
Example 49
Project: 2018-1-OSS-E7   Author: 18-1-SKKU-OSS   File: bmath.py    MIT License 5 votes vote down vote up
def sign(x):
	"""Return sign of number"""
	return int(copysign(1,x))

#------------------------------------------------------------------------------- 
Example 50
Project: 2018-1-OSS-E7   Author: 18-1-SKKU-OSS   File: bmath.py    MIT License 5 votes vote down vote up
def cubic(a, b, c, d=None, eps=_accuracy):
	if d is not None: # (ax^3 + bx^2 + cx + d = 0)
		a, b, c = b/float(a), c/float(a), d/float(a)

	Q = (a*a - 3.0*b) / 9.0
	R = (2.*a**3 - 9.*a*b + 27.*c)/54.

	R2 = R**2
	Q3 = Q**3
	if R2 < Q3:	# the cubic has 3 real solutions
		theta = acos(R/sqrt(Q3))
		sqrt_Q = sqrt(Q)
		x1 = -2. * sqrt_Q * cos(theta/3.) - a/3.
		x2 = -2. * sqrt_Q * cos((theta+2.*pi)/3.) - a/3.
		x3 = -2. * sqrt_Q * cos((theta-2.*pi)/3.) - a/3.
		return x1,x2,x3

	A = -copysign(1.0,R) * (abs(R) + sqrt(R2 - Q3))**(1./3.)
	if abs(A)>eps:
		B = Q / A
	else:
		B = 0.0

	return (A+B) - a/3., None, None

	# imaginary roots
	# x2 = -(A+B)/2 - a/3 + i*sqrt(3)*(A-B)
	# x3 = -(A+B)/2 - a/3 - i*sqrt(3)*(A-B)

#-------------------------------------------------------------------------------
# Fit a plane to a set of points using least square fitting
#------------------------------------------------------------------------------- 
Example 51
Project: aws-cfn-plex   Author: lordmuffin   File: relativedelta.py    MIT License 5 votes vote down vote up
def _sign(x):
    return int(copysign(1, x))

# vim:ts=4:sw=4:et 
Example 52
Project: pSPRITE   Author: OmnesRes   File: diophantine.py    MIT License 5 votes vote down vote up
def sign(self, x):
        return copysign(1, x) if x else 0 
Example 53
Project: pSPRITE   Author: OmnesRes   File: diophantine.py    MIT License 5 votes vote down vote up
def sign(self, x):
        return copysign(1, x) if x else 0 
Example 54
Project: grand_central   Author: amiracle   File: relativedelta.py    MIT License 5 votes vote down vote up
def _sign(x):
    return int(copysign(1, x))

# vim:ts=4:sw=4:et 
Example 55
Project: alexa-apple-calendar   Author: zanderxyz   File: relativedelta.py    MIT License 5 votes vote down vote up
def _sign(x):
    return int(copysign(1, x))

# vim:ts=4:sw=4:et 
Example 56
Project: gopca   Author: flo-compbio   File: extract_signatures_excel.py    GNU General Public License v3.0 5 votes vote down vote up
def sign(x):
    return int(math.copysign(1.0, x)) 
Example 57
Project: gopca   Author: flo-compbio   File: extract_signatures.py    GNU General Public License v3.0 5 votes vote down vote up
def sign(x):
    return int(math.copysign(1.0, x)) 
Example 58
Project: oa_qian   Author: sunqb   File: relativedelta.py    Apache License 2.0 5 votes vote down vote up
def _sign(x):
    return int(copysign(1, x))

# vim:ts=4:sw=4:et 
Example 59
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def Pitch(signal):
	signal = np.fromstring(signal, 'Int16');
	crossing = [math.copysign(1.0, s) for s in signal]
	index = find(np.diff(crossing));
	f0=round(len(index) *RATE /(2*np.prod(len(signal))))
	return f0; 
Example 60
Project: PySail-426   Author: j3b4   File: SimulazioneRegata300.py    GNU General Public License v3.0 5 votes vote down vote up
def DisegnaFincature(self):
        self.Graficodx.delete(ALL)
        #self.Graficosx.delete("icona")
        NW=self.Bbox[0]#angolo NW
        SE=self.Bbox[1]#angolo SE
        N=25
        height=float(self.Graficodx.cget("height"))
        width=float(self.Graficodx.cget("width"))
        Df=math.log(math.tan(SE[0]/2+math.pi/4)/math.tan(NW[0]/2+math.pi/4),math.e)
        self.q=math.copysign((NW[0]-SE[0])/Df,1)
        self.FattoreDiScala=0.85*min(height/math.copysign((NW[0]-SE[0]),1),width/(self.q*math.copysign((NW[1]-SE[1]),1)))
        lat=NW[0]
        passo=(NW[0]-SE[0])*1.0/N
        for i in range(0,N+1):
            self.disegna([(lat,NW[1]),(lat,SE[1])],"darkgray","fincature")#orizontali
            lat=lat-passo
        lon=NW[1]
        passo=(NW[1]-SE[1])*1.0/N
        for i in range(0,N+1):
            self.disegna([(NW[0],lon),(SE[0],lon)],"darkgray","fincature")#verticali
            lon=lon-passo
        testo=stampalat(NW[0])
        x=-NW[1]*self.FattoreDiScala*self.q
        y=-NW[0]*self.FattoreDiScala
        self.Graficodx.create_text(x-5,y-15,text=testo,fill="darkgray",tags="fincature",anchor="e", font=MIOFONT)
        testo=stampalon(NW[1])
        self.Graficodx.create_text(x-5,y,text=testo,fill="darkgray",tags="fincature",anchor="e", font=MIOFONT)
        testo=stampalat(SE[0])
        x=-SE[1]*self.FattoreDiScala*self.q
        y=-SE[0]*self.FattoreDiScala
        self.Graficodx.create_text(x+5,y,text=testo,fill="darkgray",tags="fincature",anchor="w", font=MIOFONT)
        testo=stampalon(SE[1])
        self.Graficodx.create_text(x+5,y+15,text=testo,fill="darkgray",tags="fincature",anchor="w", font=MIOFONT)
        x1=-self.Partenza[1]*self.FattoreDiScala*self.q
        y1=-self.Partenza[0]*self.FattoreDiScala
        self.Graficodx.create_rectangle(x1-3,y1-3,x1+3,y1+3,fill="red",tags="fincature")
        x2=-self.Arrivo[1]*self.FattoreDiScala*self.q
        y2=-self.Arrivo[0]*self.FattoreDiScala
        self.Graficodx.create_rectangle(x2-3,y2-3,x2+3,y2+3,fill="green",tags="fincature")
        self.Graficodx.create_line(x1,y1,x2,y2,fill=BGCOLOR,tags="fincature") 
Example 61
Project: PySail-426   Author: j3b4   File: ModuloBarca01.py    GNU General Public License v3.0 5 votes vote down vote up
def Speed(self):
        twa=math.copysign(self.TWA,1)
        return self.Plr.Speed(self.TW[1],twa) 
Example 62
Project: PySail-426   Author: j3b4   File: ModuloBarca01.py    GNU General Public License v3.0 5 votes vote down vote up
def TWAmaxCMG(self,rlv):
        twabrg=riduci180(self.TW[0]-rlv)
        maxtupla=self.Plr.maxVMGtwa(self.TW[1],math.copysign(twabrg,1))
        return math.copysign(maxtupla[1],twabrg) 
Example 63
Project: PySail-426   Author: j3b4   File: ModuloBarca01.py    GNU General Public License v3.0 5 votes vote down vote up
def AW(self):
        TWA=math.copysign(self.TWA,1)
        TWS=self.TW[1]
        SPEED=self.Speed()
        AWSy=TWS*math.cos(TWA)+SPEED
        AWSx=TWS*math.sin(TWA)
        AWS=(AWSy**2+AWSx**2)**0.5
        AWA=math.pi/2-math.atan2(AWSy,AWSx)
        aw=(AWS,AWA)
        if self.TWA<0:
            aw=(aw[0],-aw[1])
        return aw 
Example 64
Project: PySail-426   Author: j3b4   File: ModuloBarca01.py    GNU General Public License v3.0 5 votes vote down vote up
def Fiocco(self):
        fiocco=[]
        aw=self.AW()
        awa=aw[1]
        if math.copysign(awa,1)>math.radians(60):
            l=125.0
            zero=135
        else:
            l=90
            zero=125
        #if math.copysign(awa,1)<math.radians(25):
        if self.Speed()<=0:
            fiocco=[(0,125.0),(0,35.0)]
        else:
            if awa>0:
                r=l/awa
                cx=+r*math.cos(awa)
                cy=zero-r*math.sin(awa)
                for angolo in range(0,int(math.degrees(awa))):
                    angolo=math.radians(angolo)
                    x=cx-r*math.cos(angolo)
                    y=cy+r*math.sin(angolo)
                    fiocco.append((x,y))
            else:
                awa=math.copysign(awa,1)
                r=l/awa
                cx=-r*math.cos(awa)
                cy=zero-r*math.sin(awa)
                for angolo in range(0,int(math.degrees(awa))):
                    angolo=math.radians(angolo)
                    x=cx+r*math.cos(angolo)
                    y=cy+r*math.sin(angolo)
                    fiocco.append((x,y))
        return fiocco 
Example 65
Project: PySail-426   Author: j3b4   File: SimulazioneRegata316.py    GNU General Public License v3.0 5 votes vote down vote up
def steerautomode(self,hdg=0.0):
        #calcola il TWA necessario a rispettare il modo di steer (modi gps,vmgwp e vmwtw)
        if self.mode=="compass":
            self.MaVie.TWA=riduci180(self.MaVie.TW[0]-hdg)
        if self.mode=="gps":
            self.MaVie.TWA=riduci180(self.MaVie.TW[0]-self.MaVie.BRGGPS(self.Arrivo))
        if self.mode=="vmgwp":
            self.MaVie.TWA=self.MaVie.TWAmaxVMGWP(self.Arrivo)
        if self.mode=="vmgtw":
            scarto=scartorotta(self.MaVie.TW[0],self.MaVie.BRG(self.Arrivo))
            if scarto<=math.pi/2:#poppa (mure a sx)
                TWA=self.MaVie.TWAmaxCMG(self.MaVie.TW[0])
            else:#bolina (mure a sx)
                TWA=self.MaVie.TWAmaxCMG(riduci360(self.MaVie.TW[0]+math.pi))
            #definire le mura
            '''
            hdgsx=riduci360(self.MaVie.TW[0]+TWA)#mure dx
            hdgdx=riduci360(self.MaVie.TW[0]-TWA)#mure sx
            brg=self.MaVie.BRG(self.Arrivo)
            if scartorotta(brg,hdgdx)<scartorotta(brg,hdgsx):
                TWA=-TWA
            self.MaVie.TWA=-TWA#twa positivi per mure a dritta
            '''
            self.MaVie.TWA=math.copysign(-TWA,self.MaVie.TWA)
        if self.mode=="cmg":
            try:
                ril=self.cmgtxt.get("1.0","1.end")
                ril=math.radians(int(ril))
                ril=riduci360(ril)
                self.MaVie.TWA=self.MaVie.TWAmaxCMG(ril)
            except:
                self.cmgtxt.delete("1.0",END) 
Example 66
Project: PySail-426   Author: j3b4   File: ModuloBarca02.py    GNU General Public License v3.0 5 votes vote down vote up
def Orza(self):#revisione 29/11/2013
        twa=math.copysign(self.TWA,1)
        twa=twa-math.radians(1)
        if twa<0:twa=0
        self.TWA=math.copysign(twa,self.TWA) 
Example 67
Project: PySail-426   Author: j3b4   File: ModuloBarca02.py    GNU General Public License v3.0 5 votes vote down vote up
def Puggia(self):
        twa=math.copysign(self.TWA,1)
        twa=twa+math.radians(1)
        if twa>math.pi:twa=math.pi
        self.TWA=math.copysign(twa,self.TWA) 
Example 68
Project: PySail-426   Author: j3b4   File: ModuloBarca02.py    GNU General Public License v3.0 5 votes vote down vote up
def SpeedRoutage(self):
        twa=math.copysign(self.TWA,1)
        return self.Plr.SpeedRoutage(self.TW[1],twa) 
Example 69
Project: PySail-426   Author: j3b4   File: ModuloBarca02.py    GNU General Public License v3.0 5 votes vote down vote up
def TWAmaxCMG(self,rlv):
        twabrg=riduci180(self.TW[0]-rlv)
        maxtupla=self.Plr.maxVMGtwa(self.TW[1],math.copysign(twabrg,1))
        return math.copysign(maxtupla[1],twabrg) 
Example 70
Project: PySail-426   Author: j3b4   File: ModuloBarca02.py    GNU General Public License v3.0 5 votes vote down vote up
def AW(self):
        TWA=math.copysign(self.TWA,1)
        TWS=self.TW[1]
        SPEED=self.Speed()
        aw=AW(TWS,TWA,SPEED)
        #AWSy=TWS*math.cos(TWA)+SPEED
        #AWSx=TWS*math.sin(TWA)
        #AWS=(AWSy**2+AWSx**2)**0.5
        #AWA=math.pi/2-math.atan2(AWSy,AWSx)
        #aw=(AWS,AWA)
        if self.TWA<0:
            aw=(aw[0],-aw[1])
        return aw 
Example 71
Project: PySail-426   Author: j3b4   File: ModuloBarca02.py    GNU General Public License v3.0 5 votes vote down vote up
def Fiocco(self):
        fiocco=[]
        aw=self.AW()
        awa=aw[1]
        if awa>0:
            segno=1
        else:
            segno=-1
        awa=math.copysign(awa,1)
        if awa>math.radians(90):
            l=200
            zero=165
            x0=-(165-125)*segno*math.cos(awa)
            y0=(165-125)*math.sin(awa)
        elif awa>math.radians(60):
            l=145.0
            zero=135
            x0=0
            y0=0
        else:
            l=90
            zero=125
            x0=0
            y0=0
      #if math.copysign(awa,1)<math.radians(25):
        if self.Speed()<=0 or awa<math.radians(15):
            fiocco=[(0,125.0),(0,35.0)]
        else:
            r=l/awa
            cx=+segno*r*math.cos(awa)
            cy=zero-r*math.sin(awa)            
            fine=int(math.degrees(awa)+0.5)
            for angolo in range(0,fine):
                angolo=math.radians(angolo)
                x=cx-segno*r*math.cos(angolo)+x0
                y=cy+r*math.sin(angolo)+y0
                fiocco.append((x,y))
        return fiocco 
Example 72
Project: PySail-426   Author: j3b4   File: ModuloBarca02.py    GNU General Public License v3.0 5 votes vote down vote up
def Randa(self):
        aw=self.AW()
        awa=aw[1]
        randa=[]
        if awa>0:
            segno=1
        else:
            segno=-1
        awa=math.copysign(awa,1)
        l=110
        zero=35
        alfa0=10#integer
        r=0.5*l/math.tan(math.radians(alfa0))
        if self.Speed()<=0 or awa<=math.radians(alfa0):
            randa=[(0,35.0),(0,-75.0)]
        else:
            beta=awa-math.radians(5)
            if beta>0.5*math.pi:
                beta=0.5*math.pi
            cx=segno*r*math.cos(beta+math.radians(alfa0))
            cy=zero-r*math.sin(beta+math.radians(alfa0))
            betaint=int(math.degrees(beta)+0.5)
            for angolo in range(betaint-alfa0,betaint+alfa0):
                angolo=math.radians(angolo)
                x=cx-r*segno*math.cos(angolo)
                y=cy+r*math.sin(angolo)
                randa.append((x,y))
        return randa
#FUNZIONI 
Example 73
Project: PySail-426   Author: j3b4   File: ModuloNav.py    GNU General Public License v3.0 5 votes vote down vote up
def lossodromica(latA,lonA,latB,lonB):
    #non funziona in prossimita' dei poli
    #per latB=-90: math domain error log(0)
    #per latA=-90 [zero divison error]
    #per A==B ritorna (0.0,0.0)
    #if latA==latB:
    if  math.copysign(latA-latB,1)<=math.radians(0.1/3600.0):
        q=math.cos(latA)
    else:
        Df=math.log(math.tan(latB/2+math.pi/4)/math.tan(latA/2+math.pi/4),math.e)
        q=(latB-latA)*1.0/Df
    Distanza=RaggioTerrestre*((latA-latB)**2+(q*(lonA-lonB))**2)**0.5
    Rotta=math.atan2(-q*(lonB-lonA),(latB-latA))
    if Rotta<0:Rotta=Rotta+2.0*math.pi#atan2:[-pi,pi]
    return Distanza,Rotta 
Example 74
Project: PySail-426   Author: j3b4   File: ModuloNav.py    GNU General Public License v3.0 5 votes vote down vote up
def riduci360(alfa):
    n=int(alfa*0.5/math.pi)
    n=math.copysign(n,1)
    if alfa>2.0*math.pi:
        alfa=alfa-n*2.0*math.pi
    if alfa<0:
        alfa=(n+1)*2.0*math.pi+alfa
    if alfa>2.0*math.pi or alfa<0:
        print "errore riduci360"
    return alfa 
Example 75
Project: pyblish-win   Author: pyblish   File: test_cmath.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def rAssertAlmostEqual(self, a, b, rel_err = 2e-15, abs_err = 5e-323,
                           msg=None):
        """Fail if the two floating-point numbers are not almost equal.

        Determine whether floating-point values a and b are equal to within
        a (small) rounding error.  The default values for rel_err and
        abs_err are chosen to be suitable for platforms where a float is
        represented by an IEEE 754 double.  They allow an error of between
        9 and 19 ulps.
        """

        # special values testing
        if math.isnan(a):
            if math.isnan(b):
                return
            self.fail(msg or '{!r} should be nan'.format(b))

        if math.isinf(a):
            if a == b:
                return
            self.fail(msg or 'finite result where infinity expected: '
                      'expected {!r}, got {!r}'.format(a, b))

        # if both a and b are zero, check whether they have the same sign
        # (in theory there are examples where it would be legitimate for a
        # and b to have opposite signs; in practice these hardly ever
        # occur).
        if not a and not b:
            if math.copysign(1., a) != math.copysign(1., b):
                self.fail(msg or 'zero has wrong sign: expected {!r}, '
                          'got {!r}'.format(a, b))

        # if a-b overflows, or b is infinite, return False.  Again, in
        # theory there are examples where a is within a few ulps of the
        # max representable float, and then b could legitimately be
        # infinite.  In practice these examples are rare.
        try:
            absolute_error = abs(b-a)
        except OverflowError:
            pass
        else:
            # test passes if either the absolute error or the relative
            # error is sufficiently small.  The defaults amount to an
            # error of between 9 ulps and 19 ulps on an IEEE-754 compliant
            # machine.
            if absolute_error <= max(abs_err, rel_err * abs(a)):
                return
        self.fail(msg or
                  '{!r} and {!r} are not sufficiently close'.format(a, b)) 
Example 76
Project: jawfish   Author: war-and-code   File: _struct.py    MIT License 4 votes vote down vote up
def float_pack(x, size):
    """Convert a Python float x into a 64-bit unsigned integer
    with the same byte representation."""

    if size == 8:
        MIN_EXP = -1021  # = sys.float_info.min_exp
        MAX_EXP = 1024   # = sys.float_info.max_exp
        MANT_DIG = 53    # = sys.float_info.mant_dig
        BITS = 64
    elif size == 4:
        MIN_EXP = -125   # C's FLT_MIN_EXP
        MAX_EXP = 128    # FLT_MAX_EXP
        MANT_DIG = 24    # FLT_MANT_DIG
        BITS = 32
    else:
        raise ValueError("invalid size value")

    sign = math.copysign(1.0, x) < 0.0
    if math.isinf(x):
        mant = 0
        exp = MAX_EXP - MIN_EXP + 2
    elif math.isnan(x):
        mant = 1 << (MANT_DIG-2) # other values possible
        exp = MAX_EXP - MIN_EXP + 2
    elif x == 0.0:
        mant = 0
        exp = 0
    else:
        m, e = math.frexp(abs(x))  # abs(x) == m * 2**e
        exp = e - (MIN_EXP - 1)
        if exp > 0:
            # Normal case.
            mant = round_to_nearest(m * (1 << MANT_DIG))
            mant -= 1 << MANT_DIG - 1
        else:
            # Subnormal case.
            if exp + MANT_DIG - 1 >= 0:
                mant = round_to_nearest(m * (1 << exp + MANT_DIG - 1))
            else:
                mant = 0
            exp = 0

        # Special case: rounding produced a MANT_DIG-bit mantissa.
        assert 0 <= mant <= 1 << MANT_DIG - 1
        if mant == 1 << MANT_DIG - 1:
            mant = 0
            exp += 1

        # Raise on overflow (in some circumstances, may want to return
        # infinity instead).
        if exp >= MAX_EXP - MIN_EXP + 2:
             raise OverflowError("float too large to pack in this format")

    # check constraints
    assert 0 <= mant < 1 << MANT_DIG - 1
    assert 0 <= exp <= MAX_EXP - MIN_EXP + 2
    assert 0 <= sign <= 1
    return ((sign << BITS - 1) | (exp << MANT_DIG - 1)) | mant 
Example 77
Project: Repobot   Author: Desgard   File: newround.py    MIT License 4 votes vote down vote up
def from_float_26(f):
    """Converts a float to a decimal number, exactly.

    Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
    Since 0.1 is not exactly representable in binary floating point, the
    value is stored as the nearest representable value which is
    0x1.999999999999ap-4.  The exact equivalent of the value in decimal
    is 0.1000000000000000055511151231257827021181583404541015625.

    >>> Decimal.from_float(0.1)
    Decimal('0.1000000000000000055511151231257827021181583404541015625')
    >>> Decimal.from_float(float('nan'))
    Decimal('NaN')
    >>> Decimal.from_float(float('inf'))
    Decimal('Infinity')
    >>> Decimal.from_float(-float('inf'))
    Decimal('-Infinity')
    >>> Decimal.from_float(-0.0)
    Decimal('-0')

    """
    import math as _math
    from decimal import _dec_from_triple    # only available on Py2.6 and Py2.7 (not 3.3)

    if isinstance(f, (int, long)):        # handle integer inputs
        return Decimal(f)
    if _math.isinf(f) or _math.isnan(f):  # raises TypeError if not a float
        return Decimal(repr(f))
    if _math.copysign(1.0, f) == 1.0:
        sign = 0
    else:
        sign = 1
    n, d = abs(f).as_integer_ratio()
    # int.bit_length() method doesn't exist on Py2.6:
    def bit_length(d):
        if d != 0:
            return len(bin(abs(d))) - 2
        else:
            return 0
    k = bit_length(d) - 1
    result = _dec_from_triple(sign, str(n*5**k), -k)
    return result 
Example 78
Project: NiujiaoDebugger   Author: MrSrc   File: _pydecimal.py    GNU General Public License v3.0 4 votes vote down vote up
def from_float(cls, f):
        """Converts a float to a decimal number, exactly.

        Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
        Since 0.1 is not exactly representable in binary floating point, the
        value is stored as the nearest representable value which is
        0x1.999999999999ap-4.  The exact equivalent of the value in decimal
        is 0.1000000000000000055511151231257827021181583404541015625.

        >>> Decimal.from_float(0.1)
        Decimal('0.1000000000000000055511151231257827021181583404541015625')
        >>> Decimal.from_float(float('nan'))
        Decimal('NaN')
        >>> Decimal.from_float(float('inf'))
        Decimal('Infinity')
        >>> Decimal.from_float(-float('inf'))
        Decimal('-Infinity')
        >>> Decimal.from_float(-0.0)
        Decimal('-0')

        """
        if isinstance(f, int):                # handle integer inputs
            sign = 0 if f >= 0 else 1
            k = 0
            coeff = str(abs(f))
        elif isinstance(f, float):
            if _math.isinf(f) or _math.isnan(f):
                return cls(repr(f))
            if _math.copysign(1.0, f) == 1.0:
                sign = 0
            else:
                sign = 1
            n, d = abs(f).as_integer_ratio()
            k = d.bit_length() - 1
            coeff = str(n*5**k)
        else:
            raise TypeError("argument must be int or float.")

        result = _dec_from_triple(sign, coeff, -k)
        if cls is Decimal:
            return result
        else:
            return cls(result) 
Example 79
Project: NiujiaoDebugger   Author: MrSrc   File: test_cmath.py    GNU General Public License v3.0 4 votes vote down vote up
def rAssertAlmostEqual(self, a, b, rel_err = 2e-15, abs_err = 5e-323,
                           msg=None):
        """Fail if the two floating-point numbers are not almost equal.

        Determine whether floating-point values a and b are equal to within
        a (small) rounding error.  The default values for rel_err and
        abs_err are chosen to be suitable for platforms where a float is
        represented by an IEEE 754 double.  They allow an error of between
        9 and 19 ulps.
        """

        # special values testing
        if math.isnan(a):
            if math.isnan(b):
                return
            self.fail(msg or '{!r} should be nan'.format(b))

        if math.isinf(a):
            if a == b:
                return
            self.fail(msg or 'finite result where infinity expected: '
                      'expected {!r}, got {!r}'.format(a, b))

        # if both a and b are zero, check whether they have the same sign
        # (in theory there are examples where it would be legitimate for a
        # and b to have opposite signs; in practice these hardly ever
        # occur).
        if not a and not b:
            if math.copysign(1., a) != math.copysign(1., b):
                self.fail(msg or 'zero has wrong sign: expected {!r}, '
                          'got {!r}'.format(a, b))

        # if a-b overflows, or b is infinite, return False.  Again, in
        # theory there are examples where a is within a few ulps of the
        # max representable float, and then b could legitimately be
        # infinite.  In practice these examples are rare.
        try:
            absolute_error = abs(b-a)
        except OverflowError:
            pass
        else:
            # test passes if either the absolute error or the relative
            # error is sufficiently small.  The defaults amount to an
            # error of between 9 ulps and 19 ulps on an IEEE-754 compliant
            # machine.
            if absolute_error <= max(abs_err, rel_err * abs(a)):
                return
        self.fail(msg or
                  '{!r} and {!r} are not sufficiently close'.format(a, b)) 
Example 80
Project: PySail-426   Author: j3b4   File: SimulazioneRegata300.py    GNU General Public License v3.0 4 votes vote down vote up
def Play(self,event):
        self.run=not self.run
        while self.run:
            if self.mode=="vmg":
                self.MaVie.TWA=self.MaVie.TWAmaxVMGWP(self.Arrivo)
            if self.mode=="gps":
                self.MaVie.TWA=riduci180(self.MaVie.TW[0]-self.MaVie.BRGGPS(self.Arrivo))
            if self.isocronamodo:
                self.CalcolaIsocrona()
                curvaisocrona=[]
                bestcourse=[]
                mindist=self.Course[0]
                for valore in self.Isocrone[-1]:
                    pto=valore[0]
                    curvaisocrona.append(pto)
                    losso=lossodromica(pto[0],pto[1],self.Arrivo[0],self.Arrivo[1])
                    dist=losso[0]
                    if dist<mindist:
                        mindist=dist
                        bestpto=pto
                        previusindice=valore[1]
                bestcourse.append(bestpto)
                for i in range(-2,-len(self.Isocrone),-1):
                    valore=self.Isocrone[i][previusindice]
                    pto=valore[0]
                    previusindice=valore[1]
                    bestcourse.append(pto)
                bestcourse.append(self.OrigineIsocrone)
                self.Graficodx.delete("bestcourse")
                self.disegna(bestcourse,"#8B4519","bestcourse")
                self.disegna(curvaisocrona,"dodgerblue","isocrona")
            pos1=self.MaVie.Pos
            twa_arrivo=riduci180(self.MaVie.TW[0]-self.MaVie.BRG(self.Arrivo))
            v_arrivo=self.MaVie.Plr.SpeedRoutage(self.MaVie.TW[1],math.copysign(twa_arrivo,1))
            Dt_arrivo=self.MaVie.Dist(self.Arrivo)/v_arrivo
            if self.Dt>Dt_arrivo:#ultimo passo
                self.run=False
                self.MaVie.TWA=twa_arrivo
                self.MaVie.MuoviRoutage(Dt_arrivo)
                self.T=self.T+Dt_arrivo
            else:#passo standard
                if self.mode=="gps":
                    self.MaVie.MuoviRoutage(self.Dt)
                else:
                    self.MaVie.Muovi(self.Dt)
                self.T=self.T+self.Dt  
            hdg=self.MaVie.HDG()#prima di aggiornare il vento memorizzo la hdg per il modo compass
            self.MaVie.TW=self.vento(self.MaVie.Pos[0],self.MaVie.Pos[1])
            if self.mode=="compass":
                self.MaVie.TWA=riduci180(self.MaVie.TW[0]-hdg)
            self.DisegnaCampoDiVento()
            self.disegna([pos1,self.MaVie.Pos],"darkblue","tracking")
            self.Graficodx.delete("brg")
            self.disegna([self.MaVie.Pos,self.Arrivo],"yellow","brg")
            self.Graficodx.update()
            self.Graficodx.config(scrollregion=self.Graficodx.bbox(ALL))
            self.DisegnaVettoriBarca()
            self.SettaStrVar()
            self.SettaBottoni()
            time.sleep(0.0001)