Python math.frexp() Examples

The following are code examples for showing how to use math.frexp(). 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_math.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def testFrexp(self):
        self.assertRaises(TypeError, math.frexp)

        def testfrexp(name, result, expected):
            (mant, exp), (emant, eexp) = result, expected
            if abs(mant-emant) > eps or exp != eexp:
                self.fail('%s returned %r, expected %r'%\
                          (name, (mant, exp), (emant,eexp)))

        testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1))
        testfrexp('frexp(0)', math.frexp(0), (0, 0))
        testfrexp('frexp(1)', math.frexp(1), (0.5, 1))
        testfrexp('frexp(2)', math.frexp(2), (0.5, 2))

        self.assertEqual(math.frexp(INF)[0], INF)
        self.assertEqual(math.frexp(NINF)[0], NINF)
        self.assertTrue(math.isnan(math.frexp(NAN)[0])) 
Example 2
Project: NiujiaoDebugger   Author: MrSrc   File: test_math.py    GNU General Public License v3.0 6 votes vote down vote up
def testFrexp(self):
        self.assertRaises(TypeError, math.frexp)

        def testfrexp(name, result, expected):
            (mant, exp), (emant, eexp) = result, expected
            if abs(mant-emant) > eps or exp != eexp:
                self.fail('%s returned %r, expected %r'%\
                          (name, result, expected))

        testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1))
        testfrexp('frexp(0)', math.frexp(0), (0, 0))
        testfrexp('frexp(1)', math.frexp(1), (0.5, 1))
        testfrexp('frexp(2)', math.frexp(2), (0.5, 2))

        self.assertEqual(math.frexp(INF)[0], INF)
        self.assertEqual(math.frexp(NINF)[0], NINF)
        self.assertTrue(math.isnan(math.frexp(NAN)[0])) 
Example 3
Project: bssrdf-estimate   Author: tatsy   File: hdr_pixel.py    MIT License 6 votes vote down vote up
def __init__(self, r, g, b):
        d = max(r, max(g, b))
        if (d < 1.0e-32):
            self.r = 0
            self.g = 0
            self.b = 0
            self.e = 0
            return

        m, ie = math.frexp(d)
        d = m * 256.0 / d

        self.r = int(clamp(r * d, 0, 255))
        self.g = int(clamp(g * d, 0, 255))
        self.b = int(clamp(b * d, 0, 255))
        self.e = int(clamp(ie + 128, 0, 255)) 
Example 4
Project: rpython-lang-scheme   Author: tomoh1r   File: rewrite.py    MIT License 6 votes vote down vote up
def optimize_FLOAT_TRUEDIV(self, op):
        arg1 = op.getarg(0)
        arg2 = op.getarg(1)
        v2 = self.get_box_replacement(arg2)

        # replace "x / const" by "x * (1/const)" if possible
        newop = op
        if v2.is_constant():
            divisor = v2.getfloat()
            fraction = math.frexp(divisor)[0]
            # This optimization is valid for powers of two
            # but not for zeroes, some denormals and NaN:
            if fraction == 0.5 or fraction == -0.5:
                reciprocal = 1.0 / divisor
                rfraction = math.frexp(reciprocal)[0]
                if rfraction == 0.5 or rfraction == -0.5:
                    c = ConstFloat(longlong.getfloatstorage(reciprocal))
                    newop = self.replace_op_with(op, rop.FLOAT_MUL,
                                                 args=[arg1, c])
        self.emit_operation(newop) 
Example 5
Project: rpython-lang-scheme   Author: tomoh1r   File: objectmodel.py    MIT License 6 votes vote down vote up
def _hash_float(f):
    """The algorithm behind compute_hash() for a float.
    This implementation is identical to the CPython implementation,
    except the fact that the integer case is not treated specially.
    In RPython, floats cannot be used with ints in dicts, anyway.
    """
    from rpython.rlib.rarithmetic import intmask
    from rpython.rlib.rfloat import isfinite, isinf
    if not isfinite(f):
        if isinf(f):
            if f < 0.0:
                return -271828
            else:
                return 314159
        else: #isnan(f):
            return 0
    v, expo = math.frexp(f)
    v *= TAKE_NEXT
    hipart = int(v)
    v = (v - float(hipart)) * TAKE_NEXT
    x = hipart + int(v) + (expo << 15)
    return intmask(x) 
Example 6
Project: rpython-lang-scheme   Author: tomoh1r   File: rbigint.py    MIT License 6 votes vote down vote up
def _fromfloat_finite(dval):
        sign = 1
        if dval < 0.0:
            sign = -1
            dval = -dval
        frac, expo = math.frexp(dval) # dval = frac*2**expo; 0.0 <= frac < 1.0
        if expo <= 0:
            return NULLRBIGINT
        ndig = (expo-1) // SHIFT + 1 # Number of 'digits' in result
        v = rbigint([NULLDIGIT] * ndig, sign, ndig)
        frac = math.ldexp(frac, (expo-1) % SHIFT + 1)
        for i in range(ndig-1, -1, -1):
            # use int(int(frac)) as a workaround for a CPython bug:
            # with frac == 2147483647.0, int(frac) == 2147483647L
            bits = int(int(frac))
            v.setdigit(i, bits)
            frac -= float(bits)
            frac = math.ldexp(frac, SHIFT)
        return v 
Example 7
Project: ironpython2   Author: IronLanguages   File: test_math.py    Apache License 2.0 6 votes vote down vote up
def testFrexp(self):
        self.assertRaises(TypeError, math.frexp)

        def testfrexp(name, result, expected):
            (mant, exp), (emant, eexp) = result, expected
            if abs(mant-emant) > eps or exp != eexp:
                self.fail('%s returned %r, expected %r'%\
                          (name, (mant, exp), (emant,eexp)))

        testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1))
        testfrexp('frexp(0)', math.frexp(0), (0, 0))
        testfrexp('frexp(1)', math.frexp(1), (0.5, 1))
        testfrexp('frexp(2)', math.frexp(2), (0.5, 2))

        self.assertEqual(math.frexp(INF)[0], INF)
        self.assertEqual(math.frexp(NINF)[0], NINF)
        self.assertTrue(math.isnan(math.frexp(NAN)[0])) 
Example 8
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_math.py    GNU General Public License v3.0 6 votes vote down vote up
def testFrexp(self):
        self.assertRaises(TypeError, math.frexp)

        def testfrexp(name, result, expected):
            (mant, exp), (emant, eexp) = result, expected
            if abs(mant-emant) > eps or exp != eexp:
                self.fail('%s returned %r, expected %r'%\
                          (name, result, expected))

        testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1))
        testfrexp('frexp(0)', math.frexp(0), (0, 0))
        testfrexp('frexp(1)', math.frexp(1), (0.5, 1))
        testfrexp('frexp(2)', math.frexp(2), (0.5, 2))

        self.assertEqual(math.frexp(INF)[0], INF)
        self.assertEqual(math.frexp(NINF)[0], NINF)
        self.assertTrue(math.isnan(math.frexp(NAN)[0])) 
