Ejemplo n.º 1
0
def p(L, n):

    C = mp.log10(2)
    po = mp.mp.power(10, mp.floor(mp.log10(L)))
    C1 = mp.log10(mp.mpf(L) / po)
    C2 = mp.log10(mp.mpf(L + 1) / po)
    k = 1

    while not (C1 <= mp.frac(k * C) < C2):
        k += 1
        auxi = lambda k: mp.frac(k * C) - C1

    approximators = add_approximators(1000, C)
    curr = (k, auxi(k))
    treshold = mp.log10(mp.mpf(L + 1) / mp.mpf(L))
    idx = 1
    while idx < n:
        for el in approximators:
            if 0 <= curr[1] + el[1] < treshold:

                curr = (curr[0] + el[0], auxi(curr[0] + el[0]))
                idx += 1
                #print(curr[0], idx)
                break
    return curr[0]
def verige(num, denominator_limit):
    Z = num
    C = []
    P = []
    Q = []

    C.append(int(mp.floor(num)))
    Z = mp.fdiv(1, mp.frac(Z))
    C.append(int(mp.floor(Z)))

    P.append(C[0])
    P.append(C[0] * C[1] + 1)
    Q.append(1)
    Q.append(C[1])

    for k in range(2, 1000000):
        Z = mp.fdiv(1, mp.frac(Z))
        C.append(int(mp.floor(Z)))

        if Q[-1] > denominator_limit:
            break

        P.append(C[k] * P[k - 1] + P[k - 2])
        Q.append(C[k] * Q[k - 1] + Q[k - 2])

    return C, P, Q
Ejemplo n.º 3
0
    def forbidden_index_search(self, x, q):
        with workdps(self.dps):
            x_big = [mpf(el) * self.gamma**self.k for el in x]
            eps = mpf('1') / (self.gamma - 1)
            intervals = mp.linspace(mpf('0'), mpf('1'), self.gamma)
            length = mpf('1.0') * (self.gamma - 2) / (self.gamma - 1)

            x_big_frac = [mp.frac(el) for el in x_big]
            ineq = [mp.frac(el + q*eps) <= length for el in x_big_frac]

            # Determine i-s
            ord_val = eps * q * self.gamma**self.k
            mod_val = ord_val - length

            indices = [int(mp.floor(el + ord_val)) if ineq[i] else int(mp.floor(el + mod_val)) for i, el in enumerate(x_big)]
            multipliers = [1]*len(x_big)

            for i in xrange(len(x_big)):
                if not ineq[i]:
                    indices[i] = [indices[i], indices[i] + 1]
                    #multipliers[i] = [mpf('0.5'), mpf('0.5')]
                    multipliers[i] = [(indices[i][0] + eps - (x_big[i] + mod_val))/eps, (x_big[i] + mod_val - indices[i][0])/eps]

            # Now we have indices, where indices[i] may be number, or a pair of numbers (if x[i] lay between intervals)
            return indices, multipliers
Ejemplo n.º 4
0
def decompose(x, gamma_pow, precision=40):
    with mp.workdps(2048):
        tail = x
        compressed = np.zeros(precision + 1)
        for i in xrange(precision + 1):
            if tail == 0:
                break
            tail, compressed[i] = mp.frac(tail), mp.floor(tail)
            tail = mp.ldexp(tail, gamma_pow)
        return compressed
Ejemplo n.º 5
0
    def convertUnitList(self, other):
        if not isinstance(other, list):
            raise ValueError('convertUnitList expects a list argument')

        result = []

        nonIntegral = False

        for i in range(1, len(other)):
            conversion = g.unitConversionMatrix[(other[i - 1].getUnitName(),
                                                 other[i].getUnitName())]

            if conversion != floor(conversion):
                nonIntegral = True

        if nonIntegral:
            source = self

            for count, measurement in enumerate(other):
                with extradps(2):
                    conversion = source.convertValue(measurement)

                    if count < len(other) - 1:
                        result.append(
                            RPNMeasurement(floor(conversion),
                                           measurement.units))
                        source = RPNMeasurement(chop(frac(conversion)),
                                                measurement.units)
                    else:
                        result.append(
                            RPNMeasurement(conversion, measurement.units))

            return result
        else:
            source = self.convert(other[-2])

            with extradps(2):
                result.append(source.getModulo(other[-2]).convert(other[-1]))

            source = source.subtract(result[-1])

            for i in range(len(other) - 2, 0, -1):
                source = source.convert(other[i - 1])

                with extradps(2):
                    result.append(
                        source.getModulo(other[i - 1]).convert(other[i]))

                source = source.subtract(result[-1])

            result.append(source)

            return result[::-1]
Ejemplo n.º 6
0
    def convertUnitList( self, other ):
        if not isinstance( other, list ):
            raise ValueError( 'convertUnitList expects a list argument' )

        result = [ ]

        nonIntegral = False

        for i in range( 1, len( other ) ):
            conversion = g.unitConversionMatrix[ ( other[ i - 1 ].getUnitName( ), other[ i ].getUnitName( ) ) ]

            if conversion != floor( conversion ):
                nonIntegral = True

        if nonIntegral:
            source = self

            for count, measurement in enumerate( other ):
                with extradps( 2 ):
                    conversion = source.convertValue( measurement )

                    if count < len( other ) - 1:
                        result.append( RPNMeasurement( floor( conversion ), measurement.units ) )
                        source = RPNMeasurement( chop( frac( conversion ) ), measurement.units )
                    else:
                        result.append( RPNMeasurement( conversion, measurement.units ) )

            return result
        else:
            source = self.convert( other[ -2 ] )

            with extradps( 2 ):
                result.append( source.getModulo( other[ -2 ] ).convert( other[ -1 ] ) )

            source = source.subtract( result[ -1 ] )

            for i in range( len( other ) - 2, 0, -1 ):
                source = source.convert( other[ i - 1 ] )

                with extradps( 2 ):
                    result.append( source.getModulo( other[ i - 1 ] ).convert( other[ i ] ) )

                source = source.subtract( result[ -1 ] )

            result.append( source )

            return result[ : : -1 ]
Ejemplo n.º 7
0
    def index_search(self, x):
        with workdps(self.dps):
            def q_estimate_from_many(ns):
                qs_mask = np.ones(2 * self.N + 1, dtype=np.bool)
                for n in ns:
                    if n != self.gamma - 2 and n >= self.gamma - 2 - 2*self.N:
                        qs_mask[self.gamma - 2 - n] = False
                return qs_mask

            x_big = [mpf(el) * self.gamma**self.k for el in x]
            eps = mpf('1') / (self.gamma - 1)
            intervals = mp.linspace(mpf('0'), mpf('1'), self.gamma)

            x_big_frac = [mp.frac(el) for el in x_big]
            numbers_of_intervals = [mp.floor(el / eps) for el in x_big_frac]

            qs_mask = q_estimate_from_many(numbers_of_intervals)
            #print qs
            qs = np.array(range(2 * self.N + 1))[qs_mask]
            return [([mp.floor(el + eps * q * self.gamma**self.k) for el in x_big], q) for q in qs], qs_mask
Ejemplo n.º 8
0
def add_approximators(N, C):
    '''
    This function will add all approximators with denominator less than N
    and that are coprime with its numerator 
    '''

    approximators = []

    treshold = mp.log10(mp.mpf(124) / mp.mpf(123))
    for i in range(10, N):
        chute = mp.floor(i * C)

        if mp.absmax(chute / i - C) >= mp.absmax((chute + 1) / i - C):
            chute += 1

        if mcd(chute, i) == 1:
            val = mp.frac(i * C)
            if val < treshold:
                approximators.append((i, val))
            elif val > 1 - treshold:
                approximators.append((i, val - 1))

    return approximators
Ejemplo n.º 9
0
 def _frac(num):
     return mp.frac(num)
Ejemplo n.º 10
0
def formatNumber( number, outputRadix, leadingZero, integerGrouping, integerDelimiter, decimalDelimiter ):
    negative = ( number < 0 )

    if outputRadix == g.fibBase:
        strInteger = convertToFibBase( floor( number ) )
        strMantissa = ''
    elif outputRadix == g.phiBase:
        strInteger, strMantissa = convertToNonintegerBase( number, phi )
    elif outputRadix == g.eBase:
        strInteger, strMantissa = convertToNonintegerBase( number, e )
    elif outputRadix == g.piBase:
        strInteger, strMantissa = convertToNonintegerBase( number, pi )
    elif outputRadix == g.sqrt2Base:
        strInteger, strMantissa = convertToNonintegerBase( number, sqrt( 2 ) )
    elif outputRadix < 0:   # these mean special bases, not negative numbers
        strInteger = convertToSpecialBase( floor( number ), specialBaseFunctions[ outputRadix ] )
        strMantissa = ''
    elif ( outputRadix != 10 ) or ( g.numerals != g.defaultNumerals ):
        strInteger = str( convertToBaseN( floor( number ), outputRadix, False, g.numerals ) )
        strMantissa = str( convertFractionToBaseN( frac( number ), outputRadix,
                                                   int( mp.dps / math.log10( outputRadix ) ), False ) )
        if strMantissa == '[]':
            strMantissa = ''
    else:
        strNumber = nstr( number, n=g.outputAccuracy, min_fixed=-g.maximumFixed - 1 )

        if '.' in strNumber:
            decimal = strNumber.find( '.' )
        else:
            decimal = len( strNumber )

        strInteger = strNumber[ 1 if negative else 0 : decimal ]

        strMantissa = strNumber[ decimal + 1 : ]

        if strMantissa == '0':
            strMantissa = ''
        elif ( strMantissa != '' ) and ( g.outputAccuracy == -1 ):
            strMantissa = strMantissa.rstrip( '0' )

    if integerGrouping > 0:
        if strInteger[ 0 ] == '-':
            strInteger = strInteger[ 1 : ]

        firstDelimiter = len( strInteger ) % integerGrouping

        if leadingZero and firstDelimiter > 0:
            integerResult = '0' * ( integerGrouping - firstDelimiter )
        else:
            integerResult = ''

        integerResult += strInteger[ : firstDelimiter ]

        for i in range( firstDelimiter, len( strInteger ), integerGrouping ):
            if integerResult != '':
                integerResult += integerDelimiter

            integerResult += strInteger[ i : i + integerGrouping ]
    else:
        integerResult = strInteger

    if g.decimalGrouping > 0:
        mantissaResult = ''

        for i in range( 0, len( strMantissa ), g.decimalGrouping ):
            if mantissaResult != '':
                mantissaResult += decimalDelimiter

            mantissaResult += strMantissa[ i : i + g.decimalGrouping ]
    else:
        mantissaResult = strMantissa

    result = integerResult

    if mantissaResult != '':
        result += '.' + mantissaResult

    return result, negative
Ejemplo n.º 11
0
def formatNumber( number, outputRadix, leadingZero, integerGrouping ):
    negative = ( number < 0 )

    if outputRadix == g.fibBase:
        strInteger = convertToFibBase( floor( number ) )
        strMantissa = ''
    elif outputRadix == g.phiBase:
        strInteger, strMantissa = convertToNonintegerBase( number, phi )
    elif outputRadix == g.eBase:
        strInteger, strMantissa = convertToNonintegerBase( number, e )
    elif outputRadix == g.piBase:
        strInteger, strMantissa = convertToNonintegerBase( number, pi )
    elif outputRadix == g.sqrt2Base:
        strInteger, strMantissa = convertToNonintegerBase( number, sqrt( 2 ) )
    elif outputRadix < 0:   # these mean special bases, not negative numbers
        strInteger = convertToSpecialBase( floor( number ), specialBaseFunctions[ outputRadix ] )
        strMantissa = ''
    elif ( outputRadix != 10 ) or ( g.numerals != g.defaultNumerals ):
        strInteger = str( convertToBaseN( floor( number ), outputRadix, g.outputBaseDigits, g.numerals ) )
        strMantissa = str( convertFractionToBaseN( frac( number ), outputRadix,
                                                   int( mp.dps / math.log10( outputRadix ) ),
                                                   g.outputBaseDigits ) )
    else:
        strNumber = nstr( number, n = g.outputAccuracy, min_fixed=-inf )

        if '.' in strNumber:
            decimal = strNumber.find( '.' )
        else:
            decimal = len( strNumber )

        strInteger = strNumber[ 1 if negative else 0 : decimal ]

        strMantissa = strNumber[ decimal + 1 : ]

        if strMantissa == '0':
            strMantissa = ''
        elif ( strMantissa != '' ) and ( g.outputAccuracy == -1 ):
            strMantissa = strMantissa.rstrip( '0' )

    if integerGrouping > 0:
        firstDelimiter = len( strInteger ) % integerGrouping

        if leadingZero and firstDelimiter > 0:
            integerResult = '0' * ( integerGrouping - firstDelimiter )
        else:
            integerResult = ''

        integerResult += strInteger[ : firstDelimiter ]

        for i in range( firstDelimiter, len( strInteger ), integerGrouping ):
            if integerResult != '':
                integerResult += g.integerDelimiter

            integerResult += strInteger[ i : i + integerGrouping ]

    else:
        integerResult = strInteger

    if g.decimalGrouping > 0:
        mantissaResult = ''

        for i in range( 0, len( strMantissa ), g.decimalGrouping ):
            if mantissaResult != '':
                mantissaResult += g.decimalDelimiter

            mantissaResult += strMantissa[ i : i + g.decimalGrouping ]
    else:
        mantissaResult = strMantissa

    result = integerResult

    if mantissaResult != '':
        result += '.' + mantissaResult

    return result, negative
Ejemplo n.º 12
0
    def convertValue( self, other, tryReverse=True ):
        if self.isEquivalent( other ):
            return self.getValue( )

        if self.isCompatible( other ):
            conversions = [ ]

            if isinstance( other, list ):
                result = [ ]
                source = self

                for count, measurement in enumerate( other ):
                    with extradps( 1 ):
                        conversion = source.convertValue( measurement )

                    if count < len( other ) - 1:
                        result.append( RPNMeasurement( floor( conversion ), measurement.getUnits( ) ) )
                        source = RPNMeasurement( chop( frac( conversion ) ), measurement.getUnits( ) )
                    else:
                        result.append( RPNMeasurement( conversion, measurement.getUnits( ) ) )

                return result

            units1 = self.getUnits( )
            units2 = other.getUnits( )

            unit1String = units1.getUnitString( )
            unit2String = units2.getUnitString( )

            debugPrint( 'unit1String: ', unit1String )
            debugPrint( 'unit2String: ', unit2String )

            if unit1String == unit2String:
                return fmul( self.getValue( ), other.getValue( ) )

            if unit1String in g.operatorAliases:
                unit1String = g.operatorAliases[ unit1String ]

            if unit2String in g.operatorAliases:
                unit2String = g.operatorAliases[ unit2String ]

            exponents = { }

            if not g.unitConversionMatrix:
                loadUnitConversionMatrix( )

            # look for a straight-up conversion
            unit1NoStar = unit1String.replace( '*', '-' )
            unit2NoStar = unit2String.replace( '*', '-' )

            debugPrint( 'unit1NoStar: ', unit1NoStar )
            debugPrint( 'unit2NoStar: ', unit2NoStar )

            if ( unit1NoStar, unit2NoStar ) in g.unitConversionMatrix:
                value = fmul( self.value, mpmathify( g.unitConversionMatrix[ ( unit1NoStar, unit2NoStar ) ] ) )
            elif ( unit1NoStar, unit2NoStar ) in specialUnitConversionMatrix:
                value = specialUnitConversionMatrix[ ( unit1NoStar, unit2NoStar ) ]( self.value )
            else:
                # otherwise, we need to figure out how to do the conversion
                conversionValue = mpmathify( 1 )

                # if that isn't found, then we need to do the hard work and break the units down
                newUnits1 = RPNUnits( )

                for unit in units1:
                    newUnits1.update( RPNUnits( g.unitOperators[ unit ].representation + "^" +
                                                str( units1[ unit ] ) ) )

                newUnits2 = RPNUnits( )

                for unit in units2:
                    newUnits2.update( RPNUnits( g.unitOperators[ unit ].representation + "^" +
                                                str( units2[ unit ] ) ) )

                debugPrint( 'units1:', units1 )
                debugPrint( 'units2:', units2 )
                debugPrint( 'newUnits1:', newUnits1 )
                debugPrint( 'newUnits2:', newUnits2 )

                debugPrint( )
                debugPrint( 'iterating through units:' )

                for unit1 in newUnits1:
                    foundConversion = False

                    for unit2 in newUnits2:
                        debugPrint( 'units 1:', unit1, newUnits1[ unit1 ], getUnitType( unit1 ) )
                        debugPrint( 'units 2:', unit2, newUnits2[ unit2 ], getUnitType( unit2 ) )

                        if getUnitType( unit1 ) == getUnitType( unit2 ):
                            conversions.append( [ unit1, unit2 ] )
                            exponents[ ( unit1, unit2 ) ] = units1[ unit1 ]
                            foundConversion = True
                            break

                    if not foundConversion:
                        debugPrint( 'didn\'t find a conversion, try reducing' )
                        reduced = self.getReduced( )

                        debugPrint( 'reduced:', self.units, 'becomes', reduced.units )

                        reducedOther = other.getReduced( )

                        debugPrint( 'reduced other:', other.units, 'becomes', reducedOther.units )

                        # check to see if reducing did anything and bail if it didn't... bail out
                        if ( reduced.units == self.units ) and ( reducedOther.units == other.units ):
                            break

                        reduced = reduced.convertValue( reducedOther )
                        return RPNMeasurement( fdiv( reduced, reducedOther.value ), reducedOther.getUnits( ) ).getValue( )

                debugPrint( )

                value = conversionValue

                if not foundConversion:
                    # This is a cheat.  The conversion logic has flaws, but if it's possible to do the
                    # conversion in the opposite direction, then we can do that and return the reciprocal.
                    # This allows more conversions without fixing the underlying problems, which will
                    # require some redesign.
                    if tryReverse:
                        return fdiv( 1, other.convertValue( self, False ) )
                    else:
                        raise ValueError( 'unable to convert ' + self.getUnitString( ) +
                                          ' to ' + other.getUnitString( ) )

                for conversion in conversions:
                    if conversion[ 0 ] == conversion[ 1 ]:
                        continue  # no conversion needed

                    debugPrint( 'unit conversion:', g.unitConversionMatrix[ tuple( conversion ) ] )
                    debugPrint( 'exponents', exponents )

                    conversionValue = mpmathify( g.unitConversionMatrix[ tuple( conversion ) ] )
                    conversionValue = power( conversionValue, exponents[ tuple( conversion ) ] )
                    debugPrint( 'conversion: ', conversion, conversionValue )

                    value = fmul( value, conversionValue )

                value = fmul( self.value, value )

            return value
        else:
            if isinstance( other, list ):
                otherUnit = '[ ' + ', '.join( [ unit.getUnitString( ) for unit in other ] ) + ' ]'
            else:
                otherUnit = other.getUnitString( )

            raise ValueError( 'incompatible units cannot be converted: ' + self.getUnitString( ) +
                              ' and ' + otherUnit )
Ejemplo n.º 13
0
import mpmath

mpmath.mp.prec = 3000

tmp = mpmath.frac(mpmath.mp.pi)

with open('pi.inc', 'w') as f:
    print('{', file=f)
    nbytes = 2281 // 8 + 1
    for i in range(0, nbytes):
        end = ','
        if i == nbytes - 1:
            end = ''
        tmp = mpmath.fmul(tmp, 16 * 16)
        print('  ', hex(int(mpmath.floor(tmp))), end, sep='', file=f)
        tmp = mpmath.frac(tmp)
    print('};', file=f)
Ejemplo n.º 14
0
 def _frac(num):
   return mp.frac(num)