Beispiel #1
0
def getInvertedBits( n ):
    value = real_int( n )

    # determine how many groups of bits we will be looking at
    if value == 0:
        groupings = 1
    else:
        groupings = int( fadd( floor( fdiv( ( log( value, 2 ) ), g.bitwiseGroupSize ) ), 1 ) )

    placeValue = mpmathify( 1 << g.bitwiseGroupSize )
    multiplier = mpmathify( 1 )
    remaining = value

    result = mpmathify( 0 )

    for i in range( 0, groupings ):
        # Let's let Python do the actual inverting
        group = fmod( ~int( fmod( remaining, placeValue ) ), placeValue )

        result += fmul( group, multiplier )

        remaining = floor( fdiv( remaining, placeValue ) )
        multiplier = fmul( multiplier, placeValue )

    return result
Beispiel #2
0
    def add(self, time):
        if not isinstance(time, RPNMeasurement):
            ValueError('RPNMeasurement expected')

        #print( 'time.getUnitName( )', time.getUnitName( ) )
        #print( 'g.unitOperators[ time.getUnitName( ) ].categories', g.unitOperators[ time.getUnitName( ) ].categories )

        if 'years' in g.unitOperators[time.getUnitName()].categories:
            years = time.convertValue('year')
            return self.replace(year=self.year + years)
        elif 'months' in g.unitOperators[time.getUnitName()].categories:
            months = time.convertValue('month')
            return self.incrementMonths(months)
        else:
            days = int(floor(time.convertValue('day')))
            seconds = int(fmod(floor(time.convertValue('second')), 86400))
            microseconds = int(
                fmod(floor(time.convertValue('microsecond')), 1000000))

            try:
                return self + datetime.timedelta(
                    days=days, seconds=seconds, microseconds=microseconds)
            except OverflowError:
                print(
                    'rpn:  value is out of range to be converted into a time')
                return nan
Beispiel #3
0
    def getModulo( self, other ):
        if isinstance( other, RPNMeasurement ):
            measurement = RPNMeasurement( self ).convert( other.units )
            measurement.value = fmod( measurement.value, other.value )

            return measurement.normalizeUnits( )
        else:
            return RPNMeasurement( fmod( self.value, other ), self.units ).normalizeUnits( )
Beispiel #4
0
    def getModulo(self, other):
        if isinstance(other, RPNMeasurement):
            measurement = RPNMeasurement(self).convert(other.units)
            measurement.value = fmod(measurement.value, other.value)

            return measurement.normalizeUnits()

        return RPNMeasurement(fmod(self.value, other),
                              self.units).normalizeUnits()
Beispiel #5
0
 def tupper(x: float, y: float) -> bool:
     """
     Calculates the Tupper's inequality in x and y
     :param x: horizontal shift
     :param y: vertical shift
     :return:
     """
     return 0.5 < mp.floor(
         mp.fmod(
             mp.floor(y / 17) *
             2**(-17 * mp.floor(x) - mp.fmod(mp.floor(y), 17)), 2))
Beispiel #6
0
def _crt( a, b, m, n ):
    d = getGCD( m, n )

    if fmod( fsub( a, b ), d ) != 0:
        return None

    x = floor( fdiv( m, d ) )
    y = floor( fdiv( n, d ) )
    z = floor( fdiv( fmul( m, n ), d ) )
    p, q, r = getExtendedGCD( x, y )

    return fmod( fadd( fprod( [ b, p, x ] ), fprod( [ a, q, y ] ) ), z )
Beispiel #7
0
def rotateDigitsRight(n, k):
    if k < 0:
        return rotateDigitsLeft(n, fneg(k))

    n = getMPFIntegerAsString(n)

    if k > len(n):
        fmod(k, len(n))

    rotate = int(k)

    n = n[-rotate:] + n[:-rotate]
    return mpmathify(n)