Example 9
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_math.py    GNU General Public License v2.0 6 votes vote down vote up
def testFrexp(self):
        self.assertRaises(TypeError, math.frexp)

        def testfrexp(name, result, expected):
            (mant, exp), (emant, eexp) = result, expected
            if abs(mant-emant) > eps or exp != eexp:
                self.fail('%s returned %r, expected %r'%\
                          (name, result, expected))

        testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1))
        testfrexp('frexp(0)', math.frexp(0), (0, 0))
        testfrexp('frexp(1)', math.frexp(1), (0.5, 1))
        testfrexp('frexp(2)', math.frexp(2), (0.5, 2))

        self.assertEqual(math.frexp(INF)[0], INF)
        self.assertEqual(math.frexp(NINF)[0], NINF)
        self.assertTrue(math.isnan(math.frexp(NAN)[0])) 
Example 10
Project: oss-ftp   Author: aliyun   File: test_math.py    MIT License 6 votes vote down vote up
def testFrexp(self):
        self.assertRaises(TypeError, math.frexp)

        def testfrexp(name, result, expected):
            (mant, exp), (emant, eexp) = result, expected
            if abs(mant-emant) > eps or exp != eexp:
                self.fail('%s returned %r, expected %r'%\
                          (name, (mant, exp), (emant,eexp)))

        testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1))
        testfrexp('frexp(0)', math.frexp(0), (0, 0))
        testfrexp('frexp(1)', math.frexp(1), (0.5, 1))
        testfrexp('frexp(2)', math.frexp(2), (0.5, 2))

        self.assertEqual(math.frexp(INF)[0], INF)
        self.assertEqual(math.frexp(NINF)[0], NINF)
        self.assertTrue(math.isnan(math.frexp(NAN)[0])) 
Example 11
Project: s2sphere   Author: sidewalklabs   File: sphere.py    MIT License 6 votes vote down vote up
def get_min_level(self, value):
        """Minimum cell level for given value.

        Return the minimum level such that the metric is at most the given
        value, or ``s2sphere.CellId.MAX_LEVEL`` if there is no such level.
        For example, ``s2sphere.MAX_DIAG.get_min_level(0.1)`` returns the
        minimum level such that all cell diagonal lengths are 0.1 or smaller.
        The return value is always a valid level.

        :param value:
            Depending on whether this is used in one or two dimensions, this is
            an angle in radians or a solid angle in steradians.
        """
        if value <= 0:
            return CellId.MAX_LEVEL

        m, x = math.frexp(value / self.deriv())
        level = max(0, min(CellId.MAX_LEVEL, -((x - 1) >> (self.__dim - 1))))
        assert level == CellId.MAX_LEVEL or self.get_value(level) <= value
        assert level == 0 or self.get_value(level - 1) > value
        return level 
Example 12
Project: s2sphere   Author: sidewalklabs   File: sphere.py    MIT License 6 votes vote down vote up
def get_max_level(self, value):
        """Maximum cell level for given value.

        Return the maximum level such that the metric is at least the given
        value, or zero if there is no such level.  For example,
        ``s2sphere.MIN_WIDTH.get_max_level(0.1)`` returns the maximum level
        such that all cells have a minimum width of 0.1 or larger.
        The return value is always a valid level.

        :param value:
            Depending on whether this is used in one or two dimensions, this is
            an angle in radians or a solid angle in steradians.
        """
        if value <= 0:
            return CellId.MAX_LEVEL

        m, x = math.frexp(self.deriv() / value)
        level = max(0, min(CellId.MAX_LEVEL, (x - 1) >> (self.__dim - 1)))
        assert level == 0 or self.get_value(level) >= value
        assert level == CellId.MAX_LEVEL or self.get_value(level + 1) < value
        return level 
Example 13
Project: Python-iBeacon-Scan   Author: NikNitro   File: libmpf.py    GNU General Public License v3.0 6 votes vote down vote up
def from_float(x, prec=53, rnd=round_fast):
    """Create a raw mpf from a Python float, rounding if necessary.
    If prec >= 53, the result is guaranteed to represent exactly the
    same number as the input. If prec is not specified, use prec=53."""
    # frexp only raises an exception for nan on some platforms
    if x != x:
        return fnan
    # in Python2.5 math.frexp gives an exception for float infinity
    # in Python2.6 it returns (float infinity, 0)
    try:
        m, e = math.frexp(x)
    except:
        if x == math_float_inf: return finf
        if x == -math_float_inf: return fninf
        return fnan
    if x == math_float_inf: return finf
    if x == -math_float_inf: return fninf
    return from_man_exp(int(m*(1<<53)), e-53, prec, rnd) 
Example 14
Project: hydra   Author: tatsy   File: pixel.py    MIT License 6 votes vote down vote up
def __init__(self, r, g, b):
        d = max(r, max(g, b))
        if (d < EPS):
            self.r = 0
            self.g = 0
            self.b = 0
            self.e = 0
            return

        m, ie = math.frexp(d)
        d = m * 256.0 / d

        self.r = int(clamp(r * d, (0, 255)))
        self.g = int(clamp(g * d, (0, 255)))
        self.b = int(clamp(b * d, (0, 255)))
        self.e = int(clamp(ie + 128, (0, 255))) 
Example 15
Project: auto_tomo_calibration-experimental   Author: DiamondLightSource   File: __init__.py    Apache License 2.0 6 votes vote down vote up
def error_components(self):
        """
        Individual components of the standard deviation of the affine
        function (in absolute value), returned as a dictionary with
        Variable objects as keys.

        This method assumes that the derivatives contained in the
        object take scalar values (and are not a tuple, like what
        math.frexp() returns, for instance).
        """

        # Calculation of the variance:
        error_components = {}
        for (variable, derivative) in self.derivatives.items():
            # Individual standard error due to variable:
            error_components[variable] = abs(derivative*variable._std_dev)

        return error_components 
Example 16
Project: auto_tomo_calibration-experimental   Author: DiamondLightSource   File: __init__.py    Apache License 2.0 6 votes vote down vote up
def error_components(self):
        """
        Individual components of the standard deviation of the affine
        function (in absolute value), returned as a dictionary with
        Variable objects as keys.

        This method assumes that the derivatives contained in the
        object take scalar values (and are not a tuple, like what
        math.frexp() returns, for instance).
        """

        # Calculation of the variance:
        error_components = {}
        for (variable, derivative) in self.derivatives.items():
            # Individual standard error due to variable:
            error_components[variable] = abs(derivative*variable._std_dev)

        return error_components 
