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 iterSomeSignedMidPoints(N): """Iter some particular values (mid-point between two consecutive signed FxP number with w bits) Returns the wordlength, string and mpf value""" # ordinary case: +/- (M+0.5)2^l, with (2^(w-1))+2 <= M <= 2^w - 2 for _ in range(N): w = randint(8,200) l = randint(-50,50) M = randint( 2**(w-1)+2, 2**w-2) st = "(%d+0.5)2^%d" % (M,l) mp = ldexp(fadd(M, 0.5, exact=True),l) yield w, st, mp # 2^m+2^(l-1) (so exactly the mid-point between 2^m-2^l and 2^m) for _ in range(N): w = randint(8,200) l = randint(-50, 50) m = w + l - 1 st = "2^%d-2^%d" % (m,l-1) mp = fadd(ldexp(1,m), ldexp(1,l-1), exact=True) yield w, st, mp # -2^m-2^l (so exactly the mid-point between -2^m and -2^m-2^(l+1)) for _ in range(N): w = randint(8,200) l = randint(-50, 50) m = w + l - 1 st = "-2^%d-2^%d" % (m,l) mp = fadd(ldexp(-1,m), ldexp(-1,l), exact=True) yield w, st, mp
def getEclipseTotality( body1, body2, location, date ): '''Returns the angular size of an astronomical object in radians.''' if isinstance( location, str ): location = getLocation( location ) if not isinstance( body1, RPNAstronomicalObject ) or not isinstance( body2, RPNAstronomicalObject ) and \ not isinstance( location, RPNLocation ) or not isinstance( date, RPNDateTime ): raise ValueError( 'expected two astronomical objects, a location and a date-time' ) separation = body1.getAngularSeparation( body2, location, date ).value radius1 = body1.getAngularSize( ).value radius2 = body2.getAngularSize( ).value if separation > fadd( radius1, radius2 ): return 0 distance1 = body1.getDistanceFromEarth( date ) distance2 = body2.getDistanceFromEarth( date ) area1 = fmul( pi, power( radius1, 2 ) ) area2 = fmul( pi, power( radius2, 2 ) ) area_of_intersection = fadd( getCircleIntersectionTerm( radius1, radius2, separation ), getCircleIntersectionTerm( radius2, radius1, separation ) ) if distance1 > distance2: result = fdiv( area_of_intersection, area1 ) else: result = fdiv( area_of_intersection, area2 ) if result > 1: return 1 else: return result
def getRobbinsConstant( ): robbins = fsub( fsub( fadd( 4, fmul( 17, sqrt( 2 ) ) ), fmul( 6, sqrt( 3 ) ) ), fmul( 7, pi ) ) robbins = fdiv( robbins, 105 ) robbins = fadd( robbins, fdiv( log( fadd( 1, sqrt( 2 ) ) ), 5 ) ) robbins = fadd( robbins, fdiv( fmul( 2, log( fadd( 2, sqrt( 3 ) ) ) ), 5 ) ) return robbins
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
def convertToFibBase(value): ''' Returns a string with Fibonacci encoding for n (n >= 1). adapted from https://en.wikipedia.org/wiki/Fibonacci_coding ''' result = '' n = value if n >= 1: a = 1 b = 1 c = fadd(a, b) # next Fibonacci number fibs = [b] # list of Fibonacci numbers, starting with F(2), each <= n while n >= c: fibs.append(c) # add next Fibonacci number to end of list a = b b = c c = fadd(a, b) for fibnum in reversed(fibs): if n >= fibnum: n = fsub(n, fibnum) result = result + '1' else: result = result + '0' return result
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))) ])))
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
def getNthSchroederHipparchusNumber( n ): result = 0 for i in arange( n ): result = fadd( result, fmul( getNarayanaNumber( n, fadd( i, 1 ) ), power( 2, i ) ) ) return result
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)))
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)))
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
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)))
def add( self, other ): if isinstance( other, RPNMeasurement ): if self.units == other.units: return RPNMeasurement( fadd( self.value, other.value ), self.units ) else: return RPNMeasurement( fadd( self.value, other.convertValue( self ) ), self.units ) else: return RPNMeasurement( fadd( self.value, other ), self.units )
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 ) )
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 ) ) )
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 ) ) )
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 ) ) )
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))
def to_dTFmp(self, prec=64): """ This function computes corresponding transfer function in multiple precision. All operations are performed with at leaste prec bits of precision for mantissas. Parameters ---------- prec - precision for the computations Returns ------- TF - a dTFmp object """ # converting the dSS matrices to mp type oldprec = mpmath.mp.prec mpmath.mp.prec = prec from fixif.LTI import dTFmp if self.p != 1 or self.q != 1: raise ValueError('dSS: cannot convert a dSSmp to dTFmp for not a SISO system') E, V = mpmath.mp.eig(self.A) # eig returns a list E and a matrix V Cmp = self.C * V Vinv = mpmath.mp.inverse(V) Bmp = Vinv * self.B Q = mp_poly_product([-e for e in E]) PP = mpmath.mp.zeros(Q.rows - 1, 1) # tmp_polyproduct = mp.zeros([self.n, 1]) #temporary polynomial products for i in range(0, self.n): # P = sum_i=0^n c_i * b_i * product_j!=i p_j tmp_polyproduct = mp_poly_product([-e for e in E], i) PP = PP + Cmp[0, i] * Bmp[i, 0] * tmp_polyproduct if self.D[0, 0] != mpmath.mp.zero: P = self.D[0, 0] * Q else: P = mpmath.mp.zeros(Q.rows, 1) for i in range(1, P.rows): P[i, 0] = P[i, 0] + PP[i - 1, 0] b = mpmath.mp.zeros(P.rows, 1) a = mpmath.mp.zeros(Q.rows, 1) for i in range(0, P.rows): b[i, 0] = P[i, 0].real b[i, 0] = mpmath.fadd(b[i, 0], mpmath.mp.zero, prec=prec) for i in range(0, Q.rows): a[i, 0] = Q[i, 0].real a[i, 0] = mpmath.fadd(a[i, 0], mpmath.mp.zero, prec=prec) mpmath.mp.prec = oldprec return dTFmp(b, a)
def add(self, other): if isinstance(other, RPNMeasurement): if self.units == other.units: return RPNMeasurement(fadd(self.value, other.value), self.units) return RPNMeasurement(fadd(self.value, other.convertValue(self)), self.units) return RPNMeasurement(fadd(self.value, other), self.units)
def getCumulativeListMeans( args ): mean = None for index, i in enumerate( args ): if mean is None: mean = i else: mean = fdiv( fadd( fmul( mean, index ), i ), fadd( index, 1 ) ) yield mean
def getNthNonagonalTriangularNumber( n ): a = fmul( 3, sqrt( 7 ) ) b = fadd( 8, a ) c = fsub( 8, a ) return nint( fsum( [ fdiv( 5, 14 ), fmul( fdiv( 9, 28 ), fadd( power( b, real_int( n ) ), power( c, n ) ) ), fprod( [ fdiv( 3, 28 ), sqrt( 7 ), fsub( power( b, n ), power( c, n ) ) ] ) ] ) )
def move_point(self, point): ''' moves point in the direction and magnitude of this vector :param point: point to move yimath.Point :return: yipmath.Point ''' a = mpmath.fadd(self.x, point.x) b = mpmath.fadd(self.y, point.y) c = mpmath.fadd(self.z, point.z) return Point([a, b, c])
def main(): parser = argparse.ArgumentParser(description='Design Serial Diode') parser.add_argument('Vs', type=float, help='Voltage supply') parser.add_argument('Id', type=float, help='Desired current over the diode in Amps') parser.add_argument( 'Is', type=float, nargs='?', default=1e-12, help='Diode Saturation current in Amps (default = 1e-12)') parser.add_argument('N', type=float, nargs='?', default=1, help='Emission Coefficient (default = 1)') parser.add_argument('--Vt', type=float, default=0.026, help='Thermal Voltage in Volts (default = 0.026)') parser.add_argument('-g', '--graph', action='store_true', help='Draw a graph') parser.add_argument('-v', '--verbose', action='store_true', help='Print debug') args = parser.parse_args() Vs = args.Vs Id = args.Id Is = args.Is N = args.N Vt = args.Vt nVt = N * Vt if args.verbose: logging.basicConfig(format='%(levelname)s|%(message)s', level=logging.INFO) logging.info(f'Vs: {Vs}, Id: {Id}, Is: {Is}, N: {N}, Vt: {Vt}') Vd = fmul(log(fadd(fdiv(Id, Is), mpf(1))), nVt) VR = fsub(Vs, Vd) IR = Id R = fdiv(VR, IR) print("VR: {}, IR: {}, R: {}".format(VR, IR, R)) print("Vd: {}, Id: {}, Rd: {}".format(Vd, Id, fdiv(Vd, Id))) if args.graph: plot([ lambda x: fsub(Vs, fmul(x, R)), lambda x: fmul(nVt, log(fadd(fdiv(x, Is), 1))) ], [0, fdiv(Vs, R)], [0, Vs])
def getNthDecagonalHeptagonalNumberOperator(n): sqrt10 = sqrt(10) return nint( floor( fdiv( fprod([ fsub(11, fmul(fmul(2, sqrt10), power(-1, n))), fadd(1, sqrt10), power(fadd(3, sqrt10), fsub(fmul(4, n), 3)) ]), 320)))
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 ) ) ) )
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 ) )
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
def getNthDecagonalCenteredSquareNumber( n ): sqrt10 = sqrt( 10 ) dps = 7 * int( real_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 ) ) ) ] ) ) )
def add( self, other ): if isinstance( other, RPNMeasurement ): if self.getUnits( ) == other.getUnits( ): return RPNMeasurement( fadd( self.value, other.value ), self.getUnits( ), self.getUnitName( ), self.getPluralUnitName( ) ) else: newOther = other.convertValue( self ) return RPNMeasurement( fadd( self.value, newOther ), self.getUnits( ), self.getUnitName( ), self.getPluralUnitName( ) ) else: return RPNMeasurement( fadd( self.value, other ), self.getUnits( ), self.getUnitName( ), self.getPluralUnitName( ) )
def getNthNonagonalSquareNumberOperator(n): p = fsum([fmul(8, sqrt(7)), fmul(9, sqrt(14)), fmul(-7, sqrt(2)), -28]) q = fsum([fmul(7, sqrt(2)), fmul(9, sqrt(14)), fmul(-8, sqrt(7)), -28]) sign = power(-1, n) index = fdiv( fsub( fmul(fadd(p, fmul(q, sign)), power(fadd(fmul(2, sqrt(2)), sqrt(7)), n)), fmul(fsub(p, fmul(q, sign)), power(fsub(fmul(2, sqrt(2)), sqrt(7)), fsub(n, 1)))), 112) return nint(power(nint(index), 2))
def getNthNonagonalPentagonalNumberOperator(n): sqrt21 = sqrt(21) sign = power(-1, 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)))
def getNthDecagonalNonagonalNumberOperator(n): dps = 8 * 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)))
def rangeGenerator(start, end, step): if start > end and step > 0: step = -step current = start if step > 0: while current <= end: yield current current = fadd(current, step) else: while current >= end: yield current current = fadd(current, step)
def getNthNonagonalSquareNumber( n ): if real( n ) < 0: ValueError( '' ) p = fsum( [ fmul( 8, sqrt( 7 ) ), fmul( 9, sqrt( 14 ) ), fmul( -7, sqrt( 2 ) ), -28 ] ) q = fsum( [ fmul( 7, sqrt( 2 ) ), fmul( 9, sqrt( 14 ) ), fmul( -8, sqrt( 7 ) ), -28 ] ) sign = power( -1, real_int( n ) ) index = fdiv( fsub( fmul( fadd( p, fmul( q, sign ) ), power( fadd( fmul( 2, sqrt( 2 ) ), sqrt( 7 ) ), n ) ), fmul( fsub( p, fmul( q, sign ) ), power( fsub( fmul( 2, sqrt( 2 ) ), sqrt( 7 ) ), fsub( n, 1 ) ) ) ), 112 ) return nint( power( nint( index ), 2 ) )
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
def rangeGenerator( start, end, step ): if start > end and step > 0: step = -step current = start if ( step > 0 ): while ( current <= end ): yield current current = fadd( current, step ) else: while ( current >= end ): yield current current = fadd( current, step )
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
def calculateMolarMass(n): result = 0 for atom in n: result = fadd(result, fmul(getAtomicWeight(atom), n[atom])) return RPNMeasurement(result, 'gram')
def getNSphereRadius( n, k ): if real_int( k ) < 3: raise ValueError( 'the number of dimensions must be at least 3' ) if not isinstance( n, RPNMeasurement ): return RPNMeasurement( n, 'meter' ) dimensions = n.getDimensions( ) if dimensions == { 'length' : 1 }: return n elif dimensions == { 'length' : int( k - 1 ) }: m2 = n.convertValue( RPNMeasurement( 1, [ { 'meter' : int( k - 1 ) } ] ) ) result = root( fdiv( fmul( m2, gamma( fdiv( k, 2 ) ) ), fmul( 2, power( pi, fdiv( k, 2 ) ) ) ), fsub( k, 1 ) ) return RPNMeasurement( result, [ { 'meter' : 1 } ] ) elif dimensions == { 'length' : int( k ) }: m3 = n.convertValue( RPNMeasurement( 1, [ { 'meter' : int( k ) } ] ) ) result = root( fmul( fdiv( gamma( fadd( fdiv( k, 2 ), 1 ) ), power( pi, fdiv( k, 2 ) ) ), m3 ), k ) return RPNMeasurement( result, [ { 'meter' : 1 } ] ) else: raise ValueError( 'incompatible measurement type for computing the radius: ' + str( dimensions ) )
def packInteger( values, fields ): if isinstance( values, RPNGenerator ): return packInteger( list( values ), fields ) elif not isinstance( values, list ): return unpackInteger( [ values ], fields ) if isinstance( fields, RPNGenerator ): return packInteger( values, list( fields ) ) elif not isinstance( fields, list ): return unpackInteger( values, [ fields ] ) if isinstance( values[ 0 ], list ): return [ unpackInteger( value, fields ) for value in values ] result = 0 count = min( len( values ), len( fields ) ) size = 0 for i in range( count, 0, -1 ): result = fadd( result, fmul( values[ i - 1 ], power( 2, size ) ) ) size += fields[ i - 1 ] return result
def generateSquareDigitChainGenerator(n): n = int(n) chain = [] if n == 0: yield 0 return if n == 1: yield 1 return done = False while not done: digits = getDigitList(n) n = 0 for i in digits: n = fadd(n, pow(i, 2)) if n in chain: done = True else: chain.append(n) yield n
def getKSphereRadius(n, k): if k < 3: raise ValueError('the number of dimensions must be at least 3') if not isinstance(n, RPNMeasurement): return RPNMeasurement(n, 'meter') dimensions = n.getDimensions() if dimensions == {'length': 1}: return n if dimensions == {'length': int(k - 1)}: area = n.convertValue(RPNMeasurement(1, [{'meter': int(k - 1)}])) result = root( fdiv(fmul(area, gamma(fdiv(k, 2))), fmul(2, power(pi, fdiv(k, 2)))), fsub(k, 1)) return RPNMeasurement(result, [{'meter': 1}]) if dimensions == {'length': int(k)}: volume = n.convertValue(RPNMeasurement(1, [{'meter': int(k)}])) result = root( fmul(fdiv(gamma(fadd(fdiv(k, 2), 1)), power(pi, fdiv(k, 2))), volume), k) return RPNMeasurement(result, [{'meter': 1}]) raise ValueError( 'incompatible measurement type for computing the radius: ' + str(dimensions))
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
def sumDigits(n): result = 0 for c in getMPFIntegerAsString(n): result = fadd(result, int(c)) return result
def isPerfectDigitalInvariant(n): digits = getDigitList(n) exponent = 1 oldTotal = 0 while True: total = 0 for digit in digits: total = fadd(total, power(digit, exponent)) if total > n: return 0 if total == n: return 1 if total == oldTotal: return 0 oldTotal = total exponent += 1
def generateIntegerArgument( range = [ 0, 1_000_000_000 ], allowNegative = True ): factor = 1 if allowNegative and getRandomInteger( 2 ) == 1: factor = -1 return str( fmul( fadd( getRandomInteger( range[ 1 ] ), range[ 0 ] ), factor ) )
def calculateMolarMass( n ): result = 0 for atom in n: result = fadd( result, fmul( getAtomicWeight( atom ), n[ atom ] ) ) return RPNMeasurement( result, 'gram' )
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
def getPrimeRange( start, end ): result = list( ) for i in getNthPrimeRange( start, fadd( fsub( end, start ), 1 ) ): result.append( i ) return result
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
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 ) ) )
def packInteger(values, fields): if isinstance(values, RPNGenerator): return packInteger(list(values), fields) if not isinstance(values, list): return unpackInteger([values], fields) if isinstance(fields, RPNGenerator): return packInteger(values, list(fields)) if not isinstance(fields, list): return unpackInteger(values, [fields]) if isinstance(values[0], list): return [unpackInteger(value, fields) for value in values] result = 0 count = min(len(values), len(fields)) size = 0 for i in range(count, 0, -1): field = int(fields[i - 1]) value = int(values[i - 1]) & (2**field - 1) result = fadd(result, fmul(value, power(2, size))) size += field return result
def getNthLucasNumber( n ): if real( n ) == 0: return 2 elif n == 1: return 1 else: return floor( fadd( power( phi, n ), 0.5 ) )
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)))
def get_prob_poisson(events, length, rate): """ P(k, lambda = t * rate) = """ avg_events = mpmath.fmul(rate, length) # lambda prob = mpmath.fmul((-1), avg_events) for i in range(1, events + 1): prob = mpmath.fadd(prob, mpmath.log(mpmath.fdiv(avg_events, i))) prob = mpmath.exp(prob) return prob
def mpf_matrix_fadd(A, B): """ Given a m x n matrix A and m x n matrix B either in numpy.matrix or mpmath.matrix format, this function computes the sum C = A + B exactly. The output matrix C is always given in the MPMATH format. Parameters ---------- A - m x n matrix B - m x n matrix Returns ------- C - m x n matrix """ if isinstance(A, numpy.matrix): try: A = python2mpf_matrix(A) except ValueError as e: raise ValueError('Cannot compute exact sum of two matrices. %s' % e) else: if not isinstance(A, mpmath.matrix): raise ValueError('Cannot compute exact sum of two matrices: unexpected input type, excpected numpy.matrix or mpmath.matrix but got %s') %type(A) if isinstance(B, numpy.matrix): try: B = python2mpf_matrix(B) except ValueError as e: raise ValueError('Cannot compute exact sum of two matrices. %s' % e) else: if not isinstance(B, mpmath.matrix): raise ValueError('Cannot compute exact sum of two matrices: unexpected input type, excpected numpy.matrix or mpmath.matrix but got %s') % type(B) #here both A and B are mpmath matrices #we consider that A and B are MPF matrices if their first elements are of type mpf, let's test it if not isinstance(A[0,0], mpmath.mpf) or not isinstance(B[0,0], mpmath.mpf): raise ValueError('Cannot compute exact product of two matrices: cannot sum complex matrices.') #test sizes if A.rows != B.rows or A.cols != B.cols: raise ValueError('Cannot compute exact sum of two matrices: incorrect sizes.') m = A.rows n = A.cols C = mp.zeros(m, n) for i in range(0, m): for j in range(0, n): C[i,j] = mpmath.fadd(A[i,j], B[i,j], exact=True) if mpmath.isnan(C[i,j]) or mpmath.isinf(C[i,j]): print('WARNING: in matrix sum an abnormal number (NaN/Inf) occured: %f' % C[i,j]) return C
def generate(c, num_iterations=200): orbit_re = [] orbit_im = [] z = mpmath.mpc(real='0.0', imag='0.0') for _ in range(num_iterations): z = mpmath.fadd(mpmath.fmul(z, z), c) orbit_re.append(mpmath.nstr(mpmath.re(z))) orbit_im.append(mpmath.nstr(mpmath.im(z))) return [orbit_re, orbit_im]