Beispiel #8
0
def getPowMod(a, b, c):
    '''
    Calculate (a ** y) % z efficiently.
    '''
    result = 1

    while b:
        if fmod(b, 2) == 1:
            result = fmod(fmul(result, a), c)

        b = floor(fdiv(b, 2))
        a = fmod(fmul(a, a), c)

    return result
Beispiel #9
0
def getShortOrdinalName(n):
    if n == 11:
        return '11th'

    if n == 12:
        return '12th'

    if n == 13:
        return '13th'

    modulo = int(fmod(n, 10))

    if modulo in [0, 4, 5, 6, 7, 8, 9]:
        result = str(int(n)) + 'th'
    elif modulo == 1:
        result = str(int(n)) + 'st'
    elif modulo == 2:
        result = str(int(n)) + 'nd'
    else:
        result = str(int(n)) + 'rd'

    length = len(result)
    offset = -5

    while offset > -length:
        result = result[:offset] + ',' + result[offset:]
        offset -= 4
        length += 1

    return result
Beispiel #10
0
def convertToBaseN( value, base, outputBaseDigits, numerals ):
    if outputBaseDigits:
        if ( base < 2 ):
            raise ValueError( 'base must be greater than 1' )
    else:
        if not ( 2 <= base <= len( numerals ) ):
            raise ValueError( 'base must be from 2 to {0}'.format( len( numerals ) ) )

    if value == 0:
        return 0

    if value < 0:
        return '-' + convertToBaseN( fneg( value ), base, outputBaseDigits, numerals )

    if base == 10:
        return str( value )

    if outputBaseDigits:
        result = [ ]
    else:
        result = ''

    leftDigits = mpmathify( value )

    while leftDigits > 0:
        modulo = fmod( leftDigits, base )

        if outputBaseDigits:
            result.insert( 0, int( modulo ) )
        else:
            result = numerals[ int( modulo ) ] + result

        leftDigits = floor( fdiv( leftDigits, base ) )

    return result
Beispiel #11
0
def getRoot( n, k ):
    if isinstance( n, RPNMeasurement ):
        if not isInteger( k ):
            raise ValueError( 'cannot take a fractional root of a measurement' )

        newUnits = RPNUnits( n.getUnits( ) )

        for unit, exponent in newUnits.items( ):
            if fmod( exponent, k ) != 0:
                if k == 2:
                    name = 'square'
                elif k == 3:
                    name = 'cube'
                else:
                    name = getOrdinalName( k )

                raise ValueError( 'cannot take the ' + name + ' root of this measurement: ', n.getUnits( ) ) #print measurement RPNMeasurement.getValue( ) )

            newUnits[ unit ] /= k

        value = root( n.getValue( ), k )

        return RPNMeasurement( value, newUnits )

    return root( n, k )
Beispiel #12
0
    def getRoot( self, operand ):
        if ( floor( operand ) != operand ):
            raise ValueError( 'cannot take a fractional root of a measurement' )

        newUnits = RPNUnits( self.units )

        for unit, exponent in newUnits.items( ):
            if fmod( exponent, operand ) != 0:
                if operand == 2:
                    name = 'square'
                elif operand == 3:
                    name = 'cube'
                else:
                    name = getOrdinalName( operand )

                baseUnits = self.convertToBaseUnits( )

                if ( baseUnits != self ):
                    return baseUnits.getRoot( operand )
                else:
                    raise ValueError( 'cannot take the ' + name + ' root of this measurement: ', self.units )

            newUnits[ unit ] /= operand

        value = root( self.value, operand )

        return RPNMeasurement( value, newUnits ).normalizeUnits( )
Beispiel #13
0
    def getRoot(self, operand):
        if floor(operand) != operand:
            raise ValueError('cannot take a fractional root of a measurement')

        newUnits = RPNUnits(self.units)

        for unit, exponent in newUnits.items():
            if fmod(exponent, operand) != 0:
                if operand == 2:
                    name = 'square'
                elif operand == 3:
                    name = 'cube'
                else:
                    # getOrdinalName( operand )
                    name = str(int(operand)) + 'th'

                baseUnits = self.convertToPrimitiveUnits()

                if baseUnits != self:
                    return baseUnits.getRoot(operand)

                raise ValueError(
                    'cannot take the ' + name + ' root of this measurement: ',
                    self.units)

            newUnits[unit] /= operand

        value = root(self.value, operand)

        return RPNMeasurement(value, newUnits).normalizeUnits()
Beispiel #14
0
def getModulo( n, k ):
    if isinstance( n, RPNMeasurement ):
        return n.getModulo( k )
    elif isinstance( k, RPNMeasurement ):
        raise ValueError( 'cannot take a non-measurement modulo a measurement' )
    else:
        return fmod( real( n ), real( k ) )
Beispiel #15
0
def getShortOrdinalName( n ):
    if n == 11:
        return '11th'
    elif n == 12:
        return '12th'
    elif n == 13:
        return '13th'

    modulo = int( fmod( n, 10 ) )

    if modulo in [ 0, 4, 5, 6, 7, 8, 9 ]:
        result = str( int( n ) ) + 'th'
    elif modulo == 1:
        result = str( int( n ) ) + 'st'
    elif modulo == 2:
        result = str( int( n ) ) + 'nd'
    else:
        result = str( int( n ) ) + 'rd'

    length = len( result )
    offset = -5

    while offset > -length:
        result = result[ : offset ] + ',' + result[ offset : ]
        offset -= 4
        length += 1

    return result
Beispiel #16
0
def getModuloOperator(n, k):
    if isinstance(n, RPNMeasurement):
        return n.getModulo(k)

    if isinstance(k, RPNMeasurement):
        raise ValueError('cannot take a non-measurement modulo a measurement')

    return fmod(n, k)
Beispiel #17
0
 def value(self,t,scurve=scurve_inf):
     n = self.node_number(t)
     angle_minus = self.node_angle(n)
     angle_plus = self.node_angle(n+1)
     wrap = self.wrap_number(n)
     offset = angle_plus-angle_minus+self._tau*wrap
     ratio = (t-n*self._period)/self._period
     value = scurve(ratio)*offset + angle_minus
     return mpmath.fmod(value,self._tau)
Beispiel #18
0
def splitNumber( value, base ):
    result = [ ]

    while value:
        digit = fmod( value, base )
        result.append( digit )
        value = fdiv( fsub( value, digit ), base )

    return result
Beispiel #19
0
def getNthGeneralizedPolygonalNumber(n, k):
    negative = (fmod(n, 2) == 0)

    n = floor(fdiv(fadd(n, 1), 2))

    if negative:
        n = fneg(n)

    return getNthPolygonalNumber(n, k)
Beispiel #20
0
    def adjust_polar_coordinate(self):
        #  This function adjusts the polar coordinate (phi, theta)  such that -pi/2 <= phi <= pi/2,
        #  and 0 <= theta < 2 pi, yet we get the same Cartesian coordinate.

        from mpmath import fmod, pi

        theta = fmod(self.theta, 2 * pi)

        modephi = fmod(self.phi, 2 * pi)

        if modephi <= pi / 2:
            self.phi = modephi
            self.theta = theta
        elif modephi <= 3 * pi / 2:
            self.phi = pi - modephi
            self.theta = fmod(theta - pi, 2 * pi)
        else:
            self.phi = modephi - 2 * pi
            self.theta = theta
Beispiel #21
0
    def add( self, time ):
        if not isinstance( time, RPNMeasurement ):
            ValueError( 'RPNMeasurement expected' )

        if 'years' in g.unitOperators[ time.getUnitString( ) ].categories:
            years = convertUnits( time, 'year' ).getValue( )
            return self.replace( year = self.year + years )
        elif 'months' in g.unitOperators[ time.getUnitString( ) ].categories:
            months = convertUnits( time, 'month' ).getValue( )
            return self.incrementMonths( months )
        else:
            days = int( floor( convertUnits( time, 'day' ).getValue( ) ) )
            seconds = int( fmod( floor( convertUnits( time, 'second' ).getValue( ) ), 86400 ) )
            microseconds = int( fmod( floor( convertUnits( time, 'microsecond' ).getValue( ) ), 1000000 ) )

            try:
                return self + datetime.timedelta( days = days, seconds = seconds, microseconds = microseconds )
            except OverflowError:
                print( 'rpn:  value is out of range to be converted into a time' )
                return nan
Beispiel #22
0
def convertToSignedInt(n, k):
    newPrecision = (int(k) * 3 / 10) + 3

    if mp.dps < newPrecision:
        setAccuracy(newPrecision)

    value = fadd(n, (power(2, fsub(k, 1))))
    value = fmod(value, power(2, k))
    value = fsub(value, (power(2, fsub(k, 1))))

    return value
Beispiel #23
0
def isStrongPseudoprime( n, k ):
    if n < k or fmod( n, 2 ) == 0 or isPrime( n ):
        return 0

    d = int( n - 1 )
    s = 0

    while d % 2 == 0:
        d >>= 1
        s += 1

    return 1 if miller_rabin_pass( int( k ), s, d, int( n ) ) else 0
Beispiel #24
0
def getNthGeneralizedPolygonalNumber( n, k ):
    if real_int( k ) < 3:
        raise ValueError( 'the number of sides of the polygon cannot be less than 3,' )

    negative = ( fmod( n, 2 ) == 0 )

    n = floor( fdiv( fadd( n, 1 ), 2 ) )

    if negative:
        n = fneg( n )

    return getNthPolygonalNumber( n, k )
Beispiel #25
0
def performBitwiseOperation(i, j, operation):
    value1 = int(i)
    value2 = int(j)

    # determine how many groups of bits we will be looking at
    if value1 == 0:
        groupings = 1
    else:
        groupings = int(
            fadd(floor(fdiv((log(value1, 2)), g.bitwiseGroupSize)), 1))

    if value2 == 0:
        groupings2 = 1
    else:
        groupings2 = int(
            fadd(floor(fdiv((log(value2, 2)), g.bitwiseGroupSize)), 1))

    if groupings2 > groupings:
        groupings = groupings2

    placeValue = mpmathify(1 << g.bitwiseGroupSize)
    multiplier = mpmathify(1)
    remaining1 = value1
    remaining2 = value2

    result = mpmathify(0)

    for _ in range(0, groupings):
        mod1 = fmod(remaining1, placeValue)
        mod2 = fmod(remaining2, placeValue)

        result = fadd(fmul(operation(int(mod1), int(mod2)), multiplier),
                      result)

        remaining1 = floor(fdiv(remaining1, placeValue))
        remaining2 = floor(fdiv(remaining2, placeValue))

        multiplier = fmul(multiplier, placeValue)

    return result
Beispiel #26
0
def sample(masses):
    """
    Sample an element i of {0, 1, ..., n-1} with probability proportional to
    masses[i]

    """
    # get the most sensitive mass for the precision, and add some more digits for accuracy
    # fmod is from mpmath, the fractional part
    # notice that sometimes the list in the maximum might be empty, so we add a 0 just in case
    prec = max([abs(log(fmod(mass, 1), 10)) for mass in masses if fmod(mass, 1) != 0.0] + [0]) + 10
    # HERE WE RESCALE THE MASSES
    scaled_masses = [mass*(10**prec) for mass in masses]
    sums = []
    cur = 0
    for i in xrange(len(masses)):
        cur += scaled_masses[i]
        sums.append(cur)
    total_mass = sums[-1]
    rand = randrange(int(total_mass))
    for i in xrange(len(masses)):
        if rand < sums[i]:
            return i
    return len(masses) - 1
Beispiel #27
0
def getInvertedBits(n):
    # determine how many groups of bits we will be looking at
    if n == 0:
        groupings = 1
    else:
        groupings = int(fadd(floor(fdiv((log(n, 2)), g.bitwiseGroupSize)), 1))

    placeValue = mpmathify(1 << g.bitwiseGroupSize)
    multiplier = mpmathify(1)
    remaining = n

    result = mpmathify(0)

    for _ in range(0, groupings):
        # Let's let Python do the actual inverting
        group = fmod(~int(fmod(remaining, placeValue)), placeValue)

        result += fmul(group, multiplier)

        remaining = floor(fdiv(remaining, placeValue))
        multiplier = fmul(multiplier, placeValue)

    return result
Beispiel #28
0
def performBitwiseOperation( i, j, operation ):
    value1 = real_int( i )
    value2 = real_int( j )

    # determine how many groups of bits we will be looking at
    if value1 == 0:
        groupings = 1
    else:
        groupings = int( fadd( floor( fdiv( ( log( value1, 2 ) ), g.bitwiseGroupSize ) ), 1 ) )

    if value2 == 0:
        groupings2 = 1
    else:
        groupings2 = int( fadd( floor( fdiv( ( log( value2, 2 ) ), g.bitwiseGroupSize ) ), 1 ) )

    if groupings2 > groupings:
        groupings = groupings2

    placeValue = mpmathify( 1 << g.bitwiseGroupSize )
    multiplier = mpmathify( 1 )
    remaining1 = value1
    remaining2 = value2

    result = mpmathify( 0 )

    for i in range( 0, groupings ):
        mod1 = fmod( remaining1, placeValue )
        mod2 = fmod( remaining2, placeValue )

        result = fadd( fmul( operation( int( mod1 ), int( mod2 ) ), multiplier ), result )

        remaining1 = floor( fdiv( remaining1, placeValue ) )
        remaining2 = floor( fdiv( remaining2, placeValue ) )

        multiplier = fmul( multiplier, placeValue )

    return result
Beispiel #29
0
def makePythagoreanQuadruple( a, b ):
    if a < 0 or b < 0:
        raise ValueError( "'make_pyth_4' requires positive arguments" )

    # if a == b:
    #     raise ValueError( "'make_pyth_4' requires unequal arguments" )

    odd1 = ( fmod( a, 2 ) == 1 )
    odd2 = ( fmod( b, 2 ) == 1 )

    if odd1 and odd2:
        raise ValueError( "'make_pyth_4' arguments cannot both be odd" )

    result = [ a, b ]

    sumsqr = fadd( fmul( a, a ), fmul( b, b ) )

    div = getDivisors( sumsqr )

    if odd1 != odd2:
        if len( div ) <= 3:
            p = 1
        else:
            p = random.choice( div[ : ( len( div ) - 1 ) // 2 ] )
    else:
        if ( fmod( sumsqr, 2 ) == 1 ):
            raise ValueError( "'make_pyth_4' oops, can't make one!" )
        else:
            div = [ i for i in div[ : ( len( div ) - 1 ) // 2 ] if fmod( sumsqr, fmul( i, 2 ) ) == 0 and fmod( i, 2 ) == 0 ]
            p = random.choice( div )

    psqr = fmul( p, p )
    result.append( fdiv( fsub( sumsqr, psqr ), fmul( p, 2 ) ) )
    result.append( fdiv( fadd( sumsqr, psqr ), fmul( p, 2 ) ) )

    return sorted( result )
Beispiel #30
0
def convertToBaseN(value,
                   base,
                   outputBaseDigits=False,
                   numerals=g.defaultNumerals):
    '''
    This handles any integer base as long as there is a big-enough list of
    numerals to use.  In practice this ends up being 0-9, a-z, and A-Z, which
    allows us to support up to base 62.
    '''
    if outputBaseDigits:
        if base < 2:
            raise ValueError('base must be greater than 1')

        if value < 0:
            raise ValueError(
                '\'get_base_k_digits\' does not support negative numbers.')
    else:
        if not 2 <= base <= len(numerals):
            raise ValueError('base must be from 2 to {0}'.format(
                len(numerals)))

    if value == 0:
        return 0

    if value < 0:
        return '-' + convertToBaseN(fneg(value), base, outputBaseDigits,
                                    numerals)

    if outputBaseDigits:
        result = []
    else:
        result = ''

    leftDigits = mpmathify(value)

    while leftDigits > 0:
        modulo = fmod(leftDigits, base)

        if outputBaseDigits:
            result.insert(0, int(modulo))
        else:
            result = numerals[int(modulo)] + result

        leftDigits = floor(fdiv(leftDigits, base))

    return result
Beispiel #31
0
def getBitCount( n ):
    n = real_int( n )

    if real_int( n ) < 0:
        raise ValueError( '\'bit_count\' requires a positive integer value' )

    result = 0

    if isinstance( n, RPNMeasurement ):
        value = n.value
    else:
        value = n

    while ( value ):
        result += fmod( value, 2 )
        value = floor( fdiv( value, 2 ) )

    return result
Beispiel #32
0
def getExtendedGCD( a, b ):
    '''
    Euclid's Extended GCD Algorithm

    >>> xgcd(314159265, 271828186)
    (-18013273, 20818432, 7)
    '''
    u, u1 = 1, 0
    v, v1 = 0, 1

    while b != 0:
        q = floor( fdiv( a, b ) )
        r = fmod( a, b )
        a, b = b, r
        u, u1 = u1, fsub( u, fmul( q, u1 ) )
        v, v1 = v1, fsub( v, fmul( q, v1 ) )

    return ( u, v, a ) if a > 0 else ( -u, -v, -a )
Beispiel #33
0
def getBitCount(n):
    n = int(n)

    if n < 0:
        raise ValueError('\'bit_count\' requires a positive integer value')

    result = 0

    if isinstance(n, RPNMeasurement):
        value = n.value
    else:
        value = n

    while value:
        result += fmod(value, 2)
        value = floor(fdiv(value, 2))

    return result
Beispiel #34
0
def factorByTrialDivision( n ):
    if n > g.maxToFactorByTrialDivision:
        raise ValueError( 'value', n, 'is too big to factor by trial division' )

    result = [ ]

    for i in primes:
        while n > 1 and fmod( n, i ) == 0:
            n = fdiv( n, i )
            result.append( i )

        if isPrimeNumber( n ):
            break

    if n > 1:
        result.append( int( n ) )

    return result
Beispiel #35
0
def factorByTrialDivision(n):
    if n > g.maxToFactorByTrialDivision:
        raise ValueError('value', n, 'is too big to factor by trial division')

    result = []

    for i in primes:
        while n > 1 and fmod(n, i) == 0:
            n = fdiv(n, i)
            result.append(i)

        if isPrime(n):
            break

    if n > 1:
        result.append(int(n))

    return result
Beispiel #36
0
def cafeize(input_str: str) -> str:
    input_str = input_str.strip().lower()
    a, oper, b = input_str.split(" ")

    a = decrypt(a)
    b = decrypt(b)

    result = None
    if oper == "+":
        result = a + b
    elif oper == "-":
        result = a - b
    elif oper == "/":
        result = a / b
    elif oper == "*":
        result = a * b
    elif oper == "mod":
        result = mpmath.fmod(a, b)

    print(f"{a} {oper} {b} = {result}")
    result_str = encrypt(result)
    return result_str
Beispiel #37
0
def getInvertedBits( n ):
    value = real_int( n )

    # determine how many groups of bits we will be looking at
    if value == 0:
        groupings = 1
    else:
        groupings = int( fadd( floor( fdiv( ( log( value, 2 ) ), g.bitwiseGroupSize ) ), 1 ) )

    placeValue = mpmathify( 1 << g.bitwiseGroupSize )
    multiplier = mpmathify( 1 )
    remaining = value

    result = mpmathify( 0 )

    for i in range( 0, groupings ):
        result = fadd( fmul( fsum( [ placeValue,
                                     fneg( fmod( remaining, placeValue ) ), -1 ] ),
                             multiplier ), result )
        remaining = floor( fdiv( remaining, placeValue ) )
        multiplier = fmul( multiplier, placeValue )

    return result
Beispiel #38
0
def getGCD( a, b = 0 ):
    if real( b ) == 0:
        a = list( a )
    else:
        a, b = fabs( a ), fabs( b )

        while a:
            b, a = a, fmod( b, a )

        return b

    if isinstance( a[ 0 ], ( list, RPNGenerator ) ):
        return [ getGCD( real( arg ) ) for arg in a ]
    else:
        result = max( a )

        for pair in itertools.combinations( a, 2 ):
            gcd = getGCD( *pair )

            if gcd < result:
                result = gcd

        return result
Beispiel #39
0
def convertToBaseN( value, base, outputBaseDigits=False, numerals=g.defaultNumerals ):
    '''
    This handles any integer base as long as there is a big-enough list of
    numerals to use.  In practice this ends up being 0-9, a-z, and A-Z, which
    allows us to support up to base 62.
    '''
    if outputBaseDigits:
        if ( base < 2 ):
            raise ValueError( 'base must be greater than 1' )
    else:
        if not ( 2 <= base <= len( numerals ) ):
            raise ValueError( 'base must be from 2 to {0}'.format( len( numerals ) ) )

    if value == 0:
        return 0

    if value < 0:
        return '-' + convertToBaseN( fneg( value ), base, outputBaseDigits, numerals )

    if outputBaseDigits:
        result = [ ]
    else:
        result = ''

    leftDigits = mpmathify( value )

    while leftDigits > 0:
        modulo = fmod( leftDigits, base )

        if outputBaseDigits:
            result.insert( 0, int( modulo ) )
        else:
            result = numerals[ int( modulo ) ] + result

        leftDigits = floor( fdiv( leftDigits, base ) )

    return result
Beispiel #40
0
def getMantissaOperator(n):
    return fmod(fabs(n), 1)
Beispiel #41
0
def getNumberName( n, ordinal = False ):
    units = ''

    if isinstance( n, RPNMeasurement ):
        value = n.value

        if value == 1 or value == -1:
            units = n.getUnitName( )
        else:
            units = n.getPluralUnitName( )

        n = real_int( value )

    if n == 0:
        if ordinal:
            name = 'zeroth'
        else:
            name = 'zero'

        if units:
            name += ' '
            name += units

        return name

    current = fabs( n )

    if current >= power( 10, 3003 ):
        raise ValueError( 'value out of range for converting to an English name' )

    group = 0
    name = ''

    firstTime = True

    while current > 0:
        section = getSmallNumberName( int( fmod( current, 1000 ) ), ordinal if firstTime else False )

        firstTime = False

        if section != '':
            groupName = getNumberGroupName( group )

            if groupName != '':
                section += ' ' + groupName

                if ordinal and name == '':
                    section += 'th'

            if name == '':
                name = section
            else:
                name = section + ' ' + name

        current = floor( fdiv( current, 1000 ) )
        group += 1

    if n < 0:
        name = 'negative ' + name

    if units:
        name += ' '
        name += units

    return name
Beispiel #42
0
def isOdd(n):
    return 1 if fmod(n, 2) == 1 else 0
Beispiel #43
0
def duplicateDigitsOperator(n, k):
    return appendDigits(n, fmod(n, power(10, nint(floor(k)))), k)
Beispiel #44
0
def getMantissa( n ):
    return fmod( real( n ), 1 )
Beispiel #45
0
def getGCD( n, k ):
    while k:
        n, k = k, fmod( n, k )

    return n
Beispiel #46
0
def isInteger(n):
    return 1 if fmod(n, 1) == 0 else 0
Beispiel #47
0
def isInteger( n ):
    return 1 if fmod( real( n ), 1 ) == 0 else 0
Beispiel #48
0
def isDivisible( n, k ):
    return 1 if fmod( real( n ), real( k ) ) == 0 else 0
Beispiel #49
0
def isEven(n):
    return 1 if fmod(n, 2) == 0 else 0
Beispiel #50
0
def isDivisible(n, k):
    if n == 0:
        return 1

    return 1 if (n >= k) and (fmod(n, k) == 0) else 0
Beispiel #51
0
def convertToSignedInt( n, k ):
    value = fadd( real_int( n ), ( power( 2, fsub( real_int( k ), 1 ) ) ) )
    value = fmod( value, power( 2, k ) )
    value = fsub( value, ( power( 2, fsub( k, 1 ) ) ) )

    return value
Beispiel #52
0
def hash_string_to_float(arg):
    x = mpf(hash_string_to_int(arg))
    return fmod(x * mp.pi, mpf(1.0))
Beispiel #53
0
def color():
    global red, green, blue
    red = int(mpmath.fdiv(mpmath.re(a[listindex]), 256))
    green = int(mpmath.fmod(mpmath.re(a[listindex]), 256))
    blue = int(mpmath.fmod(mpmath.im(a[listindex]), 256))
Beispiel #54
0
def isEven( n ):
    return 1 if fmod( real_int( n ), 2 ) == 0 else 0
Beispiel #55
0
def getNumberName(n, ordinal=False):
    units = ''

    if isinstance(n, RPNMeasurement):
        value = n.value

        if value in [1, -1]:
            units = n.getUnitName()
        else:
            units = n.getPluralUnitName()

        n = value

    if n == 0:
        if ordinal:
            name = 'zeroth'
        else:
            name = 'zero'

        if units:
            name += ' '
            name += units

        return name

    current = fabs(n)

    if current >= power(10, 3003):
        raise ValueError(
            'value out of range for converting to an English name')

    group = 0
    name = ''

    firstTime = True

    while current > 0:
        section = getSmallNumberName(int(fmod(current, 1000)),
                                     ordinal if firstTime else False)

        firstTime = False

        if section != '':
            groupName = getNumberGroupName(group)

            if groupName != '':
                section += ' ' + groupName

                if ordinal and name == '':
                    section += 'th'

            if name == '':
                name = section
            else:
                name = section + ' ' + name

        current = floor(fdiv(current, 1000))
        group += 1

    if n < 0:
        name = 'negative ' + name

    if units:
        name += ' '
        name += units

    return name
Beispiel #56
0
def isOdd( n ):
    return 1 if fmod( real_int( n ), 2 ) == 1 else 0
Beispiel #57
0
#Python Programm to check your enter number is odd or even

import mpmath
print("This program checking your enter number is odd or even")
number = input("Please enter your number:")
number = int(number)
if mpmath.fmod(number, 2):
    print("Your number is {0} and it's odd".format(number))
else:
    print("Your number is {0} and it's even".format(number))
Beispiel #58
0
def getRightDigitsOperator(n, k):
    return fmod(n, pow(10, k))
Beispiel #59
0
def getNthThueMorse( n ):
    if n == 0:
        return 0
    else:
        return fmod( fadd( n, getNthThueMorse( floor( fdiv( n, 2 ) ) ) ), 2 )
import math
import mpmath as mp
M = 1000000007
def fibSum(n):    
    if n == 0 or n == 1:
        return 0
    elif n == 2:
        return 1
    else:
        n = n+1
        a = math.sqrt(5) ; b =1+a ; c = 1-a
        e = (mp.power(b,n)-mp.power(c,n))/(mp.power(2,n)*a)
        return e-1

n = int(raw_input().strip())
while n>0:
    l,r = map(long,raw_input().strip().split(' '))
    s1 = fibSum(l-1)
    s2 = fibSum(r)
    s = mp.fmod((s2-s1),10000)
    print('%.f' %(mp.fmod(s,M)))
    n-=1