Example 17
Project: auto_tomo_calibration-experimental   Author: DiamondLightSource   File: __init__.py    Apache License 2.0 6 votes vote down vote up
def error_components(self):
        """
        Individual components of the standard deviation of the affine
        function (in absolute value), returned as a dictionary with
        Variable objects as keys.

        This method assumes that the derivatives contained in the
        object take scalar values (and are not a tuple, like what
        math.frexp() returns, for instance).
        """

        # Calculation of the variance:
        error_components = {}
        for (variable, derivative) in self.derivatives.items():
            # Individual standard error due to variable:
            error_components[variable] = abs(derivative*variable._std_dev)

        return error_components 
Example 18
Project: auto_tomo_calibration-experimental   Author: DiamondLightSource   File: __init__.py    Apache License 2.0 6 votes vote down vote up
def error_components(self):
        """
        Individual components of the standard deviation of the affine
        function (in absolute value), returned as a dictionary with
        Variable objects as keys.

        This method assumes that the derivatives contained in the
        object take scalar values (and are not a tuple, like what
        math.frexp() returns, for instance).
        """

        # Calculation of the variance:
        error_components = {}
        for (variable, derivative) in self.derivatives.items():
            # Individual standard error due to variable:
            error_components[variable] = abs(derivative*variable._std_dev)

        return error_components 
Example 19
Project: auto_tomo_calibration-experimental   Author: DiamondLightSource   File: __init__.py    Apache License 2.0 6 votes vote down vote up
def error_components(self):
        """
        Individual components of the standard deviation of the affine
        function (in absolute value), returned as a dictionary with
        Variable objects as keys.

        This method assumes that the derivatives contained in the
        object take scalar values (and are not a tuple, like what
        math.frexp() returns, for instance).
        """

        # Calculation of the variance:
        error_components = {}
        for (variable, derivative) in self.derivatives.items():
            # Individual standard error due to variable:
            error_components[variable] = abs(derivative*variable._std_dev)

        return error_components 
Example 20
Project: auto_tomo_calibration-experimental   Author: DiamondLightSource   File: __init__.py    Apache License 2.0 6 votes vote down vote up
def error_components(self):
        """
        Individual components of the standard deviation of the affine
        function (in absolute value), returned as a dictionary with
        Variable objects as keys.

        This method assumes that the derivatives contained in the
        object take scalar values (and are not a tuple, like what
        math.frexp() returns, for instance).
        """

        # Calculation of the variance:
        error_components = {}
        for (variable, derivative) in self.derivatives.items():
            # Individual standard error due to variable:
            error_components[variable] = abs(derivative*variable._std_dev)

        return error_components 
Example 21
Project: auto_tomo_calibration-experimental   Author: DiamondLightSource   File: __init__.py    Apache License 2.0 6 votes vote down vote up
def error_components(self):
        """
        Individual components of the standard deviation of the affine
        function (in absolute value), returned as a dictionary with
        Variable objects as keys.

        This method assumes that the derivatives contained in the
        object take scalar values (and are not a tuple, like what
        math.frexp() returns, for instance).
        """

        # Calculation of the variance:
        error_components = {}
        for (variable, derivative) in self.derivatives.items():
            # Individual standard error due to variable:
            error_components[variable] = abs(derivative*variable._std_dev)

        return error_components 
Example 22
Project: pyblish-win   Author: pyblish   File: aifc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
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 or fmant != fmant: # 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_ushort(f, expon)
    _write_ulong(f, himant)
    _write_ulong(f, lomant) 
Example 23
Project: python-pool-performance   Author: JohnStarich   File: utils.py    MIT License 5 votes vote down vote up
def bytes_for_humans(byte_count: int):
    # Get power of two directly from floating point exponent bits (mantissa)
    power_of_2 = frexp(byte_count)[1] - 1
    binary_multiple = power_of_2 // 10
    # If too big, represent in largest form
    if binary_multiple >= len(byte_names):
        binary_multiple = len(byte_names) - 1
    # Gets the magnitude of the most significant multiple of 1024
    impercise_magnitude = byte_count // (1 << (binary_multiple * 10))
    # If less than 1024B, just return number of bytes
    if binary_multiple == 0:
        return str(impercise_magnitude) + ' B'
    return str(impercise_magnitude) + ' ' \
        + byte_names[binary_multiple - 1] + 'B' 
Example 24
Project: asn1tools   Author: eerimoq   File: ber.py    MIT License 5 votes vote down vote up
def encode_real(data):
    if data == float('inf'):
        data = b'\x40'
    elif data == float('-inf'):
        data = b'\x41'
    elif math.isnan(data):
        data = b'\x42'
    elif data == 0.0:
        data = b''
    else:
        if data >= 0:
            negative_bit = 0
        else:
            negative_bit = 0x40
            data *= -1

        mantissa, exponent = math.frexp(abs(data))
        mantissa = int(mantissa * 2 ** 53)
        lowest_set_bit = compiler.lowest_set_bit(mantissa)
        mantissa >>= lowest_set_bit
        mantissa |= (0x80 << (8 * ((mantissa.bit_length() // 8) + 1)))
        mantissa = binascii.unhexlify(hex(mantissa)[4:].rstrip('L'))
        exponent = (52 - lowest_set_bit - exponent)

        if -129 < exponent < 128:
            exponent = [0x80 | negative_bit, ((0xff - exponent) & 0xff)]
        elif -32769 < exponent < 32768:
            exponent = ((0xffff - exponent) & 0xffff)
            exponent = [0x81 | negative_bit, (exponent >> 8), exponent & 0xff]
        else:
            raise NotImplementedError(
                'REAL exponent {} out of range.'.format(exponent))

        data = bytearray(exponent) + mantissa

    return data 
Example 25
Project: NiujiaoDebugger   Author: MrSrc   File: aifc.py    GNU General Public License v3.0 5 votes vote down vote up
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 or fmant != fmant: # 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 = int(fsmant)
            fmant = math.ldexp(fmant - fsmant, 32)
            fsmant = math.floor(fmant)
            lomant = int(fsmant)
    _write_ushort(f, expon)
    _write_ulong(f, himant)
    _write_ulong(f, lomant) 
Example 26
Project: rpython-lang-scheme   Author: tomoh1r   File: test_rbuiltin.py    MIT License 5 votes vote down vote up
def test_builtin_math_frexp(self):
        def fn(f):
            return math.frexp(f)
        for x in (.5, 1, 1.5, 10/3.0):
            for y in (1, -1):
                res = self.interpret(fn, [x*y])
                mantissa, exponent = math.frexp(x*y)
                assert (self.float_eq(res.item0, mantissa) and
                        self.float_eq(res.item1, exponent)) 
Example 27
Project: rpython-lang-scheme   Author: tomoh1r   File: test_standalone.py    MIT License 5 votes vote down vote up
def test_frexp(self):
        import math
        def entry_point(argv):
            m, e = math.frexp(0)
            x, y = math.frexp(0)
            print m, x
            return 0

        t, cbuilder = self.compile(entry_point)
        data = cbuilder.cmdexec('hi there')
        assert map(float, data.split()) == [0.0, 0.0] 
Example 28
Project: rpython-lang-scheme   Author: tomoh1r   File: test_sandbox.py    MIT License 5 votes vote down vote up
def test_safefuncs(self):
        import math
        def entry_point(argv):
            a = float(argv[1])
            print int(math.floor(a - 0.2)),
            print int(math.ceil(a)),
            print int(100.0 * math.sin(a)),
            mantissa, exponent = math.frexp(a)
            print int(100.0 * mantissa), exponent,
            fracpart, intpart = math.modf(a)
            print int(100.0 * fracpart), int(intpart),
            print
            return 0
        self.run(entry_point, ["3.011"], "2 4 13 75 2 1 3\n") 
Example 29
Project: rpython-lang-scheme   Author: tomoh1r   File: rfloat.py    MIT License 5 votes vote down vote up
def float_as_rbigint_ratio(value):
    from rpython.rlib.rbigint import rbigint

    if isinf(value):
        raise OverflowError("cannot pass infinity to as_integer_ratio()")
    elif isnan(value):
        raise ValueError("cannot pass nan to as_integer_ratio()")
    float_part, exp_int = math.frexp(value)
    for i in range(300):
        if float_part == math.floor(float_part):
            break
        float_part *= 2.0
        exp_int -= 1
    num = rbigint.fromfloat(float_part)
    den = rbigint.fromint(1)
    exp = den.lshift(abs(exp_int))
    if exp_int > 0:
        num = num.mul(exp)
    else:
        den = exp
    return num, den



# Implementation of the error function, the complimentary error function, the
# gamma function, and the natural log of the gamma function.  These exist in
# libm, but I hear those implementations are horrible. 
Example 30
Project: ironpython2   Author: IronLanguages   File: aifc.py    Apache License 2.0 5 votes vote down vote up
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 or fmant != fmant: # 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_ushort(f, expon)
    _write_ulong(f, himant)
    _write_ulong(f, lomant) 
Example 31
Project: respeaker_python_library   Author: respeaker   File: spectrum_analyzer.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, size, sample_rate=16000, band_number=12, window=[50, 8000]):
        self.size = 1 << math.frexp(size - 1)[1]
        self.sample_rate = float(sample_rate)
        self.resolution = self.sample_rate / self.size  # (sample_rate/2) / (band/2)

        self.set_band(band_number, window)

        self.fft = FFT(self.size) 
Example 32
Project: Blockly-rduino-communication   Author: technologiescollege   File: aifc.py    GNU General Public License v3.0 5 votes vote down vote up
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 or fmant != fmant: # 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 = int(fsmant)
            fmant = math.ldexp(fmant - fsmant, 32)
            fsmant = math.floor(fmant)
            lomant = int(fsmant)
    _write_ushort(f, expon)
    _write_ulong(f, himant)
    _write_ulong(f, lomant) 
Example 33
Project: IronHydra   Author: microdee   File: aifc.py    MIT License 5 votes vote down vote up
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) 
Example 34
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: aifc.py    GNU General Public License v2.0 5 votes vote down vote up
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 or fmant != fmant: # 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 = int(fsmant)
            fmant = math.ldexp(fmant - fsmant, 32)
            fsmant = math.floor(fmant)
            lomant = int(fsmant)
    _write_ushort(f, expon)
    _write_ulong(f, himant)
    _write_ulong(f, lomant) 
Example 35
Project: aws-lambda-runtime-pypy   Author: uscheller   File: aifc.py    Apache License 2.0 5 votes vote down vote up
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 or fmant != fmant: # 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 = int(fsmant)
            fmant = math.ldexp(fmant - fsmant, 32)
            fsmant = math.floor(fmant)
            lomant = int(fsmant)
    _write_ushort(f, expon)
    _write_ulong(f, himant)
    _write_ulong(f, lomant) 
Example 36
Project: oss-ftp   Author: aliyun   File: aifc.py    MIT License 5 votes vote down vote up
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 or fmant != fmant: # 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_ushort(f, expon)
    _write_ulong(f, himant)
    _write_ulong(f, lomant) 
Example 37
Project: setup   Author: mindbender-studio   File: aifc.py    MIT License 5 votes vote down vote up
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 or fmant != fmant: # 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 = int(fsmant)
            fmant = math.ldexp(fmant - fsmant, 32)
            fsmant = math.floor(fmant)
            lomant = int(fsmant)
    _write_ushort(f, expon)
    _write_ulong(f, himant)
    _write_ulong(f, lomant) 
Example 38
Project: TensorGCC   Author: edumotya   File: ops.py    MIT License 5 votes vote down vote up
def next_power_of_two(n):
    """Return res for integer n such that 2^res>= n."""
    mantissa, res = math.frexp(n)
    if (mantissa == 0.5):
        res -= 1
    return res 
Example 39
Project: godot-zeronet-plugin   Author: zam-org   File: aifc.py    GNU General Public License v2.0 5 votes vote down vote up
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 or fmant != fmant: # 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_ushort(f, expon)
    _write_ulong(f, himant)
    _write_ulong(f, lomant) 
Example 40
Project: godot-zeronet-plugin   Author: zam-org   File: aifc.py    GNU General Public License v2.0 5 votes vote down vote up
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 or fmant != fmant: # 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_ushort(f, expon)
    _write_ulong(f, himant)
    _write_ulong(f, lomant) 
Example 41
Project: godot-zeronet-plugin   Author: zam-org   File: aifc.py    GNU General Public License v2.0 5 votes vote down vote up
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 or fmant != fmant: # 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_ushort(f, expon)
    _write_ulong(f, himant)
    _write_ulong(f, lomant) 
Example 42
Project: godot-zeronet-plugin   Author: zam-org   File: aifc.py    GNU General Public License v2.0 5 votes vote down vote up
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 or fmant != fmant: # 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_ushort(f, expon)
    _write_ulong(f, himant)
    _write_ulong(f, lomant) 
Example 43
Project: godot-zeronet-plugin   Author: zam-org   File: aifc.py    GNU General Public License v2.0 5 votes vote down vote up
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 or fmant != fmant: # 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_ushort(f, expon)
    _write_ulong(f, himant)
    _write_ulong(f, lomant) 
Example 44
Project: farc   Author: dwhall   File: __init__.py    MIT License 5 votes vote down vote up
def _insortTimeEvent(tm_event, expiration):
        """Inserts a TimeEvent into the list of time events,
        sorted by the next expiration of the timer.
        If the expiration time matches an existing expiration,
        we add the smallest amount of time to the given expiration
        to avoid a key collision in the Dict
        and make the identically-timed events fire in a FIFO fashion.
        """
        # If the event is to happen in the past, post it now
        now = Framework._event_loop.time()
        if expiration < now:
            tm_event.act.postFIFO(tm_event)
            # TODO: if periodic, need to schedule next?

        # If an event already occupies this expiration time,
        # increase this event's expiration by the smallest measurable amount
        while expiration in Framework._time_events.keys():
            m, e = math.frexp(expiration)
            expiration = (m + sys.float_info.epsilon) * 2**e
        Framework._time_events[expiration] = tm_event

        # If this is the only active TimeEvent, schedule its callback
        if len(Framework._time_events) == 1:
            Framework._tm_event_handle = Framework._event_loop.call_at(
                expiration, Framework.timeEventCallback, tm_event, expiration)

        # If there are other TimeEvents,
        # check if this one should replace the scheduled one
        else:
            if expiration < min(Framework._time_events.keys()):
                Framework._tm_event_handle.cancel()
                Framework._tm_event_handle = Framework._event_loop.call_at(
                    expiration, Framework.timeEventCallback, tm_event,
                    expiration) 
Example 45
Project: farc   Author: dwhall   File: __init__simple.py    MIT License 5 votes vote down vote up
def _insortTimeEvent(tm_event, expiration):
        """Inserts a TimeEvent into the list of time events,
        sorted by the next expiration of the timer.
        If the expiration time matches an existing expiration,
        we add the smallest amount of time to the given expiration
        to avoid a key collision in the Dict
        and make the identically-timed events fire in a FIFO fashion.
        """
        # If the event is to happen in the past, post it now
        now = Framework._event_loop.time()
        if expiration < now:
            tm_event.act.postFIFO(tm_event)
            # TODO: if periodic, need to schedule next?

        # If an event already occupies this expiration time,
        # increase this event's expiration by the smallest measurable amount
        while expiration in Framework._time_events.keys():
            m, e = math.frexp(expiration)
            expiration = (m + sys.float_info.epsilon) * 2**e
        Framework._time_events[expiration] = tm_event

        # If this is the only active TimeEvent, schedule its callback
        if len(Framework._time_events) == 1:
            Framework._tm_event_handle = Framework._event_loop.call_at(
                expiration, Framework.timeEventCallback, tm_event, expiration)

        # If there are other TimeEvents,
        # check if this one should replace the scheduled one
        else:
            if expiration < min(Framework._time_events.keys()):
                Framework._tm_event_handle.cancel()
                Framework._tm_event_handle = Framework._event_loop.call_at(
                    expiration, Framework.timeEventCallback, tm_event,
                    expiration) 
Example 46
Project: FATE   Author: FederatedAI   File: fixedpoint.py    Apache License 2.0 5 votes vote down vote up
def encode(cls, scalar, n=None, max_int=None, precision=None, max_exponent=None):
        """return an encoding of an int or float.
        """
        # Calculate the maximum exponent for desired precision
        exponent = None
        
        #  Too low value preprocess;
        #  avoid "OverflowError: int too large to convert to float"
        
        if np.abs(scalar) < 1e-200:
            scalar = 0
        
        if n is None:
            n = cls.Q
            max_int = cls.Q // 3 - 1    
                
        if precision is None:
            if isinstance(scalar, int) or isinstance(scalar, np.int16) or \
              isinstance(scalar, np.int32) or isinstance(scalar, np.int64):
                exponent = 0                                
            elif isinstance(scalar, float) or isinstance(scalar, np.float16)  \
                 or isinstance(scalar, np.float32) or isinstance(scalar, np.float64):               
                flt_exponent = math.frexp(scalar)[1]
                lsb_exponent = cls.FLOAT_MANTISSA_BITS - flt_exponent
                exponent = math.floor(lsb_exponent / cls.LOG2_BASE)
            else:
                raise TypeError("Don't know the precision of type %s."
                                % type(scalar))
        else:
            exponent = math.floor(math.log(precision, cls.BASE))        
        
        if max_exponent is not None:
            exponent = max(max_exponent, exponent)
            
        int_fixpoint = int(round(scalar * pow(cls.BASE, exponent)))

        if abs(int_fixpoint) > max_int:
            raise ValueError('Integer needs to be within +/- %d but got %d'
                             % (max_int, int_fixpoint))

        return cls(int_fixpoint % n, exponent, n, max_int) 
Example 47
Project: Python-iBeacon-Scan   Author: NikNitro   File: ctx_fp.py    GNU General Public License v3.0 5 votes vote down vote up
def mag(ctx, z):
        if z:
            return ctx.frexp(abs(z))[1]
        return ctx.ninf 
Example 48
Project: KalutClient   Author: TwoUnderscorez   File: aifc.py    Apache License 2.0 5 votes vote down vote up
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 or fmant != fmant: # 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_ushort(f, expon)
    _write_ulong(f, himant)
    _write_ulong(f, lomant) 
Example 49
Project: PyRival   Author: cheran-senthil   File: as_integer_ratio.py    Apache License 2.0 5 votes vote down vote up
def as_integer_ratio(x, prec=53):
    if x == 0:
        return 0, 1
    a, b = math.frexp(x)
    a = int(a * (1 << prec))
    g = (a & -a).bit_length() - 1
    a >>= g
    b += g - prec
    return (a << b, 1) if b > 0 else (a, 1 << -b) 
Example 50
Project: auto_tomo_calibration-experimental   Author: DiamondLightSource   File: umath.py    Apache License 2.0 5 votes vote down vote up
def frexp(x):
    """
    Version of frexp that works for numbers with uncertainty, and also
    for regular numbers.
    """

    # The code below is inspired by wrap().  It is
    # simpler because only 1 argument is given, and there is no
    # delegation to other functions involved (as for __mul__, etc.).

    aff_func = to_affine_scalar(x)

    if aff_func.derivatives:
        result = math.frexp(aff_func.nominal_value)
        # With frexp(x) = (m, e), dm/dx = 1/(2**e):
        factor = 1/(2**result[1])
        return (
            AffineScalarFunc(
                result[0],
                # Chain rule:
                dict((var, factor*deriv)
                     for (var, deriv) in aff_func.derivatives.iteritems())),
            # The exponent is an integer and is supposed to be
            # continuous (small errors):
            result[1])
    else:
        # This function was not called with an AffineScalarFunc
        # argument: there is no need to return numbers with uncertainties:
        return math.frexp(x) 
Example 51
Project: auto_tomo_calibration-experimental   Author: DiamondLightSource   File: umath.py    Apache License 2.0 5 votes vote down vote up
def frexp(x):
    """
    Version of frexp that works for numbers with uncertainty, and also
    for regular numbers.
    """

    # The code below is inspired by wrap().  It is
    # simpler because only 1 argument is given, and there is no
    # delegation to other functions involved (as for __mul__, etc.).

    aff_func = to_affine_scalar(x)

    if aff_func.derivatives:
        result = math.frexp(aff_func.nominal_value)
        # With frexp(x) = (m, e), dm/dx = 1/(2**e):
        factor = 1/(2**result[1])
        return (
            AffineScalarFunc(
                result[0],
                # Chain rule:
                dict((var, factor*deriv)
                     for (var, deriv) in aff_func.derivatives.iteritems())),
            # The exponent is an integer and is supposed to be
            # continuous (small errors):
            result[1])
    else:
        # This function was not called with an AffineScalarFunc
        # argument: there is no need to return numbers with uncertainties:
        return math.frexp(x) 
Example 52
Project: auto_tomo_calibration-experimental   Author: DiamondLightSource   File: umath.py    Apache License 2.0 5 votes vote down vote up
def frexp(x):
    """
    Version of frexp that works for numbers with uncertainty, and also
    for regular numbers.
    """

    # The code below is inspired by wrap().  It is
    # simpler because only 1 argument is given, and there is no
    # delegation to other functions involved (as for __mul__, etc.).

    aff_func = to_affine_scalar(x)

    if aff_func.derivatives:
        result = math.frexp(aff_func.nominal_value)
        # With frexp(x) = (m, e), dm/dx = 1/(2**e):
        factor = 1/(2**result[1])
        return (
            AffineScalarFunc(
                result[0],
                # Chain rule:
                dict((var, factor*deriv)
                     for (var, deriv) in aff_func.derivatives.iteritems())),
            # The exponent is an integer and is supposed to be
            # continuous (small errors):
            result[1])
    else:
        # This function was not called with an AffineScalarFunc
        # argument: there is no need to return numbers with uncertainties:
        return math.frexp(x) 
Example 53
Project: auto_tomo_calibration-experimental   Author: DiamondLightSource   File: umath.py    Apache License 2.0 5 votes vote down vote up
def frexp(x):
    """
    Version of frexp that works for numbers with uncertainty, and also
    for regular numbers.
    """

    # The code below is inspired by wrap().  It is
    # simpler because only 1 argument is given, and there is no
    # delegation to other functions involved (as for __mul__, etc.).

    aff_func = to_affine_scalar(x)

    if aff_func.derivatives:
        result = math.frexp(aff_func.nominal_value)
        # With frexp(x) = (m, e), dm/dx = 1/(2**e):
        factor = 1/(2**result[1])
        return (
            AffineScalarFunc(
                result[0],
                # Chain rule:
                dict((var, factor*deriv)
                     for (var, deriv) in aff_func.derivatives.iteritems())),
            # The exponent is an integer and is supposed to be
            # continuous (small errors):
            result[1])
    else:
        # This function was not called with an AffineScalarFunc
        # argument: there is no need to return numbers with uncertainties:
        return math.frexp(x) 
Example 54
Project: auto_tomo_calibration-experimental   Author: DiamondLightSource   File: umath.py    Apache License 2.0 5 votes vote down vote up
def frexp(x):
    """
    Version of frexp that works for numbers with uncertainty, and also
    for regular numbers.
    """

    # The code below is inspired by wrap().  It is
    # simpler because only 1 argument is given, and there is no
    # delegation to other functions involved (as for __mul__, etc.).

    aff_func = to_affine_scalar(x)

    if aff_func.derivatives:
        result = math.frexp(aff_func.nominal_value)
        # With frexp(x) = (m, e), dm/dx = 1/(2**e):
        factor = 1/(2**result[1])
        return (
            AffineScalarFunc(
                result[0],
                # Chain rule:
                dict((var, factor*deriv)
                     for (var, deriv) in aff_func.derivatives.iteritems())),
            # The exponent is an integer and is supposed to be
            # continuous (small errors):
            result[1])
    else:
        # This function was not called with an AffineScalarFunc
        # argument: there is no need to return numbers with uncertainties:
        return math.frexp(x) 
Example 55
Project: kinect-2-libras   Author: inessadl   File: aifc.py    Apache License 2.0 5 votes vote down vote up
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) 
Example 56
Project: Wallet   Author: superbitcoin   File: aifc.py    MIT License 5 votes vote down vote up
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 or fmant != fmant: # 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_ushort(f, expon)
    _write_ulong(f, himant)
    _write_ulong(f, lomant) 
Example 57
Project: MARA_Framework   Author: xtiankisutsa   File: ast.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
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 
Example 58
Project: MARA_Framework   Author: xtiankisutsa   File: floatutil.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def fromRawFloat(size, x):
    if math.isnan(x):
        return NAN
    sign = int(math.copysign(1, x))
    x = math.copysign(x, 1)

    if math.isinf(x):
        return sign, INF_MAG
    elif x == 0.0:
        return sign, ZERO_MAG
    else:
        m, e = math.frexp(x)
        m = int(m * (1<<(size[0]+1)))
        return sign, roundMag(size, (m, e)) 
Example 59
Project: Hot   Author: dsolimando   File: aifc.py    GNU General Public License v3.0 5 votes vote down vote up
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) 
Example 60
Project: Hot   Author: dsolimando   File: test_math_jy.py    GNU General Public License v3.0 5 votes vote down vote up
def test_frexp(self):
        self.assertEqual(math.frexp(inf), (inf, 0))
        mantissa, exponent = math.frexp(nan)
        self.assertNotEqual(mantissa, mantissa)
        self.assertEqual(exponent, 0) 
Example 61
Project: PyFlow   Author: wonderworks-software   File: MathLib.py    Apache License 2.0 5 votes vote down vote up
def frexp(x=('FloatPin', 0.0), m=(REF, ('FloatPin', 0.0)), e=(REF, ('IntPin', 0))):
        '''Return the mantissa and exponent of `x` as the pair (m, e). m is `x` float and e is an integer such that `x == m * 2**e` exactly.'''
        t = math.frexp(x)
        m(t[0])
        e(t[1]) 
Example 62
Project: PyFlow   Author: wonderworks-software   File: MathLib.py    Apache License 2.0 5 votes vote down vote up
def ldexp(x=('FloatPin', 0.0), i=('IntPin', 0)):
        '''Return `x * (2**i)`. This is essentially the inverse of function `frexp()`.'''
        return math.ldexp(x, i) 
Example 63
Project: linux-cross-gcc   Author: nmercier   File: aifc.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 or fmant != fmant: # 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_ushort(f, expon)
    _write_ulong(f, himant)
    _write_ulong(f, lomant) 
Example 64
Project: linux-cross-gcc   Author: nmercier   File: aifc.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 or fmant != fmant: # 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_ushort(f, expon)
    _write_ulong(f, himant)
    _write_ulong(f, lomant) 
Example 65
Project: m-stp   Author: MukeunKim   File: core.py    MIT License 5 votes vote down vote up
def frexp(x):
    if isinstance(x, LineValue): lx = x.get_value()
    else: lx = x
    if lx == NAN: return LineValue(NAN)
    return LineValue(math.frexp(lx)) 
Example 66
Project: DFTSerialize   Author: ThePlasmaRailgun   File: hello_world.py    GNU General Public License v3.0 5 votes vote down vote up
def f(p):
    if p < 1:
        return 1
    else:
        return p * f(p - 1) 
Example 67
Project: DFTSerialize   Author: ThePlasmaRailgun   File: hello_world.py    GNU General Public License v3.0 5 votes vote down vote up
def h(a, b):
    u, v = p(a)
    x, y = p(b)

    h, j = u * x, int(v + y)

    return q(h, j) 
Example 68
Project: DFTSerialize   Author: ThePlasmaRailgun   File: hello_world.py    GNU General Public License v3.0 5 votes vote down vote up
def k(p):
    q = b ** p[0]
    h, z = s(p[1])

    return h * q, z * q 
Example 69
Project: DFTSerialize   Author: ThePlasmaRailgun   File: raven.py    GNU General Public License v3.0 5 votes vote down vote up
def f(p):
    if p < 1:
        return 1
    else:
        return p * f(p - 1) 
Example 70
Project: DFTSerialize   Author: ThePlasmaRailgun   File: raven.py    GNU General Public License v3.0 5 votes vote down vote up
def h(a, b):
    u, v = p(a)
    x, y = p(b)

    h, j = u * x, int(v + y)

    return q(h, j) 
Example 71
Project: DFTSerialize   Author: ThePlasmaRailgun   File: deserialize.py    GNU General Public License v3.0 5 votes vote down vote up
def float_exp_mult(a, b):
    u, v = frexp(a)
    x, y = frexp(b)

    # Multiply mantissas (that's a weird name)
    # And add exponents (that one sounds a lot better)
    h, j = u * x, int(v + y)

    return ldexp(h, j)


# Fancy multiplication
# I think it uses that FOIL thing 
Example 72
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 73
Project: me-ica   Author: ME-ICA   File: ica_nodes.py    GNU Lesser General Public License v2.1 4 votes vote down vote up
def _stop_training(self):
        """Whiten data if needed and call the 'core' routine to perform ICA.
           Take care of telescope-mode if needed.
        """
        super(ICANode, self)._stop_training()

        verbose = self.verbose
        core = self.core
        limit = self.limit

        # ?? rewrite as a 2-phases node
        # whiten if needed
        if not self.whitened:
            self.output_dim = self.white_comp
            white = mdp.nodes.WhiteningNode(output_dim = self.white_comp,
                                            dtype=self.dtype,
                                            **self.white_parm)
            white.train(self.data)
            self.data = white.execute(self.data)
            self.white = white

        # if output_dim not set, set it now
        if self.output_dim is None:
            self.output_dim = self.input_dim

        data = self.data

        # call 'core' in telescope mode if needed
        if self.telescope:
            minpow = math.frexp(self.input_dim*10)[1]
            maxpow = int(numx.log(data.shape[0])/numx.log(2))
            for tel in range(minpow, maxpow+1):
                index = 2**tel
                if verbose:
                    print "--\nUsing %d inputs" % index
                convergence = core(data[:index, :])
                if convergence <= limit:
                    break
        else:
            convergence = core(data)
        if verbose:
            print "Convergence criterium: ", convergence
        self.convergence = convergence 
Example 74
Project: me-ica   Author: ME-ICA   File: ica_nodes_old.py    GNU Lesser General Public License v2.1 4 votes vote down vote up
def _stop_training(self):
        """Whiten data if needed and call the 'core' routine to perform ICA.
           Take care of telescope-mode if needed.
        """
        super(ICANode, self)._stop_training()

        verbose = self.verbose
        core = self.core
        limit = self.limit

        # ?? rewrite as a 2-phases node
        # whiten if needed
        if not self.whitened:
            self.output_dim = self.white_comp
            white = mdp.nodes.WhiteningNode(output_dim = self.white_comp,
                                            dtype=self.dtype,
                                            **self.white_parm)
            white.train(self.data)
            self.data = white.execute(self.data)
            self.white = white

        # if output_dim not set, set it now
        if self.output_dim is None:
            self.output_dim = self.input_dim

        data = self.data

        # call 'core' in telescope mode if needed
        if self.telescope:
            minpow = math.frexp(self.input_dim*10)[1]
            maxpow = int(numx.log(data.shape[0])/numx.log(2))
            for tel in range(minpow, maxpow+1):
                index = 2**tel
                if verbose:
                    print "--\nUsing %d inputs" % index
                convergence = core(data[:index, :])
                if convergence <= limit:
                    break
        else:
            convergence = core(data)
        if verbose:
            print "Convergence criterium: ", convergence
        self.convergence = convergence 
Example 75
Project: 2015cdb_g4   Author: 40223208   File: _struct.py    GNU General Public License v3.0 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 76
Project: data_algebra   Author: WinVector   File: SQLite.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def prepare_connection(self, conn):
        # https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.create_function
        conn.create_function("is_bad", 1, _check_scalar_bad)
        # math fns
        conn.create_function("acos", 1, math.acos)
        conn.create_function("acosh", 1, math.acosh)
        conn.create_function("asin", 1, math.asin)
        conn.create_function("asinh", 1, math.asinh)
        conn.create_function("atan", 1, math.atan)
        conn.create_function("atanh", 1, math.atanh)
        conn.create_function("ceil", 1, math.ceil)
        conn.create_function("cos", 1, math.cos)
        conn.create_function("cosh", 1, math.cosh)
        conn.create_function("degrees", 1, math.degrees)
        conn.create_function("erf", 1, math.erf)
        conn.create_function("erfc", 1, math.erfc)
        conn.create_function("exp", 1, math.exp)
        conn.create_function("expm1", 1, math.expm1)
        conn.create_function("fabs", 1, math.fabs)
        conn.create_function("factorial", 1, math.factorial)
        conn.create_function("floor", 1, math.floor)
        conn.create_function("frexp", 1, math.frexp)
        conn.create_function("gamma", 1, math.gamma)
        conn.create_function("isfinite", 1, math.isfinite)
        conn.create_function("isinf", 1, math.isinf)
        conn.create_function("isnan", 1, math.isnan)
        conn.create_function("lgamma", 1, math.lgamma)
        conn.create_function("log", 1, math.log)
        conn.create_function("log10", 1, math.log10)
        conn.create_function("log1p", 1, math.log1p)
        conn.create_function("log2", 1, math.log2)
        conn.create_function("modf", 1, math.modf)
        conn.create_function("radians", 1, math.radians)
        conn.create_function("sin", 1, math.sin)
        conn.create_function("sinh", 1, math.sinh)
        conn.create_function("sqrt", 1, math.sqrt)
        conn.create_function("tan", 1, math.tan)
        conn.create_function("tanh", 1, math.tanh)
        conn.create_function("trunc", 1, math.trunc)
        conn.create_function("atan2", 2, math.atan2)
        conn.create_function("copysign", 2, math.copysign)
        conn.create_function("fmod", 2, math.fmod)
        conn.create_function("gcd", 2, math.gcd)
        conn.create_function("hypot", 2, math.hypot)
        conn.create_function("isclose", 2, math.isclose)
        conn.create_function("ldexp", 2, math.ldexp)
        conn.create_function("pow", 2, math.pow) 
Example 77
Project: data_algebra   Author: WinVector   File: SQLite.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def prepare_connection(self, conn):
        # https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.create_function
        conn.create_function("is_bad", 1, _check_scalar_bad)
        # math fns
        conn.create_function("acos", 1, math.acos)
        conn.create_function("acosh", 1, math.acosh)
        conn.create_function("asin", 1, math.asin)
        conn.create_function("asinh", 1, math.asinh)
        conn.create_function("atan", 1, math.atan)
        conn.create_function("atanh", 1, math.atanh)
        conn.create_function("ceil", 1, math.ceil)
        conn.create_function("cos", 1, math.cos)
        conn.create_function("cosh", 1, math.cosh)
        conn.create_function("degrees", 1, math.degrees)
        conn.create_function("erf", 1, math.erf)
        conn.create_function("erfc", 1, math.erfc)
        conn.create_function("exp", 1, math.exp)
        conn.create_function("expm1", 1, math.expm1)
        conn.create_function("fabs", 1, math.fabs)
        conn.create_function("factorial", 1, math.factorial)
        conn.create_function("floor", 1, math.floor)
        conn.create_function("frexp", 1, math.frexp)
        conn.create_function("gamma", 1, math.gamma)
        conn.create_function("isfinite", 1, math.isfinite)
        conn.create_function("isinf", 1, math.isinf)
        conn.create_function("isnan", 1, math.isnan)
        conn.create_function("lgamma", 1, math.lgamma)
        conn.create_function("log", 1, math.log)
        conn.create_function("log10", 1, math.log10)
        conn.create_function("log1p", 1, math.log1p)
        conn.create_function("log2", 1, math.log2)
        conn.create_function("modf", 1, math.modf)
        conn.create_function("radians", 1, math.radians)
        conn.create_function("sin", 1, math.sin)
        conn.create_function("sinh", 1, math.sinh)
        conn.create_function("sqrt", 1, math.sqrt)
        conn.create_function("tan", 1, math.tan)
        conn.create_function("tanh", 1, math.tanh)
        conn.create_function("trunc", 1, math.trunc)
        conn.create_function("atan2", 2, math.atan2)
        conn.create_function("copysign", 2, math.copysign)
        conn.create_function("fmod", 2, math.fmod)
        conn.create_function("gcd", 2, math.gcd)
        conn.create_function("hypot", 2, math.hypot)
        conn.create_function("isclose", 2, math.isclose)
        conn.create_function("ldexp", 2, math.ldexp)
        conn.create_function("pow", 2, math.pow) 
Example 78
Project: 2015wcm   Author: coursemdetw   File: _struct.py    GNU Affero General Public License v3.0 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 79
Project: CgpDrweb   Author: delatars   File: CgpDrweb_AS_AV.py    MIT License 4 votes vote down vote up
def FILE(self, seqnum, arguments):
        """ Communigate Pro FILE command.
        http://www.communigate.com/CommuniGatePro/Helpers.html#Filters
        Server sends:
                seqNum FILE fileName

        Responses Format:
                seqNum [ modifiers ] OK

        available modifiers:
            - seqNum ADDHEADER header-field-text OK
            - seqNum MIRRORTO address OK
            - seqNum ADDROUTE address OK

        available responses:
            - seqNum ERROR report
            - seqNum DISCARD
            - seqNum REJECTED report
            - seqNum FAILURE
        """

        if arguments == []:
            print("Error: FILE command requires <parameter>.")
            return
        # arguments[0] = Queue/nnnnn.msg or Queue/01-09/nnnnn.msg

        Rspamd = RspamdHttpConnector(RSPAMD_SOCKET)
        # If CGP message parse it
        if re.match(r"^Queue/.*\.msg", arguments[0]):
            with open(os.path.join(CGP_PATH, arguments[0]), "rb") as msg:
                envelope, message = self._parse_cgp_message(msg)
                # add headers to HTTP request
                Rspamd.add_header("From", envelope["from"])
                Rspamd.add_header("Rcpt", envelope["rcpts"])
                Rspamd.add_header("Ip", envelope["ip"])
        # Condition for testing purposes
        else:
            with open(arguments[0], "rb") as msg:
                message = msg.read()

        # Check message and get a json result
        rspamd_result = Rspamd.check_message(message)
        # If rspamd can't check mail return OK response and print error to CGP log
        if rspamd_result.get("error", False):
            print(rspamd_result["error"])
            ServerSendResponse(seqnum, "OK")
            return
        # adding headers to message
        spam_score = rspamd_result.get("score", "error")
        junk_score = lambda score: "X" * (math.frexp(score)[1]-4)
        mandatory_headers = [
            "X-Spam-Score: %s" % spam_score,
            "X-Spam-Threshold: %s" % rspamd_result.get("required_score", "error"),
            "X-Junk-Score: %s" % junk_score(spam_score),
        ]
        optional_headers = self._return_optional_headers(rspamd_result)
        result_headers = mandatory_headers + optional_headers
        wrapped_headers = '\"' + "\e".join(result_headers) + '\"'
        ServerSendResponse(seqnum, "ADDHEADER", [wrapped_headers, "OK"]) 
Example 80
Project: fixedpointtest   Author: sixty-north   File: fixedpoint.py    MIT License 4 votes vote down vote up
def _from_float(cls, f):
        """Create a FixedPoint using a QFormat without loss of precision.

        Args:
            f (float): A float of which to create an equivalent FixedPoint representation.

        Returns:
            A FixedPoint object the QFormat for which will have sufficient precision to
            exactly represent the float.

        Raises:
            OverflowError: If f is NaN or infinite.
        """
        assert isinstance(f, Real)
        if isnan(f) or isinf(f):
            raise OverflowError("{} cannot be represented by {}".format(f, cls.__name__))

        # 1. Work out where the binary point is
        fr, exp = frexp(f)
        numerator = int(fr * (2**53))  # 53 binary places in the fraction
        binary_point_index = 53 - exp  # Is one based

        # 2. Work out how many significant figures there are to the left of the binary point; call this m
        most_significant_set_index = numerator.bit_length() - 1
        num_leading_bits = 1 + most_significant_set_index - binary_point_index
        m = max(num_leading_bits, 0) + 1  # One to accommodate sign

        # 3. Work out how many significant figures there are to the right of the binary point; call this n
        lowest_bit = lowest_set_bit(numerator)
        least_significant_set_index = lowest_bit.bit_length() - 1
        num_trailing_bits = binary_point_index - least_significant_set_index
        n = max(num_trailing_bits, 0)

        # 4. Make QFormat(m, n)
        qformat = QFormat(m, n)

        # 5. Shift the numerator to fit Qm.n
        #    We want the binary point to be at index n
        shift = binary_point_index - n
        shifted_numerator = signed_left_shift(numerator, shift)

        return cls._from_numerator(shifted_numerator, qformat)