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
    def createStructure(self):
        startw = (self.widthSmall / 2) + self.xpoz
        startd = (self.depthSmall / 2) + self.ypoz
        starth = (self.heightSmall / 2) + self.zpoz

        for i in mp.arange(self.wElements):
            for j in mp.arange(self.dElements):
                for k in mp.arange(self.hElements):
                    if self.isInStructure(startw+self.widthSmall*i, startd+self.depthSmall*j, starth+self.heightSmall*k):
                        self.smallBlocksStructure.append([startw+self.widthSmall*i, startd+self.depthSmall*j, starth+self.heightSmall*k])
        self.nElements = mp.mpmathify(len(self.smallBlocksStructure))
Example #3
0
    def tupper_bmp(self, i: mp.mpf = 0) -> np.matrix:
        """
        Returns a bitmap representing the i-th shift from the Tupper's original self-referential formula
        :param i: i-th shift
        :return: boolean matrix representing the bitmap
        """
        bmp = mp.matrix(self.height, self.width)

        for x in mp.arange(self.height):
            for y in mp.arange(self.width):
                bmp[x, y] = TupperPy.tupper(x, (self.k + y + 17 * i))

        np_bmp = np.matrix(bmp.transpose().tolist(), dtype=bool)

        return np.flip(np_bmp, 1)
Example #4
0
def test_Diode_In_mpmath():
    b = [mpm.mpf('1.238e-14'), mpm.mpf('1.3'), mpm.mpf('1')]
    c = None
    #0.0026638081177255196
    rng = mpm.arange('0.01', '2', '0.01')
    xstart = [mpm.mpf('0.00001')]
    xend = [mpm.mpf('2')]
    Ve = np.array([[0.0001]])

    #снимем ВАХ
    #    resrng=[solver_Diode_In_mpmath ([x],b)[0] for x in rng] # изменяем напряжение на базе при постоянном напряжении на коллекторе - снимаем ток базы.

    #resrng=o_pmpm.makeMeasOneDot_lognorm(solver_Diode_In_mpmath, x],b)[0] for x in rng] # изменяем напряжение на базе при постоянном напряжении на коллекторе - снимаем ток базы.
    resrng = [
        o_pmpm.makeMeasOneDot_lognorm(solver_Diode_In_mpmath, [x], b, c, Ve)
        for x in rng
    ]

    resrng1 = [
        solver_Diode_In_mpmath([x], b)[0] for x in rng
    ]  # изменяем напряжение на базе при постоянном напряжении на коллекторе - снимаем ток базы.
    #   plt.plot(rng , resrngorig, label='r=0')
    plt.plot(rng, resrng, label='r=1000')
    plt.plot(rng, resrng1, label='r=3000')
    plt.legend(loc='upper left')
    #plt.axis([0.0,1.0,0,5])
    plt.grid()
    plt.show()
Example #5
0
def CalibrationHa(z,oldLum,it):
	newLum = [0. for x in range((it.shape[0]))]
	oldpara = np.array([[0. for i in range(3)] for i in range(it.shape[0])])
	oldLF = np.array([0. for i in range(it.shape[0])])
	interpolatingSize =100
	for i in range(oldpara.shape[0]):
	        oldpara[i][0] = 1.37e-3
	        oldpara[i][2] = -1.35
	        if z[it[i]] <1.3 :oldpara[i][1] = 5.1e41*np.power((1+z[it[i]]),3.1)
	        if z[it[i]] >=1.3:oldpara[i][1] =6.8e42
	        oldLF[i] = LuminosityFunction(oldpara[i],oldLum[i])
	rangea = oldLF.copy()
	rangea.sort()
	rangea = rangea[rangea>0]
	grid = np.array([[0. for i in range(interpolatingSize)] for i in range(2)])
	mpgrid = mpmath.arange(mpmath.log10(rangea.min()),mpmath.log10(rangea.max()),(np.log10(rangea.max())-np.log10(rangea.min()))/interpolatingSize)
	grid[0] = np.ogrid[np.log10(rangea.min()):np.log10(oldLF.max()):interpolatingSize*1j]
	grid[1] = np.ogrid[0:6:interpolatingSize*1j]
	newLF = np.array([[0.for i in range(interpolatingSize)] for i in range(interpolatingSize)])
	for i in range(interpolatingSize):
		for j in range(interpolatingSize):
			newLF[i][j]= optimize.brentq(rootfinding,1e30,1e50,args=(luminosityParameterHa(grid[1][i]),mpgrid[j]))
	newLum = interpolate.interpn([grid[0],grid[1]],newLF,np.array([np.log10(oldLF),z[it]]).T,bounds_error=False,fill_value=0.0)
	newLum = np.power(10,newLum)
	return newLum
Example #6
0
def getNthPolyPrime( n, poly ):
    result = getNthPrime( n )

    for i in arange( 1, poly ):
        result = getNthPrime( result )

    return result
Example #7
0
def getNthDelannoyNumber( n ):
    result = 0

    for k in arange( 0, fadd( real( n ), 1 ) ):
        result = fadd( result, fmul( binomial( n, k ), binomial( fadd( n, k ), k ) ) )

    return result
Example #8
0
def oldGetPartitionNumber(n):
    if n < 2:
        return 1

    result = mpmathify(0)

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

        result = fadd(
            result,
            fmul(power(-1, fadd(k, 1)),
                 fadd(getPartitionNumber(sub1), getPartitionNumber(sub2))))

        if sub1 <= 0:
            break

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

    return result
Example #9
0
def tetrate( i, j ):
    result = i

    for x in arange( 1, j ):
        result = power( result, i )

    return result
Example #10
0
def tetrateRight( i, j ):
    result = i

    for x in arange( 1, j ):
        result = power( i, result )

    return result
Example #11
0
def getNthSchroederHipparchusNumber( n ):
    result = 0

    for i in arange( n ):
        result = fadd( result, fmul( getNarayanaNumber( n, fadd( i, 1 ) ), power( 2, i ) ) )

    return result
Example #12
0
def getNthFibonorial( n ):
    result = 1

    for i in arange( 2, real( n ) ):
        result = fmul( result, fib( i ) )

    return result
Example #13
0
def getNextPrimes( p, k, func=getNextPrimeCandidateForAny ):
    result = [ ]

    for i in arange( 0, k ):
        p = getNextPrime( p, func )
        result.append( p )

    return result
Example #14
0
def getNthMotzkinNumber( n ):
    result = 0

    for j in arange( 0, floor( fdiv( real( n ), 3 ) ) + 1 ):
        result = fadd( result, fprod( [ power( -1, j ), binomial( fadd( n, 1 ), j ),
                                      binomial( fsub( fmul( 2, n ), fmul( 3, j ) ), n ) ] ) )

    return fdiv( result, fadd( n, 1 ) )
Example #15
0
def getNthAperyNumber( n ):
    result = 0

    for k in arange( 0, real( n ) + 1 ):
        result = fadd( result, fmul( power( binomial( n, k ), 2 ),
                                     power( binomial( fadd( n, k ), k ), 2 ) ) )

    return result
Example #16
0
def exponentiatePolynomialOperator( n, k ):
    '''Exponentiates an arbitrary polynomial by an integral power k.'''
    result = n

    for _ in arange( 0, k - 1 ):
        result = multiplyPolynomials( result, n )

    return result
Example #17
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 #18
0
def getNthPolytopeNumber( n, d ):
    result = real_int( n )
    m = n + 1

    for i in arange( 1, d - 1 ):
        result = fmul( result, m )
        m += 1

    return fdiv( result, fac( d - 1 ) )
Example #19
0
File: rpnDice.py Project: flawr/rpn
def rollMultipleDice( expression, times ):
    result = [ ]

    dice = parseDiceExpression( expression )

    for i in arange( 0, times ):
        result.append( evaluateDiceExpression( dice ) )

    return result
Example #20
0
def getThueMorseConstant( ):
    result = 0
    factor = mpmathify( '0.5' )

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

    return result
Example #21
0
def getNthPolytopeNumberOperator(n, d):
    result = n
    m = fadd(n, 1)

    for _ in arange(1, d):
        result = fmul(result, m)
        m = fadd(m, 1)

    return fdiv(result, fac(d))
Example #22
0
def getExpandedFactorListSympy( factors ):
    '''Takes a list of tuples where each tuple is a prime factor and an exponent
    and returns a simple list of prime factors.'''
    result = [ ]

    for key in factors:
        for i in arange( 0, factors[ key ] ):
            result.append( key )

    return sorted( result )
Example #23
0
def getNthMerten( n ):
    if real( n ) == 1:
        return 1

    result = 0

    for i in arange( 1, n + 1 ):
        result = fadd( result, getMobius( i ) )

    return result
Example #24
0
 def PlotPos(self, fignum=None, color='g', dt=0.01, lw=2):
     tVect = arange(0, self.duration, dt)
     if tVect[-1] < self.duration:
         tVect = np.append(tVect, self.duration)
         
     xVect = [self.EvalPos(t) for t in tVect]
     if fignum is not None:
         plt.figure(fignum)
     plt.plot(tVect, xVect, color=color, linewidth=lw)
     plt.show(False)
Example #25
0
def isBaseKPandigitalOperator(n, base):
    digits = convertToBaseN(n, base, outputBaseDigits=True)

    for i in arange(min(int(base), len(digits))):
        try:
            digits.index(i)
        except ValueError:
            return 0

    return 1
Example #26
0
def getNthPrimorial( n ):
    if real_int( n ) == 0:
        return 1

    result = 2

    for i in arange( 1, n ):
        result = fmul( result, getNthPrime( i + 1 ) )

    return result
Example #27
0
def getNthReversalAdditionGenerator(n, k):
    nextOne = int(n)
    yield nextOne

    for _ in arange(k):
        nextOne = fadd(reverseDigits(nextOne), nextOne)

        yield nextOne

        if isPalindrome(nextOne):
            break
Example #28
0
def getPreviousPrimes( p, k, func = getPreviousPrimeCandidateForAny ):
    if p < 1000000000 and getNthPrime( p ) < k:
        raiseError( 'There is no previous prime to 2.' )

    result = [ ]

    for i in arange( 0, k ):
        p = getPreviousPrime( p, func )
        result.append( p )

    return result
Example #29
0
def getNthReversalAddition( n, k ):
    next = int( real_int( n ) )
    yield next

    previous = next

    for i in arange( k ):
        if isPalindrome( next ):
            break

        next = fadd( reverseDigits( next ), next )
        yield next
Example #30
0
def getNthSylvester( n ):
    if real( n ) == 1:
        return 2
    elif n == 2:
        return 3
    else:
        list = [ 2, 3 ]

        for i in arange( 2, n ):
            list.append( fprod( list ) + 1 )

    return list[ -1 ]
Example #31
0
def getNthMotzkinNumber( n ):
    '''
    http://oeis.org/A001006

    a(n) = sum((-1)^j*binomial(n+1, j)*binomial(2n-3j, n), j=0..floor(n/3))/(n+1)
    '''
    result = 0

    for j in arange( 0, floor( fdiv( real( n ), 3 ) ) + 1 ):
        result = fadd( result, fprod( [ power( -1, j ), binomial( fadd( n, 1 ), j ),
                                      binomial( fsub( fmul( 2, n ), fmul( 3, j ) ), n ) ] ) )

    return fdiv( result, fadd( n, 1 ) )
Example #32
0
def getNthAperyNumber( n ):
    '''
    http://oeis.org/A005259

    a(n) = sum(k=0..n, C(n,k)^2 * C(n+k,k)^2 )
    '''
    result = 0

    for k in arange( 0, real( n ) + 1 ):
        result = fadd( result, fmul( power( binomial( n, k ), 2 ),
                                     power( binomial( fadd( n, k ), k ), 2 ) ) )

    return result
Example #33
0
def tetrateRightOperator(i, j):
    '''
    This is the larger, right-associative version of the hyper4 operator.

    This function forces the second argument to an integer and runs in O( n )
    time based on the second argument.
    '''
    result = i

    for _ in arange(1, j):
        result = power(i, result)

    return result
Example #34
0
def tetrateOperator(i, j):
    '''
    This is the smaller (left-associative) version of the hyper4 operator.

    This function forces the second argument to an integer and runs in O( n )
    time based on the second argument.
    '''
    result = i

    for _ in arange(1, j):
        result = power(result, i)

    return result
Example #35
0
def exponentiatePolynomial( n, k ):
    if not isinstance( n, list ):
        n = [ n ]

    if isinstance( k, list ):
        return [ multiplyPolynomials( n, i ) for i in k ]
    else:
        result = n

        for i in arange( 0, k - 1 ):
            result = multiplyPolynomials( result, n )

        return result
Example #36
0
def getNthSylvesterNumber(n):
    if n == 1:
        return 2

    if n == 2:
        return 3

    sylvesters = [2, 3]

    for _ in arange(2, n):
        sylvesters.append(fprod(sylvesters) + 1)

    return sylvesters[-1]
Example #37
0
def getNthAlternatingFactorial( n ):
    result = 0

    negative = False

    for i in arange( real( n ), 0, -1 ):
        if negative:
            result = fadd( result, fneg( fac( i ) ) )
            negative = False
        else:
            result = fadd( result, fac( i ) )
            negative = True

    return result
Example #38
0
def exponentiatePolynomial( n, k ):
    '''Exponentiates an arbitrary polynomial by an integral power k.'''
    if not isinstance( n, list ):
        n = [ n ]

    if isinstance( k, list ):
        return [ multiplyPolynomials( n, i ) for i in k ]
    else:
        result = n

        for i in arange( 0, k - 1 ):
            result = multiplyPolynomials( result, n )

        return result
Example #39
0
def getAliquotSequence( n, k ):
    '''
    The aliquot sum of n is the sum of the divisors of n, not counting n itself
    as a divisor.  Subsequent aliquot sums can then be computed.  These sequences
    usually terminate, but some, like 276, get so large it has not been determined
    if they ever terminate.
    '''
    yield real( floor( n ) )

    a = n

    for i in arange( 0, real( k ) - 1 ):
        b = fsub( getSigma( a ), a )
        yield b
        a = b
Example #40
0
def getNthDelannoyNumber(n):
    if n == 1:
        return 3

    precision = int(fmul(n, 0.8))

    if mp.dps < precision:
        mp.dps = precision

    result = 0

    for k in arange(0, fadd(n, 1)):
        result = fadd(result, fmul(binomial(n, k), binomial(fadd(n, k), k)))

    return result
Example #41
0
def getNthSchroederNumber( n ):
    if real( n ) == 1:
        return 1

    if n < 0:
        raise ValueError( '\'nth_schroeder\' expects a non-negative argument' )

    n = fsub( n, 1 )

    result = 0

    for k in arange( 0, fadd( n, 1 ) ):
        result = fadd( result, fdiv( fprod( [ power( 2, k ), binomial( n, k ),
                                              binomial( n, fsub( k, 1 ) ) ] ), n ) )

    return result
Example #42
0
    def PlotPos(self, fignum=None, color='g', dt=0.01, lw=2, includingSW=False):
        tVect = arange(0, self.duration, dt)
        if tVect[-1] < self.duration:
            tVect = np.append(tVect, self.duration)
            
        xVect = [self.EvalPos(t) for t in tVect]
        if fignum is not None:
            plt.figure(fignum)
        plt.plot(tVect, xVect, color=color, linewidth=lw)

        if includingSW:
            ax = plt.gca().axis()
            for s in self.switchpointsList:
                plt.plot([s, s], [ax[2], ax[3]], 'r', linewidth=1)
                
        plt.show(False)
Example #43
0
    def PlotPos(self, fignum='Displacement Profiles', includingSW=False, dt=0.005):
        plt.figure(fignum)

        tVect = arange(0, self.duration, dt)
        if tVect[-1] < self.duration:
            tVect = np.append(tVect, self.duration)

        xVect = [self.EvalPos(t) for t in tVect]
        plt.plot(tVect, xVect, linewidth=2)
        handle = ['joint {0}'.format(i + 1) for i in xrange(self.ndof)]
        plt.legend(handle)

        if includingSW:
            ax = plt.gca().axis()
            for s in self.switchpointsList:
                plt.plot([s, s], [ax[2], ax[3]], 'r', linewidth=1)
        plt.show(False)
Example #44
0
def getDecimalDigitList(n, k):
    result = []

    setAccuracy(k)

    digits = floor(log10(n))

    if digits < 0:
        for _ in arange(fsub(fabs(digits), 1)):
            result.append(0)

        k = fsub(k, fsub(fabs(digits), 1))

    value = fmul(n, power(10, fsub(k, fadd(digits, 1))))

    for c in getMPFIntegerAsString(floor(value)):
        result.append(int(c))

    return result
Example #45
0
def getNthAperyNumber(n):
    '''
    http://oeis.org/A005259

    a(n) = sum(k=0..n, C(n,k)^2 * C(n+k,k)^2 )
    '''
    precision = int(fmul(n, 1.6))

    if mp.dps < precision:
        mp.dps = precision

    result = 0

    for k in arange(0, n + 1):
        result = fadd(
            result,
            fmul(power(binomial(n, k), 2), power(binomial(fadd(n, k), k), 2)))

    return result
Example #46
0
def getNthSchroederHipparchusNumber(n):
    '''
    https://en.wikipedia.org/wiki/Schr%C3%B6der%E2%80%93Hipparchus_number
    https://oeis.org/A001003
    '''
    if n == 0:
        return 1

    precision = int(fmul(n, 0.8))

    if mp.dps < precision:
        mp.dps = precision

    result = 0

    for i in arange(n):
        result = fadd(result,
                      fmul(getNarayanaNumber(n, fadd(i, 1)), power(2, i)))

    return result
Example #47
0
def isKthPower(n, k):
    if not isint(k, gaussian=True):
        raise ValueError('integer argument expected')

    if k == 1:
        return 1

    if im(n):
        # I'm not sure why this is necessary...
        if re(n) == 0:
            return isKthPower(im(n), k)

        # We're looking for a Gaussian integer among any of the roots.
        for i in [autoprec(root)(n, k, i) for i in arange(k)]:
            if isint(i, gaussian=True):
                return 1

        return 0

    rootN = autoprec(root)(n, k)
    return 1 if isint(rootN, gaussian=True) else 0
Example #48
0
def getNthSchroederNumber(n):
    if n == 1:
        return 1

    n = fsub(n, 1)

    result = 0

    precision = int(fmul(n, 0.8))

    if mp.dps < precision:
        mp.dps = precision

    for k in arange(0, fadd(n, 1)):
        result = fadd(
            result,
            fdiv(fprod([power(2, k),
                        binomial(n, k),
                        binomial(n, fsub(k, 1))]), n))

    return result
Example #49
0
def getNthMotzkinNumber(n):
    '''
    http://oeis.org/A001006

    a(n) = sum((-1)^j*binomial(n+1, j)*binomial(2n-3j, n), j=0..floor(n/3))/(n+1)
    '''
    precision = int(n)

    if mp.dps < precision:
        mp.dps = precision

    result = 0

    for j in arange(0, floor(fdiv(n, 3)) + 1):
        result = fadd(
            result,
            fprod([
                power(-1, j),
                binomial(fadd(n, 1), j),
                binomial(fsub(fmul(2, n), fmul(3, j)), n)
            ]))

    return fdiv(result, fadd(n, 1))
Example #50
0
"""
Module: AWD, Analysis, wissenschaftliches Rechnen und Datenvisualisierung
Course: BSc INF 2015, ZH5-Mo, FS16, Schuler Josef A.
This is my solution for the eight of eight parts for the module at FFHS. This shows
some examples of how to visualize the "Kepler'sche Fassregel" and the "Trapezregel"
"""
from mpmath import arange
from sympy import *

x = Symbol('x')
domain = arange(-12, 12, 0.1)
function = x**3


def do_trapezregel(fn, N, a, b):
    """
    Calculate integral using the 'Trapezregel'. This function slices the domain in
    N equal portions and calculates their integrals. It also takes negative integrals
    into account and adds the corresponding zero-positions to the sections.
    :param fn: Function to integrate
    :param N: Number of slices (resolution)
    :param a: Left bound
    :param b: Right bound
    :return: Integral
    """
    title = 'Trapezregel:'
    print('\n\n{title}\n{underline}'.format(title=title,
                                            underline=len(title) * '='))

    # Find 0-positions
    zero_positions = solve(fn, x)
Example #51
0
def getNthMultifactorialOperator(n, k):
    return fprod(arange(n, 0, -(k)))
Example #52
0
def getSublistGenerator( args, start, count ):
    for i in arange( start, fadd( start, count ) ):
        yield args[ int( i ) ]
Example #53
0
def describeIntegerOperator(n):
    indent = ' ' * 4

    print()
    print(int(n), 'is:')

    if isOdd(n):
        print(indent + 'odd')
    elif isEven(n):
        print(indent + 'even')

    if isPrime(n):
        isPrimeFlag = True
        print(indent + 'prime')
    elif n > 3:
        isPrimeFlag = False
        print(indent + 'composite')
    else:
        isPrimeFlag = False

    if isKthPower(n, 2):
        print(indent + 'the ' + getShortOrdinalName(sqrt(n)) +
              ' square number')

    if isKthPower(n, 3):
        print(indent + 'the ' + getShortOrdinalName(cbrt(n)) + ' cube number')

    for i in arange(4, fadd(ceil(log(fabs(n), 2)), 1)):
        if isKthPower(n, i):
            print(indent + 'the ' + getShortOrdinalName(root(n, i)) + ' ' +
                  getNumberName(i, True) + ' power')

    # triangular
    guess = findPolygonalNumber(n, 3)

    if getNthPolygonalNumber(guess, 3) == n:
        print(indent + 'the ' + getShortOrdinalName(guess) +
              ' triangular number')

    # pentagonal
    guess = findPolygonalNumber(n, 5)

    if getNthPolygonalNumber(guess, 5) == n:
        print(indent + 'the ' + getShortOrdinalName(guess) +
              ' pentagonal number')

    # hexagonal
    guess = findPolygonalNumber(n, 6)

    if getNthPolygonalNumber(guess, 6) == n:
        print(indent + 'the ' + getShortOrdinalName(guess) +
              ' hexagonal number')

    # heptagonal
    guess = findPolygonalNumber(n, 7)

    if getNthPolygonalNumber(guess, 7) == n:
        print(indent + 'the ' + getShortOrdinalName(guess) +
              ' heptagonal number')

    # octagonal
    guess = findPolygonalNumber(n, 8)

    if getNthPolygonalNumber(guess, 8) == n:
        print(indent + 'the ' + getShortOrdinalName(guess) +
              ' octagonal number')

    # nonagonal
    guess = findPolygonalNumber(n, 9)

    if getNthPolygonalNumber(guess, 9) == n:
        print(indent + 'the ' + getShortOrdinalName(guess) +
              ' nonagonal number')

    # decagonal
    guess = findPolygonalNumber(n, 10)

    if getNthPolygonalNumber(guess, 10) == n:
        print(indent + 'the ' + getShortOrdinalName(guess) +
              ' decagonal number')

    # if n > 1:
    #    for i in range( 11, 101 ):
    #        if getNthPolygonalNumber( findPolygonalNumber( n, i ), i ) == n:
    #            print( indent + str( i ) + '-gonal' )

    # centered triangular
    guess = findCenteredPolygonalNumber(n, 3)

    if getNthCenteredPolygonalNumber(guess, 3) == n:
        print(indent + 'the ' + getShortOrdinalName(guess) +
              ' centered triangular')

    # centered square
    guess = findCenteredPolygonalNumber(n, 4)

    if getNthCenteredPolygonalNumber(guess, 4) == n:
        print(indent + 'the ' + getShortOrdinalName(guess) +
              ' centered square number')

    # centered pentagonal
    guess = findCenteredPolygonalNumber(n, 5)

    if getNthCenteredPolygonalNumber(guess, 5) == n:
        print(indent + 'the ' + getShortOrdinalName(guess) +
              ' centered pentagonal number')

    # centered hexagonal
    guess = findCenteredPolygonalNumber(n, 6)

    if getNthCenteredPolygonalNumber(guess, 6) == n:
        print(indent + 'the ' + getShortOrdinalName(guess) +
              ' centered hexagonal number')

    # centered heptagonal
    guess = findCenteredPolygonalNumber(n, 7)

    if getNthCenteredPolygonalNumber(guess, 7) == n:
        print(indent + 'the ' + getShortOrdinalName(guess) +
              ' centered heptagonal number')

    # centered octagonal
    guess = findCenteredPolygonalNumber(n, 8)

    if getNthCenteredPolygonalNumber(guess, 8) == n:
        print(indent + 'the ' + getShortOrdinalName(guess) +
              ' centered octagonal number')

    # centered nonagonal
    guess = findCenteredPolygonalNumber(n, 9)

    if getNthCenteredPolygonalNumber(guess, 9) == n:
        print(indent + 'the ' + getShortOrdinalName(guess) +
              ' centered nonagonal number')

    # centered decagonal
    guess = findCenteredPolygonalNumber(n, 10)

    if getNthCenteredPolygonalNumber(guess, 10) == n:
        print(indent + 'the ' + getShortOrdinalName(guess) +
              ' centered decagonal number')

    # pandigital
    if isPandigital(n):
        print(indent + 'pandigital')

    # for i in range( 4, 21 ):
    #    if isBaseKPandigital( n, i ):
    #        print( indent + 'base ' + str( i ) + ' pandigital' )

    # Fibonacci
    result = findInput(n, fib, lambda n: fmul(log10(n), 5))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' Fibonacci number')

    # Tribonacci
    result = findInput(n, lambda n: getNthKFibonacciNumber(n, 3),
                       lambda n: fmul(log10(n), 5))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' Tribonacci number')

    # Tetranacci
    result = findInput(n, lambda n: getNthKFibonacciNumber(n, 4),
                       lambda n: fmul(log10(n), 5))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' Tetranacci number')

    # Pentanacci
    result = findInput(n, lambda n: getNthKFibonacciNumber(n, 5),
                       lambda n: fmul(log10(n), 5))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' Pentanacci number')

    # Hexanacci
    result = findInput(n, lambda n: getNthKFibonacciNumber(n, 6),
                       lambda n: fmul(log10(n), 5))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' Hexanacci number')

    # Heptanacci
    result = findInput(n, lambda n: getNthKFibonacciNumber(n, 7),
                       lambda n: fmul(log10(n), 5))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' Heptanacci number')

    # Octanacci
    result = findInput(n, lambda n: getNthKFibonacciNumber(n, 8),
                       lambda n: fmul(log10(n), 5))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' Octanacci number')

    # Lucas numbers
    result = findInput(n, getNthLucasNumber, lambda n: fmul(log10(n), 5))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' Lucas number')

    # base-k repunits
    if n > 1:
        for i in range(2, 21):
            result = findInput(n,
                               lambda x: getNthBaseKRepunit(x, i),
                               lambda n: log(n, i),
                               minimum=1)

            if result[0]:
                print(indent + 'the ' + getShortOrdinalName(result[1]) +
                      ' base-' + str(i) + ' repunit')

    # Jacobsthal numbers
    result = findInput(n, getNthJacobsthalNumber, lambda n: fmul(log(n), 1.6))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' Jacobsthal number')

    # Padovan numbers
    result = findInput(n, getNthPadovanNumber, lambda n: fmul(log10(n), 9))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' Padovan number')

    # Fibonorial numbers
    result = findInput(n, getNthFibonorial, lambda n: sqrt(fmul(log(n), 10)))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' Fibonorial number')

    # Mersenne primes
    result = findInput(n, getNthMersennePrime,
                       lambda n: fadd(fmul(log(log(sqrt(n))), 2.7), 3))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' Mersenne prime')

    # perfect number
    result = findInput(n, getNthPerfectNumber,
                       lambda n: fmul(log(log(n)), 2.6))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' perfect number')

    # Mersenne exponent
    result = findInput(n,
                       getNthMersenneExponent,
                       lambda n: fmul(log(n), 2.7),
                       maximum=50)

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' Mersenne exponent')

    if not isPrimeFlag and n != 1 and n <= LARGEST_NUMBER_TO_FACTOR:
        # deficient
        if isDeficient(n):
            print(indent + 'deficient')

        # abundant
        if isAbundant(n):
            print(indent + 'abundant')

        # k_hyperperfect
        for i in sorted(list(set(sorted(
                downloadOEISSequence(34898)[:500]))))[1:]:
            if i > n:
                break

            if isKHyperperfect(n, i):
                print(indent + str(i) + '-hyperperfect')
                break

        # smooth
        for i in getPrimes(2, 50):
            if isSmooth(n, i):
                print(indent + str(i) + '-smooth')
                break

        # rough
        previousPrime = 2

        for i in getPrimes(2, 50):
            if not isRough(n, i):
                print(indent + str(previousPrime) + '-rough')
                break

            previousPrime = i

        # is_semiprime
        if isSemiprime(n):
            print(indent + 'semiprime')

        # is_sphenic
        elif isSphenic(n):
            print(indent + 'sphenic')
        elif isSquareFree(n):
            print(indent + 'square-free')

        # powerful
        if isPowerful(n):
            print(indent + 'powerful')

    # factorial
    result = findInput(n, getNthFactorial, lambda n: power(log10(n), 0.92))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' factorial number')

    # alternating factorial
    result = findInput(n, getNthAlternatingFactorial,
                       lambda n: fmul(sqrt(log(n)), 0.72))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' alternating factorial number')

    # double factorial
    if n == 1:
        result = (True, 1)
    else:
        result = findInput(n, getNthDoubleFactorial,
                           lambda n: fdiv(power(log(log(n)), 4), 7))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' double factorial number')

    # hyperfactorial
    result = findInput(n, getNthHyperfactorial,
                       lambda n: fmul(sqrt(log(n)), 0.8))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' hyperfactorial number')

    # subfactorial
    result = findInput(n, getNthSubfactorial, lambda n: fmul(log10(n), 1.1))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' subfactorial number')

    # superfactorial
    if n == 1:
        result = (True, 1)
    else:
        result = findInput(n, getNthSuperfactorial,
                           lambda n: fadd(sqrt(log(n)), 1))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' superfactorial number')

    # pernicious
    if isPernicious(n):
        print(indent + 'pernicious')

    # pronic
    if isPronic(n):
        print(indent + 'pronic')

    # Achilles
    if isAchillesNumber(n):
        print(indent + 'an Achilles number')

    # antiharmonic
    if isAntiharmonic(n):
        print(indent + 'antiharmonic')

    # unusual
    if isUnusual(n):
        print(indent + 'unusual')

    # hyperperfect
    for i in range(2, 21):
        if isKHyperperfect(n, i):
            print(indent + str(i) + '-hyperperfect')

    # Ruth-Aaron
    if isRuthAaronNumber(n):
        print(indent + 'a Ruth-Aaron number')

    # Smith numbers
    if isSmithNumber(n):
        print(indent + 'a Smith number')

    # base-k Smith numbers
    for i in range(2, 10):
        if isBaseKSmithNumber(n, i):
            print(indent + 'a base-' + str(i) + ' Smith number')

    # order-k Smith numbers
    for i in range(2, 11):
        if isOrderKSmithNumber(n, i):
            print(indent + 'an order-' + str(i) + ' Smith number')

    # polydivisible
    if isPolydivisible(n):
        print(indent + 'polydivisible')

    # Carol numbers
    result = findInput(n, getNthCarolNumber,
                       lambda n: fmul(log10(n), fdiv(5, 3)))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' Carol number')

    # Kynea numbers
    result = findInput(n, getNthKyneaNumber,
                       lambda n: fmul(log10(n), fdiv(5, 3)))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' Kynea number')

    # Leonardo numbers
    result = findInput(n, getNthLeonardoNumber,
                       lambda n: fsub(log(n, phi), fdiv(1, phi)))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' Leonardo number')

    # Thabit numbers
    result = findInput(n, getNthThabitNumber, lambda n: fmul(log10(n), 3.25))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' Thabit number')

    # Carmmichael
    if isCarmichaelNumber(n):
        print(indent + 'a Carmichael number')

    # narcissistic
    if isNarcissistic(n):
        print(indent + 'narcissistic')

    # PDI
    if isPerfectDigitalInvariant(n):
        print(indent + 'a perfect digital invariant')

    # PDDI
    if isPerfectDigitToDigitInvariant(n, 10):
        print(indent + 'a perfect digit-to-digit invariant in base 10')

    # Kaprekar
    if isKaprekarNumber(n):
        print(indent + 'a Kaprekar number')

    # automorphic
    if isAutomorphic(n):
        print(indent + 'automorphic')

    # trimorphic
    if isTrimorphic(n):
        print(indent + 'trimorphic')

    # k-morphic
    for i in range(4, 11):
        if isKMorphic(n, i):
            print(indent + str(i) + '-morphic')

    # bouncy
    if isBouncy(n):
        print(indent + 'bouncy')

    # step number
    if isStepNumber(n):
        print(indent + 'a step number')

    # Apery numbers
    result = findInput(n, getNthAperyNumber,
                       lambda n: fadd(fdiv(log(n), 1.5), 1))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' Apery number')

    # Delannoy numbers
    result = findInput(n, getNthDelannoyNumber, lambda n: fmul(log10(n), 1.35))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' Delannoy number')

    # Schroeder numbers
    result = findInput(n, getNthSchroederNumber, lambda n: fmul(log10(n), 1.6))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' Schroeder number')

    # Schroeder-Hipparchus numbers
    result = findInput(n, getNthSchroederHipparchusNumber,
                       lambda n: fdiv(log10(n), 1.5))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' Schroeder-Hipparchus number')

    # Motzkin numbers
    result = findInput(n, getNthMotzkinNumber, log)

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' Motzkin number')

    # Pell numbers
    result = findInput(n, getNthPellNumber, lambda n: fmul(log(n), 1.2))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' Pell number')

    # Sylvester numbers
    if n > 1:
        result = findInput(n, getNthSylvesterNumber,
                           lambda n: sqrt(sqrt(log(n))))

        if result[0]:
            print(indent + 'the ' + getShortOrdinalName(result[1]) +
                  ' Sylvester number')

    # partition numbers
    result = findInput(n, getPartitionNumber, lambda n: power(log(n), 1.56))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' partition number')

    # menage numbers
    result = findInput(n, getNthMenageNumber, lambda n: fdiv(log10(n), 1.2))

    if result[0]:
        print(indent + 'the ' + getShortOrdinalName(result[1]) +
              ' menage number')

    print()
    print(int(n), 'has:')

    # number of digits
    digits = log10(n)

    if isInteger(digits):
        digits += 1
    else:
        digits = ceil(digits)

    print(indent + str(int(digits)) + ' digit' + ('s' if digits > 1 else ''))

    # digit sum
    print(indent + 'a digit sum of ' + str(int(sumDigits(n))))

    # digit product
    digitProduct = multiplyDigits(n)

    print(indent + 'a digit product of ' + str(int(digitProduct)))

    # non-zero digit product
    if digitProduct == 0:
        print(indent + 'a non-zero digit product of ' +
              str(int(multiplyNonzeroDigits(n))))

    if not isPrimeFlag and n != 1 and n <= LARGEST_NUMBER_TO_FACTOR:
        # factors
        factors = getFactors(n)
        factorCount = len(factors)
        print(indent + str(factorCount) + ' prime factor' +
              ('s' if factorCount > 1 else '') + ': ' +
              ', '.join([str(int(i)) for i in factors]))

        # number of divisors
        divisorCount = int(getDivisorCount(n))
        print(indent + str(divisorCount) + ' divisor' +
              ('s' if divisorCount > 1 else ''))

    if n <= LARGEST_NUMBER_TO_FACTOR:
        print(indent + 'a divisor sum of ' + str(int(getSigma(n))))
        print(indent + 'a Stern value of ' + str(int(getNthSternNumber(n))))
        calkinWilf = getNthCalkinWilf(n)
        print(indent + 'a Calkin-Wilf value of ' + str(int(calkinWilf[0])) +
              '/' + str(int(calkinWilf[1])))
        print(indent + 'a Mobius value of ' + str(int(getNthMobiusNumber(n))))
        print(indent + 'a radical of ' + str(int(getRadical(n))))
        print(indent + 'a Euler phi value of ' + str(int(getEulerPhi(n))))

    print(indent + 'a digital root of ' + str(int(getDigitalRoot(n))))

    if hasUniqueDigits(n):
        print(indent + 'unique digits')

    print(indent + 'a multiplicative persistence of ' +
          str(int(getPersistence(n))))
    print(indent + 'an Erdos persistence of ' +
          str(int(getErdosPersistence(n))))

    if n > 9 and isIncreasing(n):
        if not isDecreasing(n):
            print(indent + 'increasing digits')
    elif n > 9 and isDecreasing(n):
        print(indent + 'decreasing digits')

    print()

    return n
Example #54
0
def getRandomIntegers(n, k):
    '''
    Returns k random integers between 0 and n-1.
    '''
    for _ in arange(0, k):
        yield randrange(n)
Example #55
0
def getMultipleRandoms(n):
    '''
    Returns n random numbers.
    '''
    for _ in arange(0, n):
        yield rand()
Example #56
0
def arange(*args):
    """Returns a numpy array with n repetitions of mp.mpf(0)"""
    return np.array(mp.arange(*args))
Example #57
0
#coding=utf-8
import math
import pandas
from mpmath import arange, plot
print(math.factorial(4))
plot(arange(5))
Example #58
0
def enumerateMultipleDice(expression, count):
    dice = parseDiceExpression(expression)

    for _ in arange(0, count):
        yield evaluateDiceExpression(dice)[0]