Exemplo n.º 1
0
def _write_float(f, x):
    import math
    if x < 0:
        sign = 32768
        x = x * -1
    else:
        sign = 0
    if x == 0:
        expon = 0
        himant = 0
        lomant = 0
    else:
        fmant, expon = math.frexp(x)
        if expon > 16384 or fmant >= 1 or fmant != fmant:
            expon = sign | 32767
            himant = 0
            lomant = 0
        else:
            expon = expon + 16382
            if expon < 0:
                fmant = math.ldexp(fmant, expon)
                expon = 0
            expon = expon | sign
            fmant = math.ldexp(fmant, 32)
            fsmant = math.floor(fmant)
            himant = long(fsmant)
            fmant = math.ldexp(fmant - fsmant, 32)
            fsmant = math.floor(fmant)
            lomant = long(fsmant)
    _write_ushort(f, expon)
    _write_ulong(f, himant)
    _write_ulong(f, lomant)
Exemplo n.º 2
0
	def set_ref(self, refval):
		x = self.teach()
		m,e = math.frexp(refval / 5e-9)
		if m < 0:
			s = 0x80
			m = -m
		else:
			s = 0
		m = math.ldexp(m, -1)
		for i in range(14,20):
			m = math.ldexp(m, 8)
			h = int(m)
			m -= h
			x[i] = s | h
			s = 0
		
		e -= 31
		if e < 0:
			e += 256
		x[20] = e

		y=bytearray("LN")
		for i in x:
			if i == 10 or i == 27 or i == 13 or i == 43:
				y.append(27)
			y.append(i)
		d.wr(y)
Exemplo n.º 3
0
	def __init__(self, pj, lo):
		super(float70, self).__init__(pj, lo, lo + 7)
		x = pj.m.rd(self.lo)
		if x & 0x80:
			s = -1
			x ^= 0x80
		else:
			s = 1
		o = -7
		m = 0
		for i in range(6):
			m +=  math.ldexp(x, o)
			o -= 8
			x = pj.m.rd(self.lo + 1 + i)
		e =  pj.m.s8(self.lo + 6)
		self.lcmt = "m %g e %g" % (m, e)
		v = s * math.ldexp(m, e)
		self.val = v

		x = "%.9e" % v
		if x.find(".") == -1 and x.find("e") == -1:
			x += "."
		self.fmt = x
		self.typ = ".FLOAT"
		self.compact = False
		pj.set_label(lo, "c_" + x)
		print(self, self.fmt)
Exemplo n.º 4
0
def sqrt(x):
    sqrt_special = [
        [inf-infj, 0-infj, 0-infj, infj, infj, inf+infj, nan+infj],
        [inf-infj, None, None, None, None, inf+infj, nan+nanj],
        [inf-infj, None, 0-0j, 0+0j, None, inf+infj, nan+nanj],
        [inf-infj, None, 0-0j, 0+0j, None, inf+infj, nan+nanj],
        [inf-infj, None, None, None, None, inf+infj, nan+nanj],
        [inf-infj, complex(float("inf"), -0.0), complex(float("inf"), -0.0), inf, inf, inf+infj, inf+nanj],
        [inf-infj, nan+nanj, nan+nanj, nan+nanj, nan+nanj, inf+infj, nan+nanj]
    ]

    z = _make_complex(x)

    if math.isinf(z.real) or math.isinf(z.imag):
        return sqrt_special[_special_type(z.real)][_special_type(z.imag)]

    abs_x, abs_y = abs(z.real), abs(z.imag)
    if abs_x < _DBL_MIN and abs_y < _DBL_MIN:
        if abs_x > 0 or abs_y > 0:
            abs_x = math.ldexp(abs_x, _CM_SCALE_UP)
            s = math.ldexp(math.sqrt(abs_x +
                                     math.hypot(abs_x,
                                                math.ldexp(abs_y,
                                                           _CM_SCALE_UP))),
                           _CM_SCALE_DOWN)
        else:
            return complex(0, z.imag)
    else:
        abs_x /= 8
        s = 2 * math.sqrt(abs_x + math.hypot(abs_x, abs_y/8))

    if z.real >= 0:
        return complex(s, math.copysign(abs_y/(2*s), z.imag))
    return complex(abs_y/(2*s), math.copysign(s, z.imag))
Exemplo n.º 5
0
def to_float(s, strict=False):
    """
    Convert a raw mpf to a Python float. The result is exact if the
    bitcount of s is <= 53 and no underflow/overflow occurs.

    If the number is too large or too small to represent as a regular
    float, it will be converted to inf or 0.0. Setting strict=True
    forces an OverflowError to be raised instead.
    """
    sign, man, exp, bc = s
    if not man:
        if s == fzero: return 0.0
        if s == finf: return math_float_inf
        if s == fninf: return -math_float_inf
        return math_float_inf/math_float_inf
    if sign:
        man = -man
    try:
        if bc < 100:
            return math.ldexp(man, exp)
        # Try resizing the mantissa. Overflow may still happen here.
        n = bc - 53
        m = man >> n
        return math.ldexp(m, exp + n)
    except OverflowError:
        if strict:
            raise
        # Overflow to infinity
        if exp + bc > 0:
            if sign:
                return -math_float_inf
            else:
                return math_float_inf
        # Underflow to zero
        return 0.0
Exemplo n.º 6
0
    def test_705836(self):
        # SF bug 705836.  "<f" and ">f" had a severe rounding bug, where a carry
        # from the low-order discarded bits could propagate into the exponent
        # field, causing the result to be wrong by a factor of 2.
        for base in range(1, 33):
            # smaller <- largest representable float less than base.
            delta = 0.5
            while base - delta / 2.0 != base:
                delta /= 2.0
            smaller = base - delta
            # Packing this rounds away a solid string of trailing 1 bits.
            packed = struct.pack("<f", smaller)
            unpacked = struct.unpack("<f", packed)[0]
            # This failed at base = 2, 4, and 32, with unpacked = 1, 2, and
            # 16, respectively.
            self.assertEqual(base, unpacked)
            bigpacked = struct.pack(">f", smaller)
            self.assertEqual(bigpacked, string_reverse(packed))
            unpacked = struct.unpack(">f", bigpacked)[0]
            self.assertEqual(base, unpacked)

        # Largest finite IEEE single.
        big = (1 << 24) - 1
        big = math.ldexp(big, 127 - 23)
        packed = struct.pack(">f", big)
        unpacked = struct.unpack(">f", packed)[0]
        self.assertEqual(big, unpacked)

        # The same, but tack on a 1 bit so it rounds up to infinity.
        big = (1 << 25) - 1
        big = math.ldexp(big, 127 - 24)
        self.assertRaises(OverflowError, struct.pack, ">f", big)
Exemplo n.º 7
0
def ldexp(x, y):
    # The code below is inspired by uncertainties.wrap().  It is
    # simpler because only 1 argument is given, and there is no
    # delegation to other functions involved (as for __mul__, etc.).

    # Another approach would be to add an additional argument to
    # uncertainties.wrap() so that some arguments are automatically
    # considered as constants.

    aff_func = to_affine_scalar(x)  # y must be an integer, for math.ldexp

    if aff_func.derivatives:
        factor = 2**y
        return AffineScalarFunc(
            math.ldexp(aff_func.nominal_value, y),
            # Chain rule:
            dict([(var, factor*deriv)
                  for (var, deriv) in aff_func.derivatives.iteritems()]))
    else:
        # This function was not called with an AffineScalarFunc
        # argument: there is no need to return numbers with uncertainties:

        # aff_func.nominal_value is not passed instead of x, because
        # we do not have to care about the type of the return value of
        # math.ldexp, this way (aff_func.nominal_value might be the
        # value of x coerced to a difference type [int->float, for
        # instance]):
        return math.ldexp(x, y)
Exemplo n.º 8
0
def _write_float(f, x):
	import math
	if x < 0:
		sign = 0x8000
		x = x * -1
	else:
		sign = 0
	if x == 0:
		expon = 0
		himant = 0
		lomant = 0
	else:
		fmant, expon = math.frexp(x)
		if expon > 16384 or fmant >= 1:		# Infinity or NaN
			expon = sign|0x7FFF
			himant = 0
			lomant = 0
		else:					# Finite
			expon = expon + 16382
			if expon < 0:			# denormalized
				fmant = math.ldexp(fmant, expon)
				expon = 0
			expon = expon | sign
			fmant = math.ldexp(fmant, 32)
			fsmant = math.floor(fmant)
			himant = long(fsmant)
			fmant = math.ldexp(fmant - fsmant, 32)
			fsmant = math.floor(fmant)
			lomant = long(fsmant)
	_write_short(f, expon)
	_write_long(f, himant)
	_write_long(f, lomant)
Exemplo n.º 9
0
        def msum(iterable):
            """Full precision summation.  Compute sum(iterable) without any
            intermediate accumulation of error.  Based on the 'lsum' function
            at http://code.activestate.com/recipes/393090/

            """
            tmant, texp = 0, 0
            for x in iterable:
                mant, exp = math.frexp(x)
                mant, exp = int(math.ldexp(mant, mant_dig)), exp - mant_dig
                if texp > exp:
                    tmant <<= texp-exp
                    texp = exp
                else:
                    mant <<= exp-texp
                tmant += mant
            # Round tmant * 2**texp to a float.  The original recipe
            # used float(str(tmant)) * 2.0**texp for this, but that's
            # a little unsafe because str -> float conversion can't be
            # relied upon to do correct rounding on all platforms.
            tail = max(len(bin(abs(tmant)))-2 - mant_dig, etiny - texp)
            if tail > 0:
                h = 1 << (tail-1)
                tmant = tmant // (2*h) + bool(tmant & h and tmant & 3*h-1)
                texp += tail
            return math.ldexp(tmant, texp)
Exemplo n.º 10
0
def get_heavy_correction(beta, heavytype):
    m = get_heavyq_mass(beta, heavytype)

    def prop(p):
        W = 1-np.cos(p)
        Weplus = W + 1./2 + np.sqrt(W + 1./4)
        Wemins = W + 1./2 - np.sqrt(W + 1./4)
        num = np.sin(p) * np.sin(p*t) + m*(1-Wemins) * np.cos(p*t)
        #num = 2*np.sin(p) * np.sin(p*t) #+ m*(1-Wemins) * np.cos(p*t)
        den = - (1-Weplus) + m**2*(1-Wemins)
        return num/den /(2*np.pi)

    Q = ((1+m**2)/(1-m**2))**2
    T  = (1-Q)/2 + np.sqrt(3*Q+Q**2)/2
    W0 = (1+Q)/2 - np.sqrt(3*Q+Q**2)/2
    m1 = np.log(T+np.sqrt(T**2-1))
    K = 2.0/((1-m**2)*(1.0+np.sqrt(Q/(1.0+4*W0))))

    Nt = 65
    it = np.arange(Nt)
    Ct = np.empty(Nt)
    R  = {}
    minDouble  = math.ldexp(1.0, -1022)
    smallEpsilon  = math.ldexp(1.0, -1074)
    epsilon  = math.ldexp(1.0, -53)
    for t in it:
        Ct[t], err = integrate.quad(prop,-np.pi,np.pi)
        if Ct[t] < err or (K*np.exp(-m1*t)) < err:
            R[t] = 1.
        else:
            R[t] = Ct[t] / (K*np.exp(-m1*t))

    return R
Exemplo n.º 11
0
def float_unpack(Q, size):
    """Convert a 16-bit, 32-bit, or 64-bit integer created
    by float_pack into a Python float."""
    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
    elif size == 2:
        MIN_EXP = -13
        MAX_EXP = 16
        MANT_DIG = 11
        BITS = 16
    else:
        raise ValueError("invalid size value")

    if not objectmodel.we_are_translated():
        # This tests generates wrong code when translated:
        # with gcc, shifting a 64bit int by 64 bits does
        # not change the value.
        if Q >> BITS:
            raise ValueError("input '%r' out of range '%r'" % (Q, Q >> BITS))

    # extract pieces with assumed 1.mant values
    one = r_ulonglong(1)
    sign = rarithmetic.intmask(Q >> BITS - 1)
    exp = rarithmetic.intmask((Q & ((one << BITS - 1) - (one << MANT_DIG - 1))) >> MANT_DIG - 1)
    mant = Q & ((one << MANT_DIG - 1) - 1)

    if exp == MAX_EXP - MIN_EXP + 2:
        # nan or infinity
        if mant == 0:
            result = rfloat.INFINITY
        else:
            # preserve at most 52 bits of mant value, but pad w/zeros
            exp = r_ulonglong(0x7FF) << 52
            sign = r_ulonglong(sign) << 63
            if MANT_DIG < 53:
                mant = r_ulonglong(mant) << (53 - MANT_DIG)
            if mant == 0:
                result = rfloat.NAN
            else:
                uint = exp | mant | sign
                result = longlong2float(cast(LONGLONG, uint))
            return result
    elif exp == 0:
        # subnormal or zero
        result = math.ldexp(mant, MIN_EXP - MANT_DIG)
    else:
        # normal: add implicit one value
        mant += one << MANT_DIG - 1
        result = math.ldexp(mant, exp + MIN_EXP - MANT_DIG - 1)
    return -result if sign else result
Exemplo n.º 12
0
def c_log(x, y):
    # The usual formula for the real part is log(hypot(z.real, z.imag)).
    # There are four situations where this formula is potentially
    # problematic:
    #
    # (1) the absolute value of z is subnormal.  Then hypot is subnormal,
    # so has fewer than the usual number of bits of accuracy, hence may
    # have large relative error.  This then gives a large absolute error
    # in the log.  This can be solved by rescaling z by a suitable power
    # of 2.
    #
    # (2) the absolute value of z is greater than DBL_MAX (e.g. when both
    # z.real and z.imag are within a factor of 1/sqrt(2) of DBL_MAX)
    # Again, rescaling solves this.
    #
    # (3) the absolute value of z is close to 1.  In this case it's
    # difficult to achieve good accuracy, at least in part because a
    # change of 1ulp in the real or imaginary part of z can result in a
    # change of billions of ulps in the correctly rounded answer.
    #
    # (4) z = 0.  The simplest thing to do here is to call the
    # floating-point log with an argument of 0, and let its behaviour
    # (returning -infinity, signaling a floating-point exception, setting
    # errno, or whatever) determine that of c_log.  So the usual formula
    # is fine here.

    # XXX the following two lines seem unnecessary at least on Linux;
    # the tests pass fine without them
    if not isfinite(x) or not isfinite(y):
        return log_special_values[special_type(x)][special_type(y)]

    ax = fabs(x)
    ay = fabs(y)

    if ax > CM_LARGE_DOUBLE or ay > CM_LARGE_DOUBLE:
        real = math.log(math.hypot(ax/2., ay/2.)) + M_LN2
    elif ax < DBL_MIN and ay < DBL_MIN:
        if ax > 0. or ay > 0.:
            # catch cases where hypot(ax, ay) is subnormal
            real = math.log(math.hypot(math.ldexp(ax, DBL_MANT_DIG),
                                       math.ldexp(ay, DBL_MANT_DIG)))
            real -= DBL_MANT_DIG*M_LN2
        else:
            # log(+/-0. +/- 0i)
            raise ValueError("math domain error")
            #real = -INF
            #imag = atan2(y, x)
    else:
        h = math.hypot(ax, ay)
        if 0.71 <= h and h <= 1.73:
            am = max(ax, ay)
            an = min(ax, ay)
            real = log1p((am-1)*(am+1) + an*an) / 2.
        else:
            real = math.log(h)
    imag = math.atan2(y, x)
    return (real, imag)
Exemplo n.º 13
0
def sqrt(x):
    """
       Return the square root of x.

       This has the same branch cut as log().
    """
    #   Method: use symmetries to reduce to the case when x = z.real and y
    #   = z.imag are nonnegative.  Then the real part of the result is
    #   given by
    #
    #       s = sqrt((x + hypot(x, y))/2)
    #
    #   and the imaginary part is
    #
    #        d = (y/2)/s
    #
    #   If either x or y is very large then there's a risk of overflow in
    #   computation of the expression x + hypot(x, y).  We can avoid this
    #   by rewriting the formula for s as:
    #
    #       s = 2*sqrt(x/8 + hypot(x/8, y/8))
    #
    #   This costs us two extra multiplications/divisions, but avoids the
    #   overhead of checking for x and y large.
    #   If both x and y are subnormal then hypot(x, y) may also be
    #   subnormal, so will lack full precision.  We solve this by rescaling
    #   x and y by a sufficiently large power of 2 to ensure that x and y
    #   are normal.
    s, d, ax, ay = .0, .0, math.fabs(x.real), math.fabs(x.imag)

    ret = _SPECIAL_VALUE(x, _sqrt_special_values)
    if ret is not None:
        return ret

    if x.real == .0 and x.imag == .0:
        _real = .0
        _imag = x.imag
        return complex(_real,_imag)

    if ax < sys.float_info.min and ay < sys.float_info.min and (ax > 0. or ay > 0.):
        #here we catch cases where hypot(ax, ay) is subnormal
        ax = math.ldexp(ax, _CM_SCALE_UP);
        s = math.ldexp(math.sqrt(ax + math.hypot(ax, math.ldexp(ay, _CM_SCALE_UP))),_CM_SCALE_DOWN)
    else:
        ax /= 8.0;
        s = 2.0*math.sqrt(ax + math.hypot(ax, ay/8.0));

    d = ay/(2.0*s)

    if x.real >= .0:
        _real = s;
        _imag = math.copysign(d, x.imag)
    else:
        _real = d;
        _imag = math.copysign(s, x.imag)

    return complex(_real,_imag)
Exemplo n.º 14
0
def TakeData():
    t0 = time.clock();
    result = "Test started at " + str(datetime.now()) + "\n";

    LIA1.write("STRT");
    #LIA1.write("STRD"); #start scan after 0.5 sec
    t = time.clock() - t0;
    result += "Scan started at t = " + str(t) + "\n";

    time.sleep(0.5); #32s max
    LIA1.write("PAUS"); #pause
    t = time.clock() - t0;
    result += "Scan ended at t = " + str(t) + "\n";
    LIA1.ask("SPTS ?");
    num = LIA1.ask("SPTS ?"); #number of points
    result += "There are " + num + " points\n";
    t = time.clock() - t0;
    result += "Transfer started at t = " + str(t) + "\n";

    #LIA1.term_chars = "\0";
    CH1 = LIA1.ask_for_values("TRCA ? 1,0," + num);
    CH2 = LIA1.ask_for_values("TRCA ? 2,0," + num);
    LIA1.values_format = visa.single;
    BIN1 = LIA1.ask("TRCL ? 1,0," + num);
    BIN2 = LIA1.ask("TRCL ? 2,0," + num);
    t = time.clock() - t0;
    result += "Transfer ended at t = " + str(t) + "\n";

    BIN1 = list(BIN1);
    BIN2 = list(BIN2);
    CONV1 = list(CH1);
    CONV2 = list(CH2);
    if len(BIN1) != 4*int(num) or len(BIN2) != 4*int(num):
        print "ERROR in num!" + num + "\t" + str(len(BIN1));
        
    for i in range(0,int(num)):
        mantissa = ord(BIN1[4*i+1])*256+ord(BIN1[4*i]);
        if mantissa >= 32768:
            mantissa -= 65536;
        CONV1[i] = math.ldexp(mantissa, ord(BIN1[4*i+2])-124);

        mantissa = ord(BIN2[4*i+1])*256+ord(BIN2[4*i]);
        if mantissa >= 32768:
            mantissa -= 65536;
        CONV2[i] = math.ldexp(mantissa, ord(BIN2[4*i+2])-124);
            
        show = str(CH1[i]) + "\t" + str(CONV1[i]) + \
               "\t" + str(CH2[i]) + "\t" + str(CONV2[i]);
        print show;
        result += show + "\n";

    t = time.clock() - t0;
    result += "Evrything ended at t = " + str(t) + "\n";

    output.write(result);
Exemplo n.º 15
0
 def __float__(s):
     """Convert s to a Python float. OverflowError will be raised
     if the magnitude of s is too large."""
     try:
         return math.ldexp(s.man, s.exp)
     # Handle case when mantissa has too many bits (will still
     # overflow if exp is too large)
     except OverflowError:
         n = s.bc - 64
         m = s.man >> n
         return math.ldexp(m, s.exp + n)
Exemplo n.º 16
0
def getBoundingBox(x, y, z, dimension, projection):
	#pixel location of the center of the metatile
	x0 = x * TILE_SIZE
	y0 = (y + dimension) * TILE_SIZE
	x1 = (x + dimension) * TILE_SIZE
	y1 = y * TILE_SIZE
	#from pixels to WGS 84, comes back as (lng, lat)
	ul = projection.from_pixels((x0, y0), z)
	lr = projection.from_pixels((x1, y1), z)
	#using ldexp for performant floating point division by 2 to get center pixel location
	center = (int(math.ldexp(x0 + x1, -1) + .5) , int(math.ldexp(y0 + y1, -1) + .5))
	center = projection.from_pixels(center, z)
	return ((ul[1], ul[0]), (lr[1], lr[0])), (center[1], center[0])
Exemplo n.º 17
0
def c_sqrt(x, y):
    '''
    Method: use symmetries to reduce to the case when x = z.real and y
    = z.imag are nonnegative.  Then the real part of the result is
    given by
    
      s = sqrt((x + hypot(x, y))/2)
    
    and the imaginary part is
    
      d = (y/2)/s
    
    If either x or y is very large then there's a risk of overflow in
    computation of the expression x + hypot(x, y).  We can avoid this
    by rewriting the formula for s as:
    
      s = 2*sqrt(x/8 + hypot(x/8, y/8))
    
    This costs us two extra multiplications/divisions, but avoids the
    overhead of checking for x and y large.
    
    If both x and y are subnormal then hypot(x, y) may also be
    subnormal, so will lack full precision.  We solve this by rescaling
    x and y by a sufficiently large power of 2 to ensure that x and y
    are normal.
    '''
    if not isfinite(x) or not isfinite(y):
        return sqrt_special_values[special_type(x)][special_type(y)]

    if x == 0. and y == 0.:
        return (0., y)

    ax = fabs(x)
    ay = fabs(y)

    if ax < DBL_MIN and ay < DBL_MIN and (ax > 0. or ay > 0.):
        # here we catch cases where hypot(ax, ay) is subnormal
        ax = math.ldexp(ax, CM_SCALE_UP)
        ay1= math.ldexp(ay, CM_SCALE_UP)
        s = math.ldexp(math.sqrt(ax + math.hypot(ax, ay1)),
                       CM_SCALE_DOWN)
    else:
        ax /= 8.
        s = 2.*math.sqrt(ax + math.hypot(ax, ay/8.))

    d = ay/(2.*s)

    if x >= 0.:
        return (s, copysign(d, y))
    else:
        return (d, copysign(s, y))
Exemplo n.º 18
0
Arquivo: matroska.py Projeto: meh/mpv
def read_float(s, length):
    t = read(s, length)
    i = byte2num(t)
    if length == 4:
        f = ldexp((i & 0x7fffff) + (1 << 23), (i >> 23 & 0xff) - 150)
        if i & (1 << 31):
            f = -f
    elif length == 8:
        f = ldexp((i & ((1 << 52) - 1)) + (1 << 52), (i >> 52 & 0x7ff) - 1075)
        if i & (1 << 63):
            f = -f
    else:
        raise SyntaxError
    return f
Exemplo n.º 19
0
  def calc(self, args, irc):
    '''(calc <math expression>) -- Lifted from supybot.
    '''
    expr = ' '.join(args)
    try:
        expr = str(expr)
    except UnicodeEncodeError:
        return 'No Unicode allowed in math expressions.'

    if self.forbidden.match(expr):
        return 'No underscores or brackets allowed in math expressions.'

    if 'lambda' in expr:
        return 'lambda is not allowed in math expressions.'

    expr = self._mathRe.sub(Math.handleMatch, expr.lower())
    try:
        log.msg('evaluating %q from %s', expr, irc.sender)
        x = complex(eval(expr, self._mathSafeEnv, self._mathSafeEnv))
        return self._complexToString(x)
    except OverflowError:
        maxFloat = math.ldexp(0.9999999999999999, 1024)
        return 'The answer exceeded %s or so.' % maxFloat
    except TypeError:
        return 'Something in there wasn\'t a valid number.'
    except NameError as e:
        return '%s is not a defined function.' % str(e).split()[1]
    except Exception as e:
        return str(e)
Exemplo n.º 20
0
    def calc(self, irc, msg, args, text):
        """<math expression>

        Returns the value of the evaluated <math expression>.  The syntax is
        Python syntax; the type of arithmetic is floating point.  Floating
        point arithmetic is used in order to prevent a user from being able to
        crash to the bot with something like '10**10**10**10'.  One consequence
        is that large values such as '10**24' might not be exact.
        """
        try:
            text = str(text)
        except UnicodeEncodeError:
            irc.error(_("There's no reason you should have fancy non-ASCII "
                            "characters in your mathematical expression. "
                            "Please remove them."))
            return
        if self._calc_match_forbidden_chars.match(text):
            irc.error(_('There\'s really no reason why you should have '
                           'underscores or brackets in your mathematical '
                           'expression.  Please remove them.'))
            return
        text = self._calc_remover(text)
        if 'lambda' in text:
            irc.error(_('You can\'t use lambda in this command.'))
            return
        text = text.lower()
        def handleMatch(m):
            s = m.group(1)
            if s.startswith('0x'):
                i = int(s, 16)
            elif s.startswith('0') and '.' not in s:
                try:
                    i = int(s, 8)
                except ValueError:
                    i = int(s)
            else:
                i = float(s)
            x = complex(i)
            if x.imag == 0:
                x = x.real
                # Need to use string-formatting here instead of str() because
                # use of str() on large numbers loses information:
                # str(float(33333333333333)) => '3.33333333333e+13'
                # float('3.33333333333e+13') => 33333333333300.0
                return '%.16f' % x
            return str(x)
        text = self._mathRe.sub(handleMatch, text)
        try:
            self.log.info('evaluating %q from %s', text, msg.prefix)
            x = complex(eval(text, self._mathSafeEnv, self._mathSafeEnv))
            irc.reply(self._complexToString(x))
        except OverflowError:
            maxFloat = math.ldexp(0.9999999999999999, 1024)
            irc.error(_('The answer exceeded %s or so.') % maxFloat)
        except TypeError:
            irc.error(_('Something in there wasn\'t a valid number.'))
        except NameError as e:
            irc.error(_('%s is not a defined function.') % str(e).split()[1])
        except Exception as e:
            irc.error(str(e))
Exemplo n.º 21
0
def truediv(a, b):
    """Correctly-rounded true division for integers."""
    negative = a^b < 0
    a, b = abs(a), abs(b)

    # exceptions:  division by zero, overflow
    if not b:
        raise ZeroDivisionError("division by zero")
    if a >= DBL_MIN_OVERFLOW * b:
        raise OverflowError("int/int too large to represent as a float")

   # find integer d satisfying 2**(d - 1) <= a/b < 2**d
    d = a.bit_length() - b.bit_length()
    if d >= 0 and a >= 2**d * b or d < 0 and a * 2**-d >= b:
        d += 1

    # compute 2**-exp * a / b for suitable exp
    exp = max(d, DBL_MIN_EXP) - DBL_MANT_DIG
    a, b = a << max(-exp, 0), b << max(exp, 0)
    q, r = divmod(a, b)

    # round-half-to-even: fractional part is r/b, which is > 0.5 iff
    # 2*r > b, and == 0.5 iff 2*r == b.
    if 2*r > b or 2*r == b and q % 2 == 1:
        q += 1

    result = math.ldexp(float(q), exp)
    return -result if negative else result
Exemplo n.º 22
0
    def icalc(self, irc, msg, args, text):
        """<math expression>

        This is the same as the calc command except that it allows integer
        math, and can thus cause the bot to suck up CPU.  Hence it requires
        the 'trusted' capability to use.
        """
        if self._calc_match_forbidden_chars.match(text):
            irc.error(
                _(
                    "There's really no reason why you should have "
                    "underscores or brackets in your mathematical "
                    "expression.  Please remove them."
                )
            )
            return
        # This removes spaces, too, but we'll leave the removal of _[] for
        # safety's sake.
        text = self._calc_remover(text)
        if "lambda" in text:
            irc.error(_("You can't use lambda in this command."))
            return
        text = text.replace("lambda", "")
        try:
            self.log.info("evaluating %q from %s", text, msg.prefix)
            irc.reply(str(eval(text, self._mathEnv, self._mathEnv)))
        except OverflowError:
            maxFloat = math.ldexp(0.9999999999999999, 1024)
            irc.error(_("The answer exceeded %s or so.") % maxFloat)
        except TypeError:
            irc.error(_("Something in there wasn't a valid number."))
        except NameError, e:
            irc.error(_("%s is not a defined function.") % str(e).split()[1])
Exemplo n.º 23
0
    def icalc(self, irc, msg, args, text):
        """<math expression>

        This is the same as the calc command except that it allows integer
        math, and can thus cause the bot to suck up CPU.  Hence it requires
        the 'trusted' capability to use.
        """
        if text != text.translate(utils.str.chars, '_[]'):
            irc.error(_('There\'s really no reason why you should have '
                           'underscores or brackets in your mathematical '
                           'expression.  Please remove them.'))
            return
        # This removes spaces, too, but we'll leave the removal of _[] for
        # safety's sake.
        text = text.translate(utils.str.chars, '_[] \t')
        if 'lambda' in text:
            irc.error(_('You can\'t use lambda in this command.'))
            return
        text = text.replace('lambda', '')
        try:
            self.log.info('evaluating %q from %s', text, msg.prefix)
            irc.reply(str(eval(text, self._mathEnv, self._mathEnv)))
        except OverflowError:
            maxFloat = math.ldexp(0.9999999999999999, 1024)
            irc.error(_('The answer exceeded %s or so.') % maxFloat)
        except TypeError:
            irc.error(_('Something in there wasn\'t a valid number.'))
        except NameError, e:
            irc.error(_('%s is not a defined function.') % str(e).split()[1])
Exemplo n.º 24
0
def PyNextAfter(x, y):
    """returns the next float after x in the direction of y if possible, else returns x"""
    # if x or y is Nan, we don't do much
    if IsNaN(x) or IsNaN(y):
        return x

    # we can't progress if x == y
    if x == y:
        return x

    # similarly if x is infinity
    if x >= infinity or x <= -infinity:
        return x

    # return small numbers for x very close to 0.0
    if -minFloat < x < minFloat:
        if y > x:
            return x + smallEpsilon
        else:
            return x - smallEpsilon  # we know x != y

    # it looks like we have a normalized number
    # break x down into a mantissa and exponent
    m, e = math.frexp(x)

    # all the special cases have been handled
    if y > x:
        m += epsilon
    else:
        m -= epsilon

    return math.ldexp(m, e)
Exemplo n.º 25
0
 def descr_hex(self, space):
     TOHEX_NBITS = rfloat.DBL_MANT_DIG + 3 - (rfloat.DBL_MANT_DIG + 2) % 4
     value = self.floatval
     if not isfinite(value):
         return self.descr_str(space)
     if value == 0.0:
         if copysign(1., value) == -1.:
             return space.wrap("-0x0.0p+0")
         else:
             return space.wrap("0x0.0p+0")
     mant, exp = math.frexp(value)
     shift = 1 - max(rfloat.DBL_MIN_EXP - exp, 0)
     mant = math.ldexp(mant, shift)
     mant = abs(mant)
     exp -= shift
     result = ['\0'] * ((TOHEX_NBITS - 1) // 4 + 2)
     result[0] = _char_from_hex(int(mant))
     mant -= int(mant)
     result[1] = "."
     for i in range((TOHEX_NBITS - 1) // 4):
         mant *= 16.0
         result[i + 2] = _char_from_hex(int(mant))
         mant -= int(mant)
     if exp < 0:
         sign = "-"
     else:
         sign = "+"
     exp = abs(exp)
     s = ''.join(result)
     if value < 0.0:
         return space.wrap("-0x%sp%s%d" % (s, sign, exp))
     else:
         return space.wrap("0x%sp%s%d" % (s, sign, exp))
Exemplo n.º 26
0
    def _float_or_double(self, x, nmbits, nebits, suffix, nanfmt):
        nbits = nmbits + nebits + 1
        assert nbits % 32 == 0

        sbit, ebits, mbits = x >> (nbits - 1), (x >> nmbits) % (1 << nebits), x % (1 << nmbits)
        if ebits == (1 << nebits) - 1:
            result = "NaN" if mbits else "Infinity"
            if self.roundtrip and mbits:
                result += nanfmt.format(x)
        elif ebits == 0 and mbits == 0:
            result = "0.0"
        else:
            ebias = (1 << (nebits - 1)) - 1
            exponent = ebits - ebias - nmbits
            mantissa = mbits
            if ebits > 0:
                mantissa += 1 << nmbits
            else:
                exponent += 1

            if self.roundtrip:
                result = "0x{:X}p{}".format(mantissa, exponent)
            else:
                result = repr(math.ldexp(mantissa, exponent))
        return "+-"[sbit] + result + suffix
Exemplo n.º 27
0
def unpack_float(data,index,size,le):
    bytes = [ord(b) for b in data[index:index+size]]
    if len(bytes) != size:
        raise StructError,"Not enough data to unpack"
    if max(bytes) == 0:
        return 0.0
    if le == 'big':
        bytes.reverse()
    if size == 4:
        bias = 127
        exp = 8
        prec = 23
    else:
        bias = 1023
        exp = 11
        prec = 52
    mantissa = long(bytes[size-2] & (2**(15-exp)-1))
    for b in bytes[size-3::-1]:
        mantissa = mantissa << 8 | b
    mantissa = 1 + (1.0*mantissa)/(2**(prec))
    mantissa /= 2
    e = (bytes[-1] & 0x7f) << (exp - 7)
    e += (bytes[size-2] >> (15 - exp)) & (2**(exp - 7) -1)
    e -= bias
    e += 1
    sign = bytes[-1] & 0x80
    if e == bias + 2:
        if mantissa == 0.5:
            number = INFINITY
        else:
            return NAN
    else:
        number = math.ldexp(mantissa,e)
    if sign : number *= -1
    return number
Exemplo n.º 28
0
def bytes2float(bytes):
    """ Convert four bytes to a string. """
    # the first 23 bits (0-22) define the mantissa
    # the next 8 bits (23-30) the exponent,
    # the last bit (31) defines the sign
    b0, b1, b2, b3 = bytes
    mantissa = ((b2 % 128) << 16) + (b1 << 8) + b0
    exponent = (b3 % 128) * 2 + (b2 >= 128) * 1
    negative = b3 >= 128

    e = exponent - 0x7f
    m = np.abs(mantissa) / np.float64(1 << 23)

    if negative:
        return -math.ldexp(m, e)
    return math.ldexp(m, e)
Exemplo n.º 29
0
 def test_ldexp(self):
     """tests if the ldexp function works"""
     a = simplearray.array(test_sample).fill_arange()       
     b = cumath.ldexp(a,5)
     
     for i in range(test_sample):
         self.assert_(math.ldexp(a[i],5) == b[i])
Exemplo n.º 30
0
    def __getvalue__(self):
        """convert the stored floating-point number into a python native float"""
        exponentbias = (2**self.components[1])/2 - 1
        value = super(type, self).__getvalue__()
        res = bitmap.new(value, sum(self.components))

        # extract components
        res,sign = bitmap.shift(res, self.components[0])
        res,exponent = bitmap.shift(res, self.components[1])
        res,mantissa = bitmap.shift(res, self.components[2])

        if exponent > 0 and exponent < (2**self.components[1]-1):
            # convert to float
            s = -1 if sign else +1
            e = exponent - exponentbias
            m = 1.0 + (float(mantissa) / 2**self.components[2])

            # done
            return math.ldexp( math.copysign(m,s), e)

        if exponent == 2**self.components[1]-1 and mantissa == 0:
            return float('-inf') if sign else float('+inf')
        elif exponent in (0,2**self.components[1]-1) and mantissa != 0:
            return float('-nan') if sign else float('+nan')
        elif exponent == 0 and mantissa == 0:
            return float('-0') if sign else float('+0')

        # FIXME: this should return NaN or something
        Log.warn('float_t.__getvalue__ : {:s} : invalid components value : {:d} : {:d} : {:d}'.format(self.instance(), sign, exponent, mantissa))
        raise NotImplementedError
Exemplo n.º 31
0
    def test_strong_reference_implementation(self):
        # Like test_referenceImplementation, but checks for exact bit-level
        # equality.  This should pass on any box where C double contains
        # at least 53 bits of precision (the underlying algorithm suffers
        # no rounding errors -- all results are exact).
        from math import ldexp

        expected = [
            0x0eab3258d2231f, 0x1b89db315277a5, 0x1db622a5518016,
            0x0b7f9af0d575bf, 0x029e4c4db82240, 0x04961892f5d673,
            0x02b291598e4589, 0x11388382c15694, 0x02dad977c9e1fe,
            0x191d96d4d334c6
        ]
        self.gen.seed(61731 + (24903 << 32) + (614 << 64) + (42143 << 96))
        actual = self.randomlist(2000)[-10:]
        for a, e in zip(actual, expected):
            self.assertEqual(int(ldexp(a, 53)), e)
Exemplo n.º 32
0
def unpack_float(input, bigendian):
    """Interpret the 'input' string into a 32-bit or 64-bit
    IEEE representation a the number.
    """
    size = len(input)
    bytes = []
    if bigendian:
        reverse_mask = size - 1
    else:
        reverse_mask = 0
    nonzero = False
    for i in range(size):
        x = ord(input[i ^ reverse_mask])
        bytes.append(x)
        nonzero |= x
    if not nonzero:
        return 0.0
    if size == 4:
        bias = 127
        exp = 8
        prec = 23
    else:
        bias = 1023
        exp = 11
        prec = 52
    mantissa_scale_factor = 0.5**prec  # this is constant-folded if it's
    # right after the 'if'
    mantissa = r_longlong(bytes[size - 2] & ((1 << (15 - exp)) - 1))
    for i in range(size - 3, -1, -1):
        mantissa = mantissa << 8 | bytes[i]
    mantissa = 1 + mantissa * mantissa_scale_factor
    mantissa *= 0.5
    e = (bytes[-1] & 0x7f) << (exp - 7)
    e += (bytes[size - 2] >> (15 - exp)) & ((1 << (exp - 7)) - 1)
    e -= bias
    e += 1
    sign = bytes[-1] & 0x80
    if e == bias + 2:
        if mantissa == 0.5:
            number = INFINITY
        else:
            return NAN
    else:
        number = math.ldexp(mantissa, e)
    if sign: number = -number
    return number
Exemplo n.º 33
0
def convert_to_floating_point(inputVal, exponentOffset, mantissaBits,
                              exponentBits):
    """
    HELPER FUNCTION NOT WRITTEN BY THE AUTHORS
    Computes modified floating point value represented by specified
    floating point parameters.
    fp = gain * mantissa^mantissaExponent * 2^exponentOffset

    Returns:
        Floating point value corresponding to passed parameters
    """

    # Error check largest number that can be represented in specified number of bits
    maxExponent = int((1 << exponentBits) - 1)
    maxMantissa = np.uint32(((1 << mantissaBits) - 1))

    exponent = int(
        math.floor(((math.log(inputVal) / math.log(2)) - exponentOffset)))
    # mantissa = 0

    if exponent > maxExponent:
        # Too big to represent
        exponent = maxExponent
        mantissa = maxMantissa
    elif exponent >= 0:
        mantissaScale = int((1 << mantissaBits))
        effectiveExponent = int(exponentOffset + exponent)
        # ldexp(X, Y) is the same as matlab pow2(X, Y) = > X * 2 ^ Y
        mantissa = np.uint32(
            (((math.ldexp(inputVal, -effectiveExponent) - 1) * mantissaScale) +
             0.5))
        if mantissa > maxMantissa:
            # Handle case where rounding causes the mantissa to overflow
            if exponent < maxExponent:
                # Still representable
                mantissa = 0
                exponent += 1
            else:
                # Handle slightly-too-big to represent case
                mantissa = maxMantissa
    else:
        # Too small to represent
        mantissa = 0
        exponent = 0
    return ((np.uint32(exponent)) << mantissaBits) | mantissa
Exemplo n.º 34
0
def run404_03():
    """
    x = m * 2 ** e
     0.5 <= abs(m) < 1
    """
    print('{:^7} {:^7} {:^7}'.format('x', 'm', 'e'))
    print('{:-^7} {:-^7} {:-^7}'.format('', '', ''))

    for x in [0.1, 0.5, 4.0]:
        m, e = math.frexp(x)
        print('{:7.2f} {:7.2f} {:7d}'.format(x, m, e))

    print('{:^7} {:^7} {:^7}'.format('m', 'e', 'x'))
    print('{:-^7} {:-^7} {:-^7}'.format('', '', ''))

    for m, e in [(0.8, -3), (0.5, 0), (0.5, 3)]:
        x = math.ldexp(m, e)
        print('{:7.2f} {:7d} {:7.2f}'.format(m, e, x))
Exemplo n.º 35
0
def truediv(a, b):
    """Correctly-rounded true division for integers."""
    negative = a ^ b < 0
    a, b = abs(a), abs(b)
    if not b:
        raise ZeroDivisionError('division by zero')
    if a >= DBL_MIN_OVERFLOW * b:
        raise OverflowError('int/int too large to represent as a float')
    d = a.bit_length() - b.bit_length()
    if d >= 0 and a >= 2**d * b or d < 0 and a * 2**-d >= b:
        d += 1
    exp = max(d, DBL_MIN_EXP) - DBL_MANT_DIG
    a, b = a << max(-exp, 0), b << max(exp, 0)
    q, r = divmod(a, b)
    if 2 * r > b or 2 * r == b and q % 2 == 1:
        q += 1
    result = math.ldexp(q, exp)
    return -result if negative else result
Exemplo n.º 36
0
def printFloat(x, isSingle):
    assert x >= 0.0 and not math.isinf(x)
    suffix = 'f' if isSingle else ''
    if isSingle and x > 0.0:
        # Try to find more compract representation for floats, since repr treats everything as doubles
        m, e = math.frexp(x)
        half_ulp2 = math.ldexp(
            1.0, max(e - 25, -150)
        )  # don't bother doubling when near the upper range of a given e value
        half_ulp1 = (half_ulp2 / 2) if m == 0.5 and e >= -125 else half_ulp2
        lbound, ubound = x - half_ulp1, x + half_ulp2
        assert lbound < x < ubound
        s = '{:g}'.format(x).replace('+', '')
        if lbound < float(
                s
        ) < ubound:  # strict ineq to avoid potential double rounding issues
            return s + suffix
    return repr(x) + suffix
Exemplo n.º 37
0
def _put01_inf(v):
    """
    Convert a value in [0,1] to a full floating point number.

    Sort order is preserved.  Reverses :func:`_get01_inf`, but with fewer
    bits of precision.
    """
    # Arctan alternative
    # return tan(pi*(v-0.5))

    v = (v - 0.5) * 4 * _E_MAX
    s = math.copysign(1., v)
    v *= s
    e = int(v)
    m = v - e
    x = math.ldexp(s * m, e + _E_MIN)
    # print "< x,e,m,s,v",x,e+_e_min,s*m,s,v
    return x
Exemplo n.º 38
0
def _bigint_true_divide(a, b):
    ad, aexp = _AsScaledDouble(a)
    bd, bexp = _AsScaledDouble(b)
    if bd == 0.0:
        raise ZeroDivisionError("long division or modulo by zero")

    # True value is very close to ad/bd * 2**(SHIFT*(aexp-bexp))
    ad /= bd  # overflow/underflow impossible here
    aexp -= bexp
    if aexp > sys.maxint / SHIFT:
        raise OverflowError
    elif aexp < -(sys.maxint / SHIFT):
        return 0.0  # underflow to 0
    ad = math.ldexp(ad, aexp * SHIFT)
    ##if isinf(ad):   # ignore underflow to 0.0
    ##    raise OverflowError
    # math.ldexp checks and raises
    return ad
Exemplo n.º 39
0
def from50(theWord):
    """Returns a double from Rep code 0x32, 32bit floating point representation.
    Value +153 is 0x00084C80
    Value -153 is 0x0008B380"""
    #mant = float(theWord & 0xFFFF) / (1 << 15)
    #exp = (theWord >> 16 )& 0xFFFF
    # Or:
    mant = theWord & 0xFFFF
    # Only take 10 bits of exponent as significant as IEEE-754
    exp = (theWord >> 16) & 0x03FF
    # Need to divide mantissa by 1 << 15 or 32768 but
    # instead we reduce the exponent by 15
    exp -= 15
    if theWord & 0x8000:
        mant -= 0x10000
    if theWord & 0x80000000:
        exp -= 0x10000
    return math.ldexp(mant, exp)
Exemplo n.º 40
0
    def descr_hex(self, space):
        """float.hex() -> string

        Return a hexadecimal representation of a floating-point
        number.

        >>> (-0.1).hex()
        '-0x1.999999999999ap-4'
        >>> 3.14159.hex()
        '0x1.921f9f01b866ep+1'

        """
        TOHEX_NBITS = rfloat.DBL_MANT_DIG + 3 - (rfloat.DBL_MANT_DIG + 2) % 4
        value = self.floatval
        if not isfinite(value):
            return self.descr_str(space)
        if value == 0.0:
            if math.copysign(1., value) == -1.:
                return space.newtext("-0x0.0p+0")
            else:
                return space.newtext("0x0.0p+0")
        mant, exp = math.frexp(value)
        shift = 1 - max(rfloat.DBL_MIN_EXP - exp, 0)
        mant = math.ldexp(mant, shift)
        mant = abs(mant)
        exp -= shift
        result = ['\0'] * ((TOHEX_NBITS - 1) // 4 + 2)
        result[0] = _char_from_hex(int(mant))
        mant -= int(mant)
        result[1] = "."
        for i in range((TOHEX_NBITS - 1) // 4):
            mant *= 16.0
            result[i + 2] = _char_from_hex(int(mant))
            mant -= int(mant)
        if exp < 0:
            sign = "-"
        else:
            sign = "+"
        exp = abs(exp)
        s = ''.join(result)
        if value < 0.0:
            return space.newtext("-0x%sp%s%d" % (s, sign, exp))
        else:
            return space.newtext("0x%sp%s%d" % (s, sign, exp))
Exemplo n.º 41
0
Arquivo: utils.py Projeto: jacobh/boto
def minimum_part_size(size_in_bytes):
    # The default part size (4 MB) will be too small for a very large
    # archive, as there is a limit of 10,000 parts in a multipart upload.
    # This puts the maximum allowed archive size with the default part size
    # at 40,000 MB. We need to do a sanity check on the part size, and find
    # one that works if the default is too small.
    part_size = _MEGABYTE
    if (DEFAULT_PART_SIZE * MAXIMUM_NUMBER_OF_PARTS) < size_in_bytes:
        if size_in_bytes > (4096 * _MEGABYTE * 10000):
            raise ValueError("File size too large: %s" % size_in_bytes)
        min_part_size = size_in_bytes / 10000
        power = 3
        while part_size < min_part_size:
            part_size = math.ldexp(_MEGABYTE, power)
            power += 1
        part_size = int(part_size)
    else:
        part_size = DEFAULT_PART_SIZE
    return part_size
Exemplo n.º 42
0
def ceil_pow_2(n):
    """Return the least integer power of 2 that is greater than or equal to n.

    >>> ceil_pow_2(128.0)
    128.0
    >>> ceil_pow_2(0.125)
    0.125
    >>> ceil_pow_2(129.0)
    256.0
    >>> ceil_pow_2(0.126)
    0.25
    >>> ceil_pow_2(1.0)
    1.0
    """
    # frexp splits floats into mantissa and exponent, ldexp does the opposite.
    # For positive numbers, mantissa is in [0.5, 1.).
    mantissa, exponent = math.frexp(n)
    return math.ldexp(1 if mantissa >= 0 else float('nan'),
                      exponent - 1 if mantissa == 0.5 else exponent)
Exemplo n.º 43
0
def int_to_float(n):
    """
    Correctly-rounded integer-to-float conversion.

    """
    # Constants, depending only on the floating-point format in use.
    # We use an extra 2 bits of precision for rounding purposes.
    PRECISION = sys.float_info.mant_dig + 2
    SHIFT_MAX = sys.float_info.max_exp - PRECISION
    Q_MAX = 1 << PRECISION
    ROUND_HALF_TO_EVEN_CORRECTION = [0, -1, -2, 1, 0, -1, 2, 1]

    # Reduce to the case where n is positive.
    if n == 0:
        return 0.0
    elif n < 0:
        return -int_to_float(-n)

    # Convert n to a 'floating-point' number q * 2**shift, where q is an
    # integer with 'PRECISION' significant bits.  When shifting n to create q,
    # the least significant bit of q is treated as 'sticky'.  That is, the
    # least significant bit of q is set if either the corresponding bit of n
    # was already set, or any one of the bits of n lost in the shift was set.
    shift = n.bit_length() - PRECISION
    q = n << -shift if shift < 0 else (n >> shift) | bool(n & ~(-1 << shift))

    # Round half to even (actually rounds to the nearest multiple of 4,
    # rounding ties to a multiple of 8).
    q += ROUND_HALF_TO_EVEN_CORRECTION[q & 7]

    # Detect overflow.
    if shift + (q == Q_MAX) > SHIFT_MAX:
        raise OverflowError("integer too large to convert to float")

    # Checks: q is exactly representable, and q**2**shift doesn't overflow.
    assert q % 4 == 0 and q // 4 <= 2**(sys.float_info.mant_dig)
    assert q * 2**shift <= sys.float_info.max

    # Some circularity here, since float(q) is doing an int-to-float
    # conversion.  But here q is of bounded size, and is exactly representable
    # as a float.  In a low-level C-like language, this operation would be a
    # simple cast (e.g., from unsigned long long to double).
    return math.ldexp(float(q), shift)
Exemplo n.º 44
0
 def _cubic_exp2_approx(self, value):
     # type: (float) -> float
     # Derived from Cardano's formula
     exponent = int(math.floor(value))
     delta_0 = self.B * self.B - 3 * self.A * self.C
     delta_1 = (
         2.0 * self.B * self.B * self.B
         - 9.0 * self.A * self.B * self.C
         - 27.0 * self.A * self.A * (value - exponent)
     )
     cardano = _cbrt(
         (delta_1 - ((delta_1 * delta_1 - 4 * delta_0 * delta_0 * delta_0) ** 0.5))
         / 2.0
     )
     significand_plus_one = (
         -(self.B + cardano + delta_0 / cardano) / (3.0 * self.A) + 1.0
     )
     mantissa = significand_plus_one / 2
     return math.ldexp(mantissa, exponent + 1)
Exemplo n.º 45
0
 def getpowers(self, times):
     x = list(
         self._sensors.find(
             {
                 'target': 'system',
                 'timestamp': {
                     '$gte': times['begin'],
                     '$lte': times['end']
                 }
             },
             projection=['rapl', 'timestamp']))
     conso = pd.DataFrame(x)
     sonde = next(iter(x[0]['rapl']['0']))
     conso['power'] = conso['rapl'].apply(
         lambda row: math.ldexp(row['0'][sonde]['RAPL_ENERGY_PKG'], -32))
     warmup = conso[(conso["timestamp"] <= times["execution"])
                    & (conso["timestamp"] > times["warmup"])]
     execution = conso[(conso["timestamp"] > times["execution"])]
     return warmup.loc[:, ['timestamp', 'power'
                           ]], execution.loc[:, ['timestamp', 'power']],
Exemplo n.º 46
0
    def _gen_power_report(self, timestamp, target, counter):
        """
        Generate a power report using the given parameters.
        :param timestamp: Timestamp of the measurements
        :param target: Target name
        :param formula: Formula identifier
        :param power: Power estimation
        :return: Power report filled with the given parameters
        """

        metadata = {
            'scope': self.config.scope.value,
            'socket': self.socket,
        }

        power = ldexp(counter, -32)

        report = PowerReport(timestamp, self.sensor, target, power, metadata)

        return report
Exemplo n.º 47
0
    def test_strong_reference_implementation(self):
        # Like test_referenceImplementation, but checks for exact bit-level
        # equality.  This should pass on any box where C double contains
        # at least 53 bits of precision (the underlying algorithm suffers
        # no rounding errors -- all results are exact).
        from math import ldexp

        expected = [
            0x0eab3258d2231fL, 0x1b89db315277a5L, 0x1db622a5518016L,
            0x0b7f9af0d575bfL, 0x029e4c4db82240L, 0x04961892f5d673L,
            0x02b291598e4589L, 0x11388382c15694L, 0x02dad977c9e1feL,
            0x191d96d4d334c6L
        ]
        self.gen.seed(61731L + (24903L << 32) + (614L << 64) + (42143L << 96))
        actual = self.randomlist(2000)[-10:]
        for a, e in zip(actual, expected):
            if not test_support.due_to_ironpython_incompatibility(
                    "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=318984"
            ):
                self.assertEqual(long(ldexp(a, 53)), e)
Exemplo n.º 48
0
    def icalc(self, irc, msg, args, text):
        """<math expression>

        This is the same as the calc command except that it allows integer
        math, and can thus cause the bot to suck up CPU.  Hence it requires
        the 'trusted' capability to use.
        """
        try:
            self.log.info('evaluating %q from %s', text, msg.prefix)
            x = safe_eval(text, allow_ints=True)
            irc.reply(str(x))
        except OverflowError:
            maxFloat = math.ldexp(0.9999999999999999, 1024)
            irc.error(_('The answer exceeded %s or so.') % maxFloat)
        except InvalidNode as e:
            irc.error(_('Invalid syntax: %s') % e.args[0])
        except NameError as e:
            irc.error(_('%s is not a defined function.') % str(e).split()[1])
        except Exception as e:
            irc.error(utils.exnToString(e))
Exemplo n.º 49
0
        def __init__(self, value):
            if isinstance(value, (int, long)):
                self.n = value
                self.d = 1

            elif isinstance(value, float):
                # Convert to exact rational equivalent.
                f, e = math.frexp(abs(value))
                assert f == 0 or 0.5 <= f < 1.0
                # |value| = f * 2**e exactly

                # Suck up CHUNK bits at a time; 28 is enough so that we suck
                # up all bits in 2 iterations for all known binary double-
                # precision formats, and small enough to fit in an int.
                CHUNK = 28
                top = 0
                # invariant: |value| = (top + f) * 2**e exactly
                while f:
                    f = math.ldexp(f, CHUNK)
                    digit = int(f)
                    assert digit >> CHUNK == 0
                    top = (top << CHUNK) | digit
                    f -= digit
                    assert 0.0 <= f < 1.0
                    e -= CHUNK

                # Now |value| = top * 2**e exactly.
                if e >= 0:
                    n = top << e
                    d = 1
                else:
                    n = top
                    d = 1 << -e
                if value < 0:
                    n = -n
                self.n = n
                self.d = d
                assert float(n) / float(d) == value

            else:
                raise TypeError("can't deal with %r" % val)
Exemplo n.º 50
0
def int_to_float(n):
    """
    Correctly-rounded integer-to-float conversion.

    """
    PRECISION = sys.float_info.mant_dig + 2
    SHIFT_MAX = sys.float_info.max_exp - PRECISION
    Q_MAX = 1 << PRECISION
    ROUND_HALF_TO_EVEN_CORRECTION = [0, -1, -2, 1, 0, -1, 2, 1]
    if n == 0:
        return 0.0
    elif n < 0:
        return -int_to_float(-n)
    shift = n.bit_length() - PRECISION
    q = n << -shift if shift < 0 else n >> shift | bool(n & ~(-1 << shift))
    q += ROUND_HALF_TO_EVEN_CORRECTION[q & 7]
    if shift + (q == Q_MAX) > SHIFT_MAX:
        raise OverflowError('integer too large to convert to float')
    assert q % 4 == 0 and q // 4 <= 2**sys.float_info.mant_dig
    assert q * 2**shift <= sys.float_info.max
    return math.ldexp(float(q), shift)
Exemplo n.º 51
0
    def ParseFloat64(self, index: int) -> str:
        if self.data[index + 7] == 0:
            return 0

        exp = self.data[
            index +
            7] - 184  #  -184 = -128 + -56 (56 because the significand is behind a decimal dot)
        mantissa = ((self.data[index + 6] | 0x80) << 48) | (self.data[index + 5] << 40) | (self.data[index + 4] << 32)  \
            | (self.data[index + 3] << 24) | (self.data[index + 2] << 16) | (self.data[index + 1] << 8) | self.data[index]

        # We must always output a positive number for doubles,
        # because a token for '-' is already added before the negative ones.
        number = math.ldexp(mantissa, exp)

        # Doubles always get their postfix '#'
        # Must round to 16 significant figures (from 17) when displaying
        # The exponent sign for doubles is 'D' instead of 'E'
        numberStr = self.CanonizeNumber(
            '%s' % float('%.16g' % number)).replace('E', 'D') + '#'

        return numberStr
Exemplo n.º 52
0
    def float_to_bin(f):
        # NOTE: the implementation closely follows float.hex()
        if not isfinite(f):
            return repr(f)  # inf nan

        sign = '-' * (copysign(1.0, f) < 0)
        if f == 0:  # zero
            return sign + '0b0.0p+0'

        # f = m * 2**e
        m, e = frexp(fabs(f))  # 0.5 <= m < 1.0
        shift = 1 - max(sys.float_info.min_exp - e, 0)
        m = ldexp(m, shift)  # m * (2**shift)
        e -= shift

        fm, im = modf(m)
        assert im == 1.0 or im == 0.0
        n, d = fm.as_integer_ratio()
        assert d & (d - 1) == 0  # power of two
        return '{sign}0b{i}.{frac:0{width}b}p{e:+}'.format(
            sign=sign, i=int(im), frac=n, width=d.bit_length() - 1, e=e)
Exemplo n.º 53
0
def to_float(s, strict=False, rnd=round_fast):
    """
    Convert a raw mpf to a Python float. The result is exact if the
    bitcount of s is <= 53 and no underflow/overflow occurs.

    If the number is too large or too small to represent as a regular
    float, it will be converted to inf or 0.0. Setting strict=True
    forces an OverflowError to be raised instead.

    Warning: with a directed rounding mode, the correct nearest representable
    floating-point number in the specified direction might not be computed
    in case of overflow or (gradual) underflow.
    """
    sign, man, exp, bc = s
    if not man:
        if s == fzero:
            return 0.0
        if s == finf:
            return math_float_inf
        if s == fninf:
            return -math_float_inf
        return math_float_inf / math_float_inf
    if bc > 53:
        sign, man, exp, bc = normalize1(sign, man, exp, bc, 53, rnd)
    if sign:
        man = -man
    try:
        return math.ldexp(man, exp)
    except OverflowError:
        if strict:
            raise
        # Overflow to infinity
        if exp + bc > 0:
            if sign:
                return -math_float_inf
            else:
                return math_float_inf
        # Underflow to zero
        return 0.0
Exemplo n.º 54
0
    def _zoomRatio(self, basePoint):
        # type: (om.MPoint) -> float
        """Calculate zoom factor as distance from the current view's camera position."""
        # FIXME: all views share this value from current one.

        # camera distance
        cameraPath = omui.M3dView.active3dView().getCamera()
        camNode = om.MFnDependencyNode(cameraPath.node())
        isOrtho = camNode.findPlug("orthographic", False)

        camMat = cameraPath.inclusiveMatrix().homogenize()
        camPos = om.MPoint(
            camMat.getElement(3, 0),
            camMat.getElement(3, 1),
            camMat.getElement(3, 2),
        )

        if isOrtho.asBool():
            orthoWidth = camNode.findPlug("orthographicWidth", False).asFloat()
            return math.ldexp(orthoWidth, 3) * 0.01
        else:
            return basePoint.distanceTo(camPos) * 0.1
Exemplo n.º 55
0
def _int_to_real(num):
    """
    Convert REAL8 from internal integer representation to Python reals.

    Zeroes:
        >>> print(_int_to_real(0x0))
        0.0
        >>> print(_int_to_real(0x8000000000000000)) # negative
        0.0
        >>> print(_int_to_real(0xff00000000000000)) # denormalized
        0.0

    Others:
        >>> print(_int_to_real(0x4110000000000000))
        1.0
        >>> print(_int_to_real(0xC120000000000000))
        -2.0
    """
    sgn = -1 if 0x8000000000000000 & num else 1
    mant = num & 0x00ffffffffffffff
    exp = (num >> 56) & 0x7f
    return math.ldexp(sgn * mant, 4 * (exp - 64) - 56)
Exemplo n.º 56
0
def _half_to_float(half):
    # Half is 16-bit int
    single = (half & 0x7fff) << 13 | (half & 0x8000) << 16
    if (half & 0x7c00) != 0x7c00:
        mant = half & 0x03ff
        exp = half & 0x7c00
        if mant and exp == 0:
            exp = 0x1c400

            while (mant & 0x400) == 0:
                mant <<= 1
                exp -= 0x400

            mant &= 0x3ff
            single = (half & 0x8000) << 16 | (exp | mant) << 13

            return struct.unpack('>f', struct.pack('>I', single))[0]

        return math.ldexp(struct.unpack('>f', struct.pack('>I', single))[0], 112)

    single |= 0x7f800000
    return struct.unpack('>f', struct.pack('>I', single))[0]
Exemplo n.º 57
0
def test_handle_hwpc_report_with_one_rapl_event_and_other_groups(state):
    """
    handle a HWPC report with a simple RAPL event and events from other
    groups

    The HWPC report contain one RAPL event and events from a group 'sys'
    with two cores

    The handle method must return a PowerReport containing only the RAPL event
    """
    raw_power = 10
    socket_id = '1'
    rapl_event_id = 'RAPL_1'

    hwpc_report = create_report_root([
        create_group_report('rapl', [
            create_socket_report(
                socket_id, [create_core_report('1', rapl_event_id, raw_power)])
        ]),
        create_group_report('sys', [
            create_socket_report(socket_id, [
                create_core_report('1', 'e0', 0),
                create_core_report('2', 'e0', 0)
            ])
        ])
    ])

    validation_report = PowerReport(hwpc_report.timestamp, hwpc_report.sensor,
                                    hwpc_report.target,
                                    math.ldexp(raw_power, -32), {
                                        'socket': socket_id,
                                        'event': rapl_event_id
                                    })

    result = RAPLFormulaHWPCReportHandler(get_fake_pusher())._process_report(
        hwpc_report, state)

    assert [validation_report] == result
Exemplo n.º 58
0
    def nearest_point_on_curve(self, P, cps):
        """Compute the parameter value fo the point on a Bezier curve
        segment closest to some arbitrary, user-input point
        Return point on the curve at that parameter value"""
        self.maxdepth = 64
        self.epsilon = math.ldexp(1.0, -self.maxdepth-1)
        rec_depth = 0
        w_degree = 5
        degree = 3
        # Convert point p and bezcurve defined by control points cps into
        # a 5th-degree bezier curve form
        w = self.convert_to_bezier_form(P, cps)
        # Find all possible roots of that 5th degree equation
        n_candidates = self.find_roots(w, rec_depth)
        t_candidates = self.tvals

        # Check distance to beginning of curve, where t = 0
        dist = (P - cps[0]).get_length_sqrd()
        tval = 0.0

        # Compare distances of point p to all candidate points found as roots
        for t in t_candidates:
            p = self.get_at_t(cps, t)
            new_dist = (P - p).get_length_sqrd()
            if new_dist < dist:
                dist = new_dist
                tval = t

        # Finally, look at distance to end point, where t = 1.0
        new_dist = (P - cps[3]).get_length_sqrd()
        if new_dist < dist:
            dist = new_dist
            tval = 1.0

        #print tval, dist, self.tvals

        # Return point on curve at parameter value tval
        return self.get_at_t(cps, tval)
Exemplo n.º 59
0
def minimum_part_size(size_in_bytes, default_part_size=DEFAULT_PART_SIZE):
    """Calculate the minimum part size needed for a multipart upload.

    Glacier allows a maximum of 10,000 parts per upload.  It also
    states that the maximum archive size is 10,000 * 4 GB, which means
    the part size can range from 1MB to 4GB (provided it is one 1MB
    multiplied by a power of 2).

    This function will compute what the minimum part size must be in
    order to upload a file of size ``size_in_bytes``.

    It will first check if ``default_part_size`` is sufficient for
    a part size given the ``size_in_bytes``.  If this is not the case,
    then the smallest part size than can accomodate a file of size
    ``size_in_bytes`` will be returned.

    If the file size is greater than the maximum allowed archive
    size of 10,000 * 4GB, a ``ValueError`` will be raised.

    """
    # The default part size (4 MB) will be too small for a very large
    # archive, as there is a limit of 10,000 parts in a multipart upload.
    # This puts the maximum allowed archive size with the default part size
    # at 40,000 MB. We need to do a sanity check on the part size, and find
    # one that works if the default is too small.
    part_size = _MEGABYTE
    if (default_part_size * MAXIMUM_NUMBER_OF_PARTS) < size_in_bytes:
        if size_in_bytes > (4096 * _MEGABYTE * 10000):
            raise ValueError("File size too large: %s" % size_in_bytes)
        min_part_size = size_in_bytes / 10000
        power = 3
        while part_size < min_part_size:
            part_size = math.ldexp(_MEGABYTE, power)
            power += 1
        part_size = int(part_size)
    else:
        part_size = default_part_size
    return part_size
Exemplo n.º 60
0
    def test_roundtrip(self):
        def roundtrip(x):
            return fromHex(toHex(x))

        for x in [
                NAN, INF, self.MAX, self.MIN, self.MIN - self.TINY, self.TINY,
                0.0
        ]:
            self.identical(x, roundtrip(x))
            self.identical(-x, roundtrip(-x))

        # fromHex(toHex(x)) should exactly recover x, for any non-NaN float x.
        import random
        for i in range(10000):
            e = random.randrange(-1200, 1200)
            m = random.random()
            s = random.choice([1.0, -1.0])
            try:
                x = s * ldexp(m, e)
            except OverflowError:
                pass
            else:
                self.identical(x, fromHex(toHex(x)))