Example #1
1
def OLDgetPartitionNumber( n ):
    if n < 0:
        return 0

    if n < 2:
        return 1

    result = mpmathify( 0 )

    for k in arange( 1, n + 1 ):
        #n1 = n - k * ( 3 * k - 1 ) / 2
        n1 = fsub( n, fdiv( fmul( k, fsub( fmul( 3, k ), 1 ) ), 2 ) )
        #n2 = n - k * ( 3 * k + 1 ) / 2
        n2 = fsub( n, fdiv( fmul( k, fadd( fmul( 3, k ), 1 ) ), 2 ) )

        result = fadd( result, fmul( power( -1, fadd( k, 1 ) ), fadd( getPartitionNumber( n1 ), getPartitionNumber( n2 ) ) ) )

        if n1 <= 0:
            break

    #old = NOT_QUITE_AS_OLDgetPartitionNumber( n )
    #
    #if ( old != result ):
    #    raise ValueError( "It's broke." )

    return result
Example #2
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
Example #3
0
    def combineUnits( self, units ):
        if not g.unitConversionMatrix:
            loadUnitConversionMatrix( )

        newUnits = RPNUnits( self )

        factor = mpmathify( 1 )

        for unit2 in units:
            if unit2 in newUnits:
                newUnits[ unit2 ] += units[ unit2 ]
            else:
                for unit1 in self:
                    if unit1 == unit2:
                        newUnits[ unit2 ] += units[ unit2 ]
                        break
                    elif getUnitType( unit1 ) == getUnitType( unit2 ):
                        factor = fdiv( factor, pow( mpmathify( g.unitConversionMatrix[ ( unit1, unit2 ) ] ), units[ unit2 ] ) )
                        newUnits[ unit1 ] += units[ unit2 ]
                        break
                else:
                    newUnits[ unit2 ] = units[ unit2 ]

        #print( 'newUnits', newUnits )
        return factor, newUnits
Example #4
0
def convertToBase10( integer, mantissa, inputRadix ):
    result = mpmathify( 0 )
    base = mpmathify( 1 )

    validNumerals = g.numerals[ : inputRadix ]

    for i in range( len( integer ) - 1, -1, -1 ):
        digit = validNumerals.find( integer[ i ] )

        if digit == -1:
            raise ValueError( 'invalid numeral \'%c\' for base %d' % ( integer[ i ], inputRadix ) )

        result += digit * base
        base *= inputRadix

    base = fdiv( 1, inputRadix )

    for i in range( 0, len( mantissa ) ):
        digit = validNumerals.find( mantissa[ i ] )

        if digit == -1:
            raise ValueError( 'invalid numeral \'%c\' for base %d' % ( mantissa[ i ], inputRadix ) )

        result += digit * base
        base /= inputRadix

    return result
Example #5
0
    def create_hexagonal_grid_nearestN(origin, d, point, N):
        """
        Create a new coherent basis with basis states on a hexagonal grid.

        As basis states the nearest N grid points to the center are choosen.

        *Arguments*
            * *origin*
                A complex number defining the origin of the grid.

            * *d*
                A real number defining the lattice constant.

            * *point*
                A complex number used as reference point to which the nearest
                N lattice points are selected.

            * *N*
                An integer giving the number of basis states.
        """
        origin = mpmath.mpmathify(origin)
        point = mpmath.mpmathify(point)
        d = mpmath.mpf(d)
        lat = lattice.HexagonalLattice(d, origin, dtype=mpmath.mpf)
        lat.select_nearestN(point, N)
        return CoherentBasis(lat)
def stringExpressionValid(str):
    try:
        mpmath.mpmathify(str)
        return True
    except Exception as err:
        print(err)
        return False
Example #7
0
def times_a(array1, array2):
    from  mpmath import mp as math
    math.prec = 200
    a1 = list(array1)
    a2 = list(array2)
    output = [math.fmul(math.mpmathify(a1[i]),math.mpmathify(a2[i])) for i in range(len(a1))]
    return output
Example #8
0
def getSkyLocation( n, k ):
    if not isinstance( n, ephem.Body ) or not isinstance( k, RPNDateTime ):
        raise ValueError( '\'sky_location\' expects an astronomical object and a date-time' )

    n.compute( k.to( 'utc' ).format( ) )

    return [ fdiv( fmul( mpmathify( n.ra ), 180 ), pi ), fdiv( fmul( mpmathify( n.dec ), 180 ), pi ) ]
Example #9
0
def expectResult( command, expected ):
    if g.testFilter:
        if g.testFilter not in command:
            return

    if g.timeIndividualTests:
        startTime = time.process_time( )

    print( 'rpn', command )
    result = rpn( shlex.split( command + ' -I' ) )[ 0 ]

    compare = None

    if isinstance( expected, list ):
        compare = [ ]

        for i in expected:
            if isinstance( i, ( int, float, complex ) ):
                compare.append( mpmathify( i ) )
            else:
                compare.append( i )
    else:
        if isinstance( expected, ( int, float, complex ) ):
            compare = mpmathify( expected )
        else:
            compare = expected

    compareResults( result, compare )

    print( '    test passed!' )

    if g.timeIndividualTests:
        print( 'Test complete.  Time elapsed:  {:.3f} seconds'.format( time.process_time( ) - startTime ) )

    print( '' )
Example #10
0
def getSkyLocation( n, k ):
    '''Returns the location of an astronomical object in the sky in terms of right ascension and declination.'''
    if not isinstance( n, ephem.Body ) or not isinstance( k, RPNDateTime ):
        raise ValueError( '\'sky_location\' expects an astronomical object and a date-time' )

    n.compute( k.to( 'utc' ).format( ) )

    return [ fdiv( fmul( mpmathify( n.ra ), 180 ), pi ), fdiv( fmul( mpmathify( n.dec ), 180 ), pi ) ]
Example #11
0
def getLocationInfo( location ):
    if isinstance( location, str ):
        location = getLocation( location )
    elif not isinstance( location. RPNLocation ):
        raise ValueError( 'location name or location object expected' )

    return [ fdiv( fmul( mpmathify( location.observer.lat ), 180 ), pi ),
             fdiv( fmul( mpmathify( location.observer.long ), 180 ), pi ) ]
Example #12
0
    def getAzimuthAndAltitude( self, location=None, date=None ):
        if location and date:
            if isinstance( location, str ):
                location = getLocation( location )

            location.observer.date = date.to( 'utc' ).format( )
            self.object.compute( location.observer )

        return RPNMeasurement( mpmathify( self.object.az ), 'radians' ), \
               RPNMeasurement( mpmathify( self.object.alt ), 'radians' )

        return self.getAzimuthAndAltitude( )
def doubledouble2string(doubdoub,n=19):
    """
    Convert a double-double tuple into a string with n decimal digits of precision.  Default is n=19,
    which is the maximum precision that this longdouble-based double-double format can provide.
    min_fixed is the position of the leading digit such that any number with a leading
    digit less than or equal to min_fixed will be written in exponential format.
    e.g., 0.00123 has its leading digit in the -3 place, so if min_fixed>=-3
    it will be printed as 1.23e-3, and if min_fixed<=-4 it will be printed as 0.00123.
    """
    mpmath.mp.prec=105
    hi=mpmath.mpmathify(doubdoub[0])
    lo=mpmath.mpmathify(doubdoub[1])
    tot=mpmath.fadd(hi,lo)
    return mpmath.nstr(tot,n)
Example #14
0
def downloadOEISSequence( id ):
    '''Downloads and formats data from oeis.org.'''
    keywords = downloadOEISText( id, 'K' ).split( ',' )

    # If oeis.org isn't available, just punt everything
    if keywords == [ '' ]:
        return 0

    result, success = downloadOEISTable( id )

    if success:
        return result

    if 'nonn' in keywords:
        result = downloadOEISText( id, 'S' )
        result += downloadOEISText( id, 'T' )
        result += downloadOEISText( id, 'U' )
    else:
        result = downloadOEISText( id, 'V' )
        result += downloadOEISText( id, 'W' )
        result += downloadOEISText( id, 'X' )

    if 'cons' in keywords:
        offset = int( downloadOEISText( id, 'O' ).split( ',' )[ 0 ] )
        result = ''.join( result.split( ',' ) )
        return mpmathify( result[ : offset ] + '.' + result[ offset : ] )
    else:
        #return [ mpmathify( i ) for i in result.split( ',' ) ]
        return [ int( i ) for i in result.split( ',' ) ]
Example #15
0
    def create_hexagonal_grid_rings(center, d, rings):
        """
        Create a new coherent basis with basis states on a hexagonal grid.

        The basis states are choosen in rings around the center on a hexagonal
        grid with lattice constant d.

        *Arguments*
            * *center*
                A complex number defining the center of the rings.

            * *d*
                A real number defining the lattice constant.

            * *rings*
                An integer giving the number of rings.
        """
        center = mpmath.mpmathify(center)
        d = mpmath.mpf(d)
        lat = lattice.HexagonalLattice(d, center, dtype=mpmath.mpf)
        for i in range(-rings,rings+1):
            if i<0:
                start = -rings-i
                end = rings
            else:
                start = -rings
                end = rings-i
            for j in range(start,end+1):
                lat.select((i, j))
        return CoherentBasis(lat)
Example #16
0
File: rpnBase.py Project: flawr/rpn
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
Example #17
0
def getRightTruncations( n ):
    if n < 0:
        raise ValueError( '\'get_right_truncations\' requires a positive argument' )

    str = getMPFIntegerAsString( n )

    for i in range( len( str ), 0, -1 ):
        yield mpmathify( str[ 0 : i ] )
Example #18
0
def getLeftTruncations( n ):
    if n < 0:
        raise ValueError( '\'get_left_truncations\' requires a positive argument' )

    str = getMPFIntegerAsString( n )

    for i, e in enumerate( str ):
        yield mpmathify( str[ i : ] )
Example #19
0
def getThueMorseConstant( ):
    result = 0
    factor = mpmathify( '0.5' )

    for i in arange( 0, mp.prec + 1 ):
        result = fadd( result, fmul( getNthThueMorse( i ), factor ) )
        factor = fdiv( factor, 2 )

    return result
Example #20
0
def sph_kn_exact(n, z):
    """Return the value of k_n computed using the exact formula.

    The expression used is http://dlmf.nist.gov/10.49.E12 .

    """
    zm = mpmathify(z)
    s = sum(_a(k, n)/zm**(k+1) for k in xrange(n+1))
    return pi*exp(-zm)/2*s
Example #21
0
def sph_h2n_exact(n, z):
    """Return the value of h^{(2)}_n computed using the exact formula.

    The expression used is http://dlmf.nist.gov/10.49.E7 .

    """
    zm = mpmathify(z)
    s = sum(mpc(0,-1)**(k-n-1)*_a(k, n)/zm**(k+1) for k in xrange(n+1))
    return exp(mpc(0,-1)*zm)*s
Example #22
0
 def __init__( self, value, units = RPNUnits( ) ):
     if isinstance( value, str ):
         self.value = mpmathify( value )
         self.units = RPNUnits( units )
     elif isinstance( value, RPNMeasurement ):
         self.value = value.value
         self.units = RPNUnits( value.units )
     else:
         self.value = value
         self.units = RPNUnits( units )
Example #23
0
def sph_i2n_exact(n, z):
    """Return the value of i^{(2)}_n computed using the exact formula.

    The expression used is http://dlmf.nist.gov/10.49.E10 .

    """
    zm = mpmathify(z)
    s1 = sum(mpc(-1,0)**k * _a(k, n)/zm**(k+1) for k in xrange(n+1))
    s2 = sum(_a(k, n)/zm**(k+1) for k in xrange(n+1))
    return exp(zm)/2 * s1 + mpc(-1,0)**n*exp(-zm)/2 * s2
Example #24
0
def sph_yn_exact(n, z):
    """Return the value of y_n computed using the exact formula.

    The expression used is http://dlmf.nist.gov/10.49.E4 .

    """
    zm = mpmathify(z)
    s1 = sum((-1)**k*_a(2*k, n)/zm**(2*k+1) for k in xrange(0, int(n/2) + 1))
    s2 = sum((-1)**k*_a(2*k+1, n)/zm**(2*k+2) for k in xrange(0, int((n-1)/2) + 1))
    return -cos(zm - n*pi/2)*s1 + sin(zm - n*pi/2)*s2
Example #25
0
def formatOutput( output ):
    # filter out text strings
    for c in output:
        if c in '+-.':
            continue

        # anything with embedded whitespace is a string
        if c in string.whitespace or c in string.punctuation:
            return output

    #print( )
    #print( 'formatOutput 1:', output )

    # override settings with temporary settings if needed
    # if g.tempCommaMode:
    #     comma = True
    # else:
    #     comma = g.comma

    # output settings, which may be overrided by temp settings
    outputRadix = g.outputRadix
    integerGrouping = g.integerGrouping
    leadingZero = g.leadingZero

    if g.tempHexMode:
        integerGrouping = 4
        leadingZero = True
        outputRadix = 16

    if g.tempLeadingZeroMode:
        leadingZero = True

    if g.tempOctalMode:
        integerGrouping = 3
        leadingZero = True
        outputRadix = 8

    mpOutput = mpmathify( output )

    imaginary = im( mpOutput )
    real = re( mpOutput )

    result, negative = formatNumber( real, outputRadix, leadingZero, integerGrouping )

    if negative:
        result = '-' + result

    if imaginary != 0:
        strImaginary, negativeImaginary = formatNumber( imaginary, outputRadix, leadingZero )
        result = '( ' + result + ( ' - ' if negativeImaginary else ' + ' ) + strImaginary + 'j )'

    #print( 'formatOutput 2:', output )
    #print( )

    return result
Example #26
0
def interpretAsBase( args, base ):
    if isinstance( args, list ):
        args.reverse( )
    else:
        args = [ args ]

    if isinstance( base, list ):
        return [ interpretAsBase( args, i ) for i in base ]

    value = mpmathify( 0 )
    multiplier = mpmathify( 1 )

    for i in args:
        if i >= real_int( base ):
            raise ValueError( 'invalid value for base', int( base ) )

        value = fadd( value, fmul( i, multiplier ) )
        multiplier = fmul( multiplier, base )

    return value
Example #27
0
    def getAngularSeparation( self, other, location, date ):
        if isinstance( location, str ):
            location = getLocation( location )

        location.observer.date = date.to( 'utc' ).format( )

        self.object.compute( location.observer )
        other.object.compute( location.observer )

        return RPNMeasurement( mpmathify( ephem.separation( ( self.object.az, self.object.alt ),
                                                            ( other.object.az, other.object.alt ) ) ), 'radian' )
Example #28
0
    def getAngularSize( self, location=None, date=None ):
        if location and date:
            if isinstance( location, str ):
                location = getLocation( location )

            location.observer.date = date.to( 'utc' ).format( )
            self.object.compute( location.observer )

        # I have no idea why size seems to return the value in arcseconds... that
        # goes against the pyephem documentation that it always uses radians for angles.
        return RPNMeasurement( mpmathify( fdiv( fmul( fdiv( self.object.size, 3600 ), pi ), 180 ) ), 'radian' )
Example #29
0
def getConstant( name ):
    if name not in g.constantOperators:
        raise ValueError( 'Invalid constant: ', name )

    unit = g.constantOperators[ name ].unit
    value = g.constantOperators[ name ].value

    if unit == '':
        return mpmathify( value )
    else:
        return RPNMeasurement( value, unit )
Example #30
0
def runYAFU( n ):
    import subprocess

    full_out = subprocess.run( [ g.userConfiguration[ 'yafu_path' ] + os.sep +
                                 g.userConfiguration[ 'yafu_binary' ], str( int( n ) ), '-xover', '120' ],
                             stdout=subprocess.PIPE, cwd=g.userConfiguration[ 'yafu_path' ] ).stdout.decode( 'ascii' )

    #print( 'out', full_out )

    out = full_out[ full_out.find( '***factors found***' ) : ]

    if len( out ) < 2:
        if log10( n ) > 40:
            raise ValueError( 'yafu seems to have crashed trying to factor ' + str( int( n ) ) +
                              '.\n\nyafu output follows:\n' + full_out )
        else:
            debugPrint( 'yafu seems to have crashed, switching to built-in factoring code' )
            from rpn.factorise import factorise
            return factorise( int( n ) )

    result = [ ]

    while True:
        prime = ''

        out = out[ out.find( 'P' ) : ]

        if len( out ) < 2:
            break

        out = out[ out.find( '=' ) : ]

        index = 2

        while out[ index ] >= '0' and out[ index ] <= '9':
            prime += out[ index ]
            index += 1

        result.append( mpmathify( prime ) )

    if not result:
        raise ValueError( 'yafu seems to have failed.' )

    answer = fprod( result )

    if answer != n:
        debugPrint( '\nyafu has barfed' )
        for i in result:
            n = fdiv( n, i )

        result.extend( runYAFU( n ) )

    return sorted( result )