Пример #1
0
def tables(f, r, v, xi, symmetric, verbose=False):
	"""Calculate k[i], w[i], and f[i]."""
	ki = [None] * len(xi)
	wi = ki[:]
	fi = ki[:]
	if symmetric:
		im = 2**31
	else:
		im = 2**32
	for i, x in enumerate(xi):
		if verbose and i & 7 == 0:
			print('\r{0}/{1}'.format(i, len(xi)), end='', file=sys.stderr)
		if i == 0:
			ki[0] = mpmath.floor(im * r*f(r)/v)
			wi[0] = v / f(r) / im
		else:
			ki[i] = mpmath.floor(im * xi[i-1]/x)
			wi[i] = x / im
		fi[i] = f(x)
	if verbose:
		print('\r{0}/{0}'.format(len(xi)), file=sys.stderr)
	assert all(v is not None for v in ki)
	assert all(v is not None for v in wi)
	assert all(v is not None for v in fi)
	return ki, wi, fi
Пример #2
0
def cplot_in_terminal(expr, *args, prec=None, logname=None, color=lambda i:
    -mpmath.floor(mpmath.log(abs(i), 10))/(30 -
        mpmath.floor(mpmath.log(abs(i), 10))), points=1000000, **kwargs):
    """
    Run mpmath.cplot() but show in terminal if possible
    """
    kwargs['color'] = color
    kwargs['points'] = points
    from mpmath import cplot
    if prec:
        mpmath.mp.dps = prec
    f = lambdify(t, expr, mpmath)
    try:
        from iterm2_tools.images import display_image_bytes
    except ImportError:
        if logname:
            os.makedirs('plots', exist_ok=True)
            file = 'plots/%s.png' % logname
        else:
            file = None
        cplot(f, *args, file=file, **kwargs)
    else:
        from io import BytesIO
        b = BytesIO()
        cplot(f, *args, **kwargs, file=b)
        if logname:
            os.makedirs('plots', exist_ok=True)
            with open('plots/%s.png' % logname, 'wb') as f:
                f.write(b.getvalue())
        print(display_image_bytes(b.getvalue()))
Пример #3
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
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
Пример #5
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
Пример #6
0
    def convertFromEphemDate( ephem_date ):
        dateValues = list( ephem_date.tuple( ) )

        dateValues.append( int( fmul( fsub( dateValues[ 5 ], floor( dateValues[ 5 ] ) ), 1000000 ) ) )
        dateValues[ 5 ] = int( floor( dateValues[ 5 ] ) )

        return RPNDateTime( *dateValues )
Пример #7
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
Пример #8
0
def getSigma( target ):
    '''
    Returns the sum of the divisors of n, including 1 and n.

    http://math.stackexchange.com/questions/22721/is-there-a-formula-to-calculate-the-sum-of-all-proper-divisors-of-a-number
    '''
    n = floor( target )

    if real( n ) == 0:
        return 0
    elif n == 1:
        return 1

    factors = getECMFactors( n ) if g.ecm else getFactors( n )

    result = 1

    for factor in factors:
        numerator = fsub( power( factor[ 0 ], fadd( factor[ 1 ], 1 ) ), 1 )
        denominator = fsub( factor[ 0 ], 1 )
        #debugPrint( 'sigma', numerator, denominator )
        result = fmul( result, fdiv( numerator, denominator ) )

        if result != floor( result ):
            raise ValueError( 'insufficient precision for \'sigma\', increase precision (-p))' )

    return result
Пример #9
0
def getECMFactors( target ):
    from pyecm import factors

    n = int( floor( target ) )

    verbose = g.verbose
    randomSigma = True
    asymptoticSpeed = 10
    processingPower = 1.0

    if n < -1:
        return [ ( -1, 1 ) ] + getECMFactors( fneg( n ) )
    elif n == -1:
        return [ ( -1, 1 ) ]
    elif n == 0:
        return [ ( 0, 1 ) ]
    elif n == 1:
        return [ ( 1, 1 ) ]

    if verbose:
        print( '\nfactoring', n, '(', int( floor( log10( n ) ) ), ' digits)...' )

    if g.factorCache is None:
        loadFactorCache( )

    if n in g.factorCache:
        if verbose and n != 1:
            print( 'cache hit:', n )
            print( )

        return g.factorCache[ n ]

    result = [ ]

    for factor in factors( n, verbose, randomSigma, asymptoticSpeed, processingPower ):
        result.append( factor )

    result = [ int( i ) for i in result ]

    largeFactors = list( collections.Counter( [ i for i in result if i > 65535 ] ).items( ) )
    product = int( fprod( [ power( i[ 0 ], i[ 1 ] ) for i in largeFactors ] ) )

    save = False

    if product not in g.factorCache:
        g.factorCache[ product ] = largeFactors
        save = True

    result = list( collections.Counter( result ).items( ) )

    if n > g.minValueToCache and n not in g.factorCache:
        g.factorCache[ n ] = result
        g.factorCacheIsDirty = True

    if verbose:
        print( )

    return result
Пример #10
0
    def convertFromEphemDate(ephemDate):
        dateValues = list(ephemDate.tuple())

        dateValues.append(
            int(fmul(fsub(dateValues[5], floor(dateValues[5])), 1000000)))
        dateValues[5] = int(floor(dateValues[5]))
        # We always pass UTC time to ephem, so we'll expect UTC back
        dateValues.append(tz.gettz('UTC'))

        return RPNDateTime(*dateValues)
Пример #11
0
def continued(x, n):
    l = []
    q = mpmath.floor(x)
    for i in range(n - 1):
        # x = bq + r
        b = mpmath.floor(x / q)
        l.append(b)
        r = x - b * q
        x, q = q, r
    return l
Пример #12
0
def getFactors(target):
    if target < -1:
        result = [-1]
        result.extend(getFactors(fneg(target)))
        return result

    if target == -1:
        return [-1]

    if target == 0:
        return [0]

    if target == 1:
        return [1]

    n = int(floor(target))

    setAccuracy(floor(fadd(log10(n), 2)))

    if g.factorCache is None:
        loadFactorCache()

    if not g.ignoreCache:
        if n in g.factorCache:
            if g.verbose and n != 1:
                print('cache hit:', n)
                print()

            debugPrint('\nfactor cache', n, g.factorCache[n])

            return g.factorCache[n]

    try:
        result = factorByTrialDivision(n)  # throws if n is too big

        if n > g.minValueToCache and n not in g.factorCache:
            g.factorCache[n] = result

        return result

    except ValueError:
        pass

    if g.useYAFU and n > g.minValueForYAFU:
        result = runYAFU(n)
    else:
        result = factorise(int(n))

    if n > g.minValueToCache:
        if g.ignoreCache or (not g.ignoreCache and n not in g.factorCache):
            debugPrint('\ncaching factors of ', n, result)
            g.factorCache[n] = result

    return result
Пример #13
0
def _fmod(x, y):
    """
    returns x - n * y, where n is the quotient of x / y, rounded
    towards zero to an integer.
    """
    fquot = mpmath.mpf(x) / y
    if fquot < 0:
        n = -mpmath.floor(-fquot)
    else:
        n = mpmath.floor(fquot)
    return x - n * y
Пример #14
0
def _fmod(x, y):
    """
    returns x - n * y, where n is the quotient of x / y, rounded
    towards zero to an integer.
    """
    fquot = mpmath.mpf(x) / y
    if fquot < 0:
        n = -mpmath.floor(-fquot)
    else:
        n = mpmath.floor(fquot)
    return x - n * y
Пример #15
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))
Пример #16
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]
Пример #17
0
def getNthStern( n ):
    """Return the nth number of Stern's diatomic series recursively"""
    if real_int( n ) < 0:
        raise ValueError( 'non-negative, real integer expected' )

    if n in [ 0, 1 ]:
        return n
    elif n % 2 == 0: # even
        return getNthStern( floor( fdiv( n, 2 ) ) )
    else:
        return fadd( getNthStern( floor( fdiv( fsub( n, 1 ), 2 ) ) ),
                     getNthStern( floor( fdiv( fadd( n, 1 ), 2 ) ) ) )
Пример #18
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 )
	def reduce_to_fpp(self,z):
		# TODO: need to check what happens here when periods are infinite.
		from mpmath import floor, matrix, lu_solve
		T1, T2 = self.periods
		R1, R2 = T1.real, T2.real
		I1, I2 = T1.imag, T2.imag
		A = matrix([[R1,R2],[I1,I2]])
		b = matrix([z.real,z.imag])
		x = lu_solve(A,b)
		N = int(floor(x[0]))
		M = int(floor(x[1]))
		alpha = x[0] - N
		beta = x[1] - M
		assert(alpha >= 0 and beta >= 0)
		return alpha,beta,N,M
Пример #20
0
 def reduce_to_fpp(self, z):
     # TODO: need to check what happens here when periods are infinite.
     from mpmath import floor, matrix, lu_solve
     T1, T2 = self.periods
     R1, R2 = T1.real, T2.real
     I1, I2 = T1.imag, T2.imag
     A = matrix([[R1, R2], [I1, I2]])
     b = matrix([z.real, z.imag])
     x = lu_solve(A, b)
     N = int(floor(x[0]))
     M = int(floor(x[1]))
     alpha = x[0] - N
     beta = x[1] - M
     assert (alpha >= 0 and beta >= 0)
     return alpha, beta, N, M
Пример #21
0
def getNthLucasNumber( n ):
    if real( n ) == 0:
        return 2
    elif n == 1:
        return 1
    else:
        return floor( fadd( power( phi, n ), 0.5 ) )
Пример #22
0
 def __call__(self,t):
 
   with mp.extradps(self.prec):
     t = mpf(t)
     if t == 0:
       print "ERROR:   Inverse transform can not be calculated for t=0"
       return ("Error");
           
     N = 2*self.N
     # Initiate the stepsize (mit aktueller Präsision)
     h = 2*pi/N
  
   # The for loop is evaluating the Laplace inversion at each point theta i
   #   which is based on the trapezoidal rule
     ans =  0.0
     for k in range(self.N):
       theta = -pi + (k+0.5)*h
       z = self.shift + N/t*(Talbot.c1*theta/tan(Talbot.c2*theta) - Talbot.c3 + Talbot.c4*theta)
       dz = N/t * (-Talbot.c1*Talbot.c2*theta/sin(Talbot.c2*theta)**2 + Talbot.c1/tan(Talbot.c2*theta)+Talbot.c4)
       v1 = exp(z*t)*dz
       prec = floor(max(log10(abs(v1)),0))
       with mp.extradps(prec):
         value = self.F(z)
       ans += v1*value
           
     return ((h/pi)*ans).imag
Пример #23
0
def getNthKFibonacciNumber( n, k ):
    if real( n ) < 0:
        raise ValueError( 'non-negative argument expected' )

    if real( k ) < 2:
        raise ValueError( 'argument <= 2 expected' )

    if n < k - 1:
        return 0

    nth = int( n ) + 4

    precision = int( fdiv( fmul( n, k ), 8 ) )

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

    poly = [ 1 ]
    poly.extend( [ -1 ] * int( k ) )

    roots = polyroots( poly )
    nthPoly = getNthFibonacciPolynomial( k )

    result = 0
    exponent = fsum( [ nth, fneg( k ), -2 ] )

    for i in range( 0, int( k ) ):
        result += fdiv( power( roots[ i ], exponent ), polyval( nthPoly, roots[ i ] ) )

    return floor( fadd( re( result ), fdiv( 1, 2 ) ) )
Пример #24
0
def getMPFIntegerAsString( n ):
    '''Turns an mpmath mpf integer value into a string for use by lexicographic
    operators.'''
    if n == 0:
        return '0'
    else:
        return nstr( nint( n ), int( floor( log10( n ) + 10  ) ) )[ : -2 ]
Пример #25
0
def logSpaceAdd(update, before):
    '''
	Assume a >= b

	We want to calculate ln(exp(ln(a))+exp(ln(b))), thus
	ln(
	exp(ln(b))*(1+exp(ln(a)-ln(b)))
	)
	->
	ln(b) + ln(1+exp(ln(a)-ln(b)))
	->
	ln(b) + ln1p(exp(ln(a)-ln(b)))
	'''
    #As there is no neutral element of addition in log space we only start adding when two values are given
    if before == None:
        return update
    else:
        a = None
        b = None
        #Check which value is larger
        if update > before:
            b = update
            a = before
        else:
            b = before
            a = update

        x = mp.mpf(a) - mp.mpf(b)
        #print(update,before)
        xexp = memoexp(x)
        #print('Exp:',xexp)
        val = memolog1p(xexp)
        #print('Log:',val)
        val = val + b
        if val == 0:
            print('a:{} b:{} x:{} xexp:{} log1p:{}'.format(a, b, x, xexp, val))
            raise ValueError(
                'LogSpace Addition has resulted in a value of 0: a = {} b = {} (possible underflow)'
                .format(a, b))
        #elif val > 0:
        #print('a:{} b:{} x:{} xexp:{} log1p:{}'.format(a,b,x,xexp,val))
        #raise ValueError('Prior Update has resulted in a value > 0: a = {} b = {} val = {}'.format(a,b,val))

        if before == val:
            #print('a:{} b:{} x:{} xexp:{} log1p:{}'.format(a,b,x,xexp,val))
            logging.warning(
                'LogAddition had no effect: a = {} b = {} val = {}'.format(
                    a, b, val))
            #raise ValueError('LogAddition had no effect: a = {} b = {} val = {}'.format(a,b,val))
            #raise ValueError('LogAddition had no effect!')

        if mp.isnan(val):
            raise ValueError(
                'LogSpace Addition has resulted in a value of nan: a = {} b = {}'
                .format(a, b))

        if mp.fabs(val) > 1000:  #At this point who cares let's round a bit
            val = mp.floor(val)

        return val
Пример #26
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( )
Пример #27
0
def getNthOctagonalHeptagonalNumberOperator(n):
    return nint(
        floor(
            fdiv(
                fmul(fadd(17, fmul(sqrt(30), 2)),
                     power(fadd(sqrt(5), sqrt(6)), fsub(fmul(8, n), 6))),
                480)))
Пример #28
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
Пример #29
0
def getNthOctagonalTriangularNumber( n ):
    sign = power( -1, real( n ) )

    return nint( floor( fdiv( fmul( fsub( 7, fprod( [ 2, sqrt( 6 ), sign ] ) ),
                                    power( fadd( sqrt( 3 ), sqrt( 2 ) ),
                                           fsub( fmul( 4, real_int( n ) ), 2 ) ) ),
                              96 ) ) )
Пример #30
0
def getNthDecagonalCenteredSquareNumberOperator(n):
    sqrt10 = sqrt(10)

    dps = 7 * int(n)

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

    return nint(
        floor(
            fsum([
                fdiv(1, 8),
                fmul(fdiv(7, 16),
                     power(fsub(721, fmul(228, sqrt10)), fsub(n, 1))),
                fmul(
                    fmul(fdiv(1, 8),
                         power(fsub(721, fmul(228, sqrt10)), fsub(n, 1))),
                    sqrt10),
                fmul(
                    fmul(fdiv(1, 8),
                         power(fadd(721, fmul(228, sqrt10)), fsub(n, 1))),
                    sqrt10),
                fmul(fdiv(7, 16),
                     power(fadd(721, fmul(228, sqrt10)), fsub(n, 1)))
            ])))
Пример #31
0
def calc_lambda_psi(psi, ups_r, r1, r2, r3, r4, En, slr, ecc):
    """
    changes lambda(r) -> lambda(psi) by computing lambda(r(psi))

    Parameters:
        psi (float): radial angle
        ups_r (float): radial Mino frequency
        r1 (float): radial root
        r2 (float): radial root
        r3 (float): radial root
        r4 (float): radial root
        En (float): energy
        slr (float): semi-latus rectum
        ecc (float): eccentricity

    Returns:
        r (float): radius
        lambda_psi (float)
    """
    pi = mp.pi
    r = calc_radius(psi, slr, ecc)
    lam_r = 2 * pi / ups_r  # radial period
    lam_r1 = calc_lambda_r(r2, r1, r2, r3, r4, En)
    turns = floor(psi / (2 * pi))
    if (psi % (2 * pi)) <= pi:
        res = calc_lambda_r(r, r1, r2, r3, r4, En) - lam_r1
    else:
        res = lam_r1 - calc_lambda_r(r, r1, r2, r3, r4, En)

    return r, lam_r * turns + res
Пример #32
0
def getMPFIntegerAsString(n):
    '''Turns an mpmath mpf integer value into a string for use by lexicographic
    operators.'''
    if n == 0:
        return '0'

    return nstr(nint(n), int(floor(log10(n) + 10)))[:-2]
Пример #33
0
    def _w_tilde(self, u_bar):
        """Compute w_tilde, the threshold for the word-length w such that
		MSB = computeNaiveMSB    if w >= w_tilde
		MSB = computeNaiveMSB+1  if w < w_tilde
		(this doesn't count into account the roundoff error, as in FxPF)
		See ARITH26 paper
		Parameters:
			- u_bar: vector of bounds on the inputs of the system
		Returns: a vector of thresholds w_tilde

		We use:  w_tilde = 1 + ceil(log2(zeta_bar)) - floor(log2( 2^ceil(log2(zeta_bar)) - zeta_bar ))
		with zeta_bar = <<Hzeta>>.u_bar
		"""
        #TODO: test if zeta_bar is a power of 2 (should be +Inf in that case)
        zeta_bar = self.Hzeta.WCPG() * u_bar

        with mpmath.workprec(500):  # TODO: compute how many bit we need !!
            wtilde = [
                int(1 + mpmath.ceil(mpmath.log(x[0], 2)) - mpmath.floor(
                    mpmath.log(
                        mpmath.power(2, mpmath.ceil(mpmath.log(x[0], 2))) -
                        x[0], 2))) for x in zeta_bar.tolist()
            ]

        return wtilde
Пример #34
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]
Пример #35
0
def getNthNonagonalOctagonalNumber( n ):
    sqrt6 = sqrt( 6 )
    sqrt7 = sqrt( 7 )

    return nint( floor( fdiv( fmul( fsub( fmul( 11, sqrt7 ), fmul( 9, sqrt6 ) ),
                                    power( fadd( sqrt6, sqrt7 ), fsub( fmul( 8, real_int( n ) ), 5 ) ) ),
                              672 ) ) )
Пример #36
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()
Пример #37
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 ]
Пример #38
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 ) )
Пример #39
0
def getNthNonagonalHeptagonalNumberOperator(n):
    sqrt35 = sqrt(35)

    return nint(
        floor(
            fdiv(
                fmul(fadd(39, fmul(4, sqrt35)),
                     power(fadd(6, sqrt35), fsub(fmul(4, n), 3))), 560)))
Пример #40
0
def real_int( n ):
    if im( n ) != 0:
        raise ValueError( 'real argument expected ({})'.format( n ) )

    if n != floor( n ):
        raise ValueError( 'integer argument expected ({})'.format( n ) )

    return int( n )
Пример #41
0
def getNthDecagonalTriangularNumberOperator(n):
    return nint(
        floor(
            fdiv(
                fmul(fadd(9, fprod([4, sqrt(2),
                                    power(-1, fadd(n, 1))])),
                     power(fadd(1, sqrt(2)), fsub(fmul(4, fadd(n, 1)), 6))),
                64)))
Пример #42
0
def duplicateOperation( valueList ):
    if g.duplicateOperations > 0:
        raise ValueError( "'dupop' must be followed by another operation" )

    if isinstance( valueList[ -1 ], list ):
        raise ValueError( "'dupop' cannot accept a list argument" )

    g.duplicateOperations = nint( floor( valueList.pop( ) ) )
Пример #43
0
def getNthOctagonalTriangularNumberOperator(n):
    sign = power(-1, n)

    return nint(
        floor(
            fdiv(
                fmul(fsub(7, fprod([2, sqrt(6), sign])),
                     power(fadd(sqrt(3), sqrt(2)), fsub(fmul(4, n), 2))), 96)))
Пример #44
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)
Пример #45
0
def getNthNonagonalPentagonalNumber( n ):
    sqrt21 = sqrt( 21 )
    sign = power( -1, real_int( n ) )

    return nint( floor( fdiv( fprod( [ fadd( 25, fmul( 4, sqrt21 ) ),
                                       fsub( 5, fmul( sqrt21, sign ) ),
                                       power( fadd( fmul( 2, sqrt( 7 ) ), fmul( 3, sqrt( 3 ) ) ),
                                              fsub( fmul( 4, n ), 4 ) ) ] ),
                              336 ) ) )
Пример #46
0
def getNthNonagonalOctagonalNumberOperator(n):
    sqrt6 = sqrt(6)
    sqrt7 = sqrt(7)

    return nint(
        floor(
            fdiv(
                fmul(fsub(fmul(11, sqrt7), fmul(9, sqrt6)),
                     power(fadd(sqrt6, sqrt7), fsub(fmul(8, n), 5))), 672)))
Пример #47
0
def addDigits(n, k):
    digits = int(k)

    if digits == 0:
        digitCount = 1
    else:
        digitCount = int(fadd(floor(log10(k)), 1))

    return appendDigits(n, digits, digitCount)
Пример #48
0
def mpmsb(value, signed):
    if isinstance(value, Interval):
        return np.max([mpmsb(value.lower_bound, signed=signed),
                       mpmsb(value.upper_bound, signed=signed)])
    if value > 0:
        return int(mpmath.floor(mpmath.log(value, 2))) + int(signed)
    if value < 0:
        return int(mpmath.ceil(mpmath.log(-value, 2)))
    return -np.inf
Пример #49
0
def getNthDecagonalNonagonalNumber( n ):
    dps = 8 * int( real_int( n ) )

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

    return nint( floor( fdiv( fmul( fadd( 15, fmul( 2, sqrt( 14 ) ) ),
                                    power( fadd( fmul( 2, sqrt( 2 ) ), sqrt( 7 ) ),
                                           fsub( fmul( 8, n ), 6 ) ) ), 448 ) ) )
Пример #50
0
def getNthDecagonalHeptagonalNumber( n ):
    sqrt10 = sqrt( 10 )

    return nint( floor( fdiv( fprod( [ fsub( 11,
                                             fmul( fmul( 2, sqrt10 ),
                                                   power( -1, real_int( n ) ) ) ),
                                       fadd( 1, sqrt10 ),
                                       power( fadd( 3, sqrt10 ),
                                              fsub( fmul( 4, n ), 3 ) ) ] ), 320 ) ) )
Пример #51
0
def _mp_round(n):
    ceil = mp.ceil(n)
    floor = mp.floor(n)
    ceil_diff = mp.fabs(n - ceil)
    floor_diff = mp.fabs(n - floor)
    if ceil_diff <= floor_diff:
        return ceil
    else:
        return floor
Пример #52
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
Пример #53
0
def real_int( n ):
    '''Validates that a value is a real integer and throws an error if it
    isn't.'''
    if im( n ) != 0:
        raise ValueError( 'real argument expected ({})'.format( n ) )

    if n != floor( n ):
        raise ValueError( 'integer argument expected ({})'.format( n ) )

    return int( n )
Пример #54
0
def convertToNonintegerBase( num, base ):
    epsilon = power( 10, -( mp.dps - 3 ) )
    minPlace = -( floor( mp.dps / log( base ) ) )

    output = ''
    integer = ''

    remaining = num

    # find starting place
    place = int( floor( log( remaining, base ) ) )

    while remaining > epsilon:
        if place < minPlace:
            break

        if place == -1:
            integer = output
            output = ''

        placeValue = power( base, place )

        value = fdiv( remaining, placeValue )

        value = fmul( value, power( 10, mp.dps - 3 ) )
        value = nint( value )
        value = fdiv( value, power( 10, mp.dps - 3 ) )

        value = floor( value )
        remaining = chop( fsub( remaining, fmul( placeValue, value ) ) )

        output += str( value )[ : -2 ]

        place -= 1

    if place >= 0:
        integer = output + '0' * ( place + 1 )
        output = ''

    if integer == '':
        return output, ''
    else:
        return integer, output
Пример #55
0
def hash():
    seed = int(mpmath.floor(random.random() * 32)) + 32

    def r(str):
        result = 1
        for i in range(1, len(str)):
            result = (seed * result + ord(str[i])) & 0xFFFFFFFF
        return result

    return r
Пример #56
0
    def __init__( self, value, maxterms = 15, cutoff = 1e-10 ):
        if isinstance( value, ( int, float, mpf ) ):
            value = mpmathify( value )
            remainder = floor( value )
            self.append( remainder )

            while len( self ) < maxterms:
                value -= remainder

                if value > cutoff:
                    value = fdiv( 1, value )
                    remainder = floor( value )
                    self.append( remainder )
                else:
                    break

        elif isinstance( value, ( list, tuple ) ):
            self.extend( value )
        else:
            raise ValueError( 'RPNContinuedFraction requires a number or a list' )
Пример #57
0
 def G(self,s): # Laplace-Transform
   zz = 2*self.v + 2 + s
   mu = sqrt(self.v**2+2*zz)
   a  = mu/2 - self.v/2 - 1
   b  = mu/2 + self.v/2 + 2
   v1 = (2*self.alp)**(-a)*gamma(b)/gamma(mu+1)/(zz*(zz - 2*(1 + self.v)))
   prec = floor(max(log10(abs(v1)),mp.dps))+self.prec
   # additional precision needed for computation of hyp1f1
   with mp.extradps(prec):
     value = hyp1f1(a,mu + 1,self.beta)*v1
   return value
Пример #58
0
    def exponentiate( self, exponent ):
        if ( floor( exponent ) != exponent ):
            raise ValueError( 'cannot raise a measurement to a non-integral power' )

        exponent = int( exponent )
        newValue = power( self.value, exponent )

        for unit in self.units:
            self.units[ unit ] *= exponent

        return RPNMeasurement( newValue, self.units )
Пример #59
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