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 getSkyLocation( n, k ): if not isinstance( n, ephem.Body ) or not isinstance( k, RPNDateTime ): raise ValueError( '\'sky_location\' expects an astronomical object and a date-time' ) n.compute( k.to( 'utc' ).format( ) ) return [ fdiv( fmul( mpmathify( n.ra ), 180 ), pi ), fdiv( fmul( mpmathify( n.dec ), 180 ), pi ) ]
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 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 vector(self): return Vector([ mpmath.fdiv(self._params[0], self._params[3]), mpmath.fdiv(self._params[1], self._params[3]), mpmath.fdiv(self._params[2], self._params[3]) ])
def extrapolateTransitiveConversions( op1, op2, unitTypeTable, unitType, unitConversionMatrix ): newConversions = { } for op3 in unitTypeTable[ unitType ]: # we can ignore duplicate operators if op3 in [ op1, op2 ]: continue # we can shortcut if the types are not compatible if unitOperators[ op3 ].unitType != unitOperators[ op1 ].unitType: continue conversion = unitConversionMatrix[ ( op1, op2 ) ] if ( op1, op3 ) not in unitConversionMatrix and \ ( op2, op3 ) in unitConversionMatrix: # print( 'transitive: ', ( op2, op3 ), # unitConversionMatrix[ ( op2, op3 ) ] ) newConversion = fmul( conversion, unitConversionMatrix[ ( op2, op3 ) ] ) # print( ( op1, op3 ), newConversion ) newConversions[ ( op1, op3 ) ] = newConversion # print( ( op3, op1 ), fdiv( 1, newConversion ) ) newConversions[ ( op3, op1 ) ] = fdiv( 1, newConversion ) elif ( op2, op3 ) not in unitConversionMatrix and \ ( op1, op3 ) in unitConversionMatrix: # print( 'transitive: ', ( op1, op3 ), # unitConversionMatrix[ ( op1, op3 ) ] ) newConversion = fdiv( unitConversionMatrix[ ( op1, op3 ) ], conversion ) # print( ( op2, op3 ), newConversion ) newConversions[ ( op2, op3 ) ] = newConversion # print( ( op3, op2 ), fdiv( 1, newConversion ) ) newConversions[ ( op3, op2 ) ] = fdiv( 1, newConversion ) return newConversions
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 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 calculateDistance( measurement1, measurement2 ): validUnitTypes = [ [ 'length', 'time' ], [ 'velocity', 'time' ], [ 'acceleration', 'time' ], [ 'jerk', 'time' ], [ 'jounce', 'time' ] ] arguments = matchUnitTypes( [ measurement1, measurement2 ], validUnitTypes ) if not arguments: raise ValueError( '\'distance\' requires specific measurement types (see help)' ) time = arguments[ 'time' ] if 'length' in arguments: distance = arguments[ 'length' ] elif 'acceleration' in arguments: # acceleration and time distance = getProduct( [ fdiv( 1, 2 ), arguments[ 'acceleration' ], time, time ] ) elif 'jerk' in arguments: # jerk and time distance = calculateDistance( getProduct( [ fdiv( 1, 2 ), arguments[ 'jerk' ], time ] ), time ) elif 'jounce' in arguments: # jounce and time distance = calculateDistance( getProduct( [ fdiv( 1, 2 ), arguments[ 'jounce' ], time ] ), time ) else: # velocity and time distance = multiply( arguments[ 'velocity' ], time ) return distance.convert( 'meter' )
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
def cont_frac_expansion_sqrt(n): """ n is NOT square e.g. 2 --> (1,2) (2 repeats) """ if is_square(n): return 0 seq = [] r = mp.sqrt(n,prec=1000) # DOESNT MATTER? a = floor(r) fls = [r] seq.append(int(a)) r = mp.fdiv(1.,mp.fsub(r,a,prec=1000),prec=1000) a = floor(r) fls.append(r) seq.append(int(a)) r = mp.fdiv(1.,mp.fsub(r,a,prec=1000),prec=1000) #THESE TWO MATTER!!! a = floor(r) fls.append(r) seq.append(int(a)) while not close(r, fls[1]): r = mp.fdiv(1.,mp.fsub(r,a,prec=1000),prec=1000) #THESE TWO MATTER!!! a = floor(r) fls.append(r) seq.append(int(a)) # print seq seq.pop() return seq
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 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 RD_new(self, i): RD_curr = self.RD_j()[i][1] RD_prime = mp.sqrt( mp.fdiv(1, mp.fdiv(1, RD_curr**2) + mp.fdiv(1, self.d_sq(i)**2))) return RD_prime
def extrapolateTransitiveConversions(op1, op2, unitTypeTable, unitType, unitConversionMatrix): newConversions = {} for op3 in unitTypeTable[unitType]: # we can ignore duplicate operators if op3 in [op1, op2]: continue conversion = unitConversionMatrix[(op1, op2)] if ( op1, op3 ) not in unitConversionMatrix and \ ( op2, op3 ) in unitConversionMatrix: # print( 'transitive: ', ( op2, op3 ), # unitConversionMatrix[ ( op2, op3 ) ] ) newConversion = fmul(conversion, unitConversionMatrix[(op2, op3)]) # print( ( op1, op3 ), newConversion ) newConversions[(op1, op3)] = newConversion # print( ( op3, op1 ), fdiv( 1, newConversion ) ) newConversions[(op3, op1)] = fdiv(1, newConversion) elif ( op2, op3 ) not in unitConversionMatrix and \ ( op1, op3 ) in unitConversionMatrix: # print( 'transitive: ', ( op1, op3 ), # unitConversionMatrix[ ( op1, op3 ) ] ) newConversion = fdiv(unitConversionMatrix[(op1, op3)], conversion) # print( ( op2, op3 ), newConversion ) newConversions[(op2, op3)] = newConversion # print( ( op3, op2 ), fdiv( 1, newConversion ) ) newConversions[(op3, op2)] = fdiv(1, newConversion) return newConversions
def findCenteredPolygonalNumber( n, k ): if real_int( k ) < 3: raise ValueError( 'the number of sides of the polygon cannot be less than 3,' ) s = fdiv( k, 2 ) return nint( fdiv( fadd( sqrt( s ), sqrt( fsum( [ fmul( 4, real( n ) ), s, -4 ] ) ) ), fmul( 2, sqrt( s ) ) ) )
def getLocationInfo( location ): if isinstance( location, str ): location = getLocation( location ) elif not isinstance( location. RPNLocation ): raise ValueError( 'location name or location object expected' ) return [ fdiv( fmul( mpmathify( location.observer.lat ), 180 ), pi ), fdiv( fmul( mpmathify( location.observer.long ), 180 ), pi ) ]
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 getSkyLocation( n, k ): '''Returns the location of an astronomical object in the sky in terms of right ascension and declination.''' if not isinstance( n, ephem.Body ) or not isinstance( k, RPNDateTime ): raise ValueError( '\'sky_location\' expects an astronomical object and a date-time' ) n.compute( k.to( 'utc' ).format( ) ) return [ fdiv( fmul( mpmathify( n.ra ), 180 ), pi ), fdiv( fmul( mpmathify( n.dec ), 180 ), pi ) ]
def char_fun(u, mu, sigma, lemu, lemd, etau, etad, T, S0): lem = lemu + lemd #Define net arrival rate for up and down jumps p = lemu / lem #Conditional probability of an up jump given that a jump is happening charac_exp = -0.5 * (sigma**2) * (u**2) + mp.mpc(0, 1) * mu * u + mp.mpc( 0, 1) * u * lem * (mp.fdiv(p, etau - mp.mpc(0, 1) * u) - mp.fdiv( 1 - p, etad + mp.mpc(0, 1) * u)) #Characteristic expression phiT = mp.exp(mp.mpc(0, 1) * u * mp.log(S0)) * mp.exp( T * charac_exp) #Characteristic function return phiT
def point(self): if mpmath.almosteq(self._params[3], mpmath.mpf(1)): return Point([self._params[0], self._params[1], self._params[2]]) return Point([ mpmath.fdiv(self._params[0], self._params[3]), mpmath.fdiv(self._params[1], self._params[3]), mpmath.fdiv(self._params[2], self._params[3]) ])
def divide(self, other): if isinstance(other, RPNMeasurement): factor, newUnits = self.units.combineUnits(other.units.inverted()) newUnits = RPNMeasurement(1, newUnits).simplifyUnits().units return RPNMeasurement(fmul(fdiv(self.value, other.value), factor), newUnits).normalizeUnits() return RPNMeasurement(fdiv(self.value, other), self.units).normalizeUnits()
def getLocationInfoOperator(location): if isinstance(location, str): location = getLocation(location) elif not isinstance(location, RPNLocation): raise ValueError('location name or location object expected') return [ fdiv(fmul(mpmathify(location.observer.lat), 180), pi), fdiv(fmul(mpmathify(location.observer.long), 180), pi) ]
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 expandDataUnits( ): # expand data measurements for all prefixes newConversions = { } for dataUnit in dataUnits: unitInfo = unitOperators[ dataUnit ] for prefix in dataPrefixes: newName = prefix[ 0 ] + dataUnit # constuct unit operator info helpText = '\n\'Using the standard SI prefixes, ' + newName + '\' is the equivalent\nof ' + \ '{:,}'.format( 10 ** prefix[ 2 ] ) + ' times the value of \'' + dataUnit + \ '\'.\n\nPlease see the help entry for \'' + dataUnit + '\' for more information.' if unitInfo.abbrev: newAbbrev = prefix[ 0 ] + unitInfo.abbrev else: newAbbrev = '' unitOperators[ newName ] = \ RPNUnitInfo( unitInfo.unitType, prefix[ 0 ] + unitInfo.plural, newAbbrev, [ ], unitInfo.categories, helpText, True ) # create new conversions newConversion = power( 10, mpmathify( prefix[ 2 ] ) ) newConversions[ ( newName, dataUnit ) ] = newConversion newConversion = fdiv( 1, newConversion ) newConversions[ ( dataUnit, newName ) ] = newConversion for prefix in binaryPrefixes: newName = prefix[ 0 ] + dataUnit # constuct unit operator info helpText = '\n\'Using the binary data size prefixes, ' + newName + '\' is the equivalent\nof 2^' + \ str( prefix[ 2 ] ) + ' times the value of \'' + dataUnit + \ '\'.\n\nPlease see the help entry for \'' + dataUnit + '\' for more information.' if unitInfo.abbrev: newAbbrev = prefix[ 0 ] + unitInfo.abbrev else: newAbbrev = '' unitOperators[ newName ] = \ RPNUnitInfo( unitInfo.unitType, prefix[ 0 ] + unitInfo.plural, newAbbrev, [ ], unitInfo.categories, helpText, True ) # create new conversions newConversion = power( 2, mpmathify( prefix[ 2 ] ) ) newConversions[ ( newName, dataUnit ) ] = newConversion newConversion = fdiv( 1, newConversion ) newConversions[ ( dataUnit, newName ) ] = newConversion return newConversions
def getAngularSize( self, location=None, date=None ): if location and date: if isinstance( location, str ): location = getLocation( location ) location.observer.date = date.to( 'utc' ).format( ) self.object.compute( location.observer ) # I have no idea why size seems to return the value in arcseconds... that # goes against the pyephem documentation that it always uses radians for angles. return RPNMeasurement( mpmathify( fdiv( fmul( fdiv( self.object.size, 3600 ), pi ), 180 ) ), 'radian' )
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 expandDataUnits(): # expand data measurements for all prefixes newConversions = {} for dataUnit in dataUnits: unitInfo = unitOperators[dataUnit] for prefix in dataPrefixes: newName = prefix[0] + dataUnit # constuct unit operator info helpText = '\n\'Using the standard SI prefixes, ' + newName + '\' is the equivalent\nof ' + \ '{:,}'.format( 10 ** prefix[ 2 ] ) + ' times the value of \'' + dataUnit + \ '\'.\n\nPlease see the help entry for \'' + dataUnit + '\' for more information.' if unitInfo.abbrev: newAbbrev = prefix[0] + unitInfo.abbrev else: newAbbrev = '' unitOperators[ newName ] = \ RPNUnitInfo( unitInfo.unitType, prefix[ 0 ] + unitInfo.plural, newAbbrev, [ ], unitInfo.categories, helpText, True ) # create new conversions newConversion = power(10, mpmathify(prefix[2])) newConversions[(newName, dataUnit)] = newConversion newConversion = fdiv(1, newConversion) newConversions[(dataUnit, newName)] = newConversion for prefix in binaryPrefixes: newName = prefix[0] + dataUnit # constuct unit operator info helpText = '\n\'Using the binary data size prefixes, ' + newName + '\' is the equivalent\nof 2^' + \ str( prefix[ 2 ] ) + ' times the value of \'' + dataUnit + \ '\'.\n\nPlease see the help entry for \'' + dataUnit + '\' for more information.' if unitInfo.abbrev: newAbbrev = prefix[0] + unitInfo.abbrev else: newAbbrev = '' unitOperators[ newName ] = \ RPNUnitInfo( unitInfo.unitType, prefix[ 0 ] + unitInfo.plural, newAbbrev, [ ], unitInfo.categories, helpText, True ) # create new conversions newConversion = power(2, mpmathify(prefix[2])) newConversions[(newName, dataUnit)] = newConversion newConversion = fdiv(1, newConversion) newConversions[(dataUnit, newName)] = newConversion return newConversions
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 getAntiprismSurfaceArea( n, k ): if real( n ) < 3: raise ValueError( 'the number of sides of the prism cannot be less than 3,' ) if not isinstance( k, RPNMeasurement ): return getAntiprismSurfaceArea( n, RPNMeasurement( real( k ), 'meter' ) ) if k.getDimensions( ) != { 'length' : 1 }: raise ValueError( '\'antiprism_area\' argument 2 must be a length' ) result = getProduct( [ fdiv( n, 2 ), fadd( cot( fdiv( pi, n ) ), sqrt( 3 ) ), getPower( k, 2 ) ] ) return result.convert( 'meter^2' )
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 isFriendly( n ): first = True abundance = 0 for i in n: if first: abundance = fdiv( getSigma( i ), i ) first = False elif fdiv( getSigma( i ), i ) != abundance: return 0 return 1
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 getRegularPolygonArea( n, k ): if real( n ) < 3: raise ValueError( 'the number of sides of the polygon cannot be less than 3,' ) if not isinstance( k, RPNMeasurement ): return getRegularPolygonArea( n, RPNMeasurement( real( k ), 'meter' ) ) dimensions = k.getDimensions( ) if dimensions != { 'length' : 1 }: raise ValueError( '\'polygon_area\' argument 2 must be a length' ) return multiply( fdiv( n, fmul( 4, tan( fdiv( pi, n ) ) ) ), getPower( k, 2 ) ).convert( 'meter^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 getAntiprismVolumeOperator(n, k): result = getProduct([ fdiv( fprod([ n, sqrt(fsub(fmul(4, cos(cos(fdiv(pi, fmul(n, 2))))), 1)), sin(fdiv(fmul(3, pi), fmul(2, n))) ]), fmul(12, sin(sin(fdiv(pi, n))))), sin(fdiv(fmul(3, pi), fmul(2, n))), getPower(k, 3) ]) return result.convert('meter^3')
def divide( self, other ): if isinstance( other, RPNMeasurement ): newValue = fdiv( self.value, other.value ) factor, newUnits = combineUnits( self.getUnits( ), other.getUnits( ).inverted( ) ) self = RPNMeasurement( fmul( newValue, factor ), newUnits ) else: newValue = fdiv( self.value, other ) self = RPNMeasurement( newValue, self.getUnits( ), self.getUnitName( ), self.getPluralUnitName( ) ) return self.normalizeUnits( )
def getPartitionNumber( n ): ''' This version is, um, less recursive than the original, which I've kept. The strategy is to create a list of the smaller partition numbers we need to calculate and then start calling them recursively, starting with the smallest. This will minimize the number of recursions necessary, and in combination with caching values, will calculate practically any integer partition without the risk of a stack overflow. I can't help but think this is still grossly inefficient compared to what's possible. It seems that using this algorithm, calculating any integer partition ends up necessitating calculating the integer partitions of every integer smaller than the original argument. ''' debugPrint( 'partition', int( n ) ) if real_int( n ) < 0: raise ValueError( 'non-negative argument expected' ) elif n in ( 0, 1 ): return 1 sign = 1 i = 1 k = 1 estimate = log10( fdiv( power( e, fmul( pi, sqrt( fdiv( fmul( 2, n ), 3 ) ) ) ), fprod( [ 4, n, sqrt( 3 ) ] ) ) ) if mp.dps < estimate + 5: mp.dps = estimate + 5 partitionList = [ ] signList = [ ] while n - k >= 0: partitionList.append( ( fsub( n, k ), sign ) ) i += 1 if i % 2: sign *= -1 k = getNthGeneralizedPolygonalNumber( i, 5 ) partitionList = partitionList[ : : -1 ] total = 0 for partition, sign in partitionList: total = fadd( total, fmul( sign, getPartitionNumber( partition ) ) ) return total
def cheb_D(n: int) -> List[mp.mpf]: pts = cheb_pts(n) Dmat = [[0 for i in range(n)] for j in range(n)] N = n - 1 Dmat[0][0] = mp.fdiv(mp.mpf(2) * mp.power(N, 2) + mp.mpf(1), mp.mpf(6)) Dmat[N][N] = -mp.fdiv(mp.mpf(2) * mp.power(N, 2) + mp.mpf(1), mp.mpf(6)) Dmat[0][N] = mp.mpf(0.5) * mp.power(-1, N) Dmat[N][0] = -mp.mpf(0.5) * mp.power(-1, N) for i in range(1, N): Dmat[0][i] = mp.mpf(2.0) * mp.power(-1, i) * mp.fdiv( 1, mp.mpf(1) - pts[i]) Dmat[N][i] = -mp.mpf(2.0) * mp.power(-1, i + N) * mp.fdiv( 1, mp.mpf(1) + pts[i]) Dmat[i][0] = -mp.mpf(0.5) * mp.power(-1, i) * mp.fdiv( 1, mp.mpf(1) - pts[i]) Dmat[i][N] = mp.mpf(0.5) * mp.power(-1, i + N) * mp.fdiv( 1, mp.mpf(1) + pts[i]) Dmat[i][i] = -0.5 * pts[i] * mp.fdiv(1, mp.mpf(1) - mp.power(pts[i], 2)) for j in range(1, N): if i != j: Dmat[i][j] = mp.power(-1, i + j) * mp.fdiv(1, pts[i] - pts[j]) return Dmat
def solveQuadraticPolynomial( a, b, c ): if a == 0: if b == 0: raise ValueError( 'invalid expression, no variable coefficients' ) else: # linear equation, one root return [ fdiv( fneg( c ), b ) ] else: d = sqrt( fsub( power( b, 2 ), fmul( 4, fmul( a, c ) ) ) ) x1 = fdiv( fadd( fneg( b ), d ), fmul( 2, a ) ) x2 = fdiv( fsub( fneg( b ), d ), fmul( 2, a ) ) return [ x1, x2 ]
def calculateHarmonicMean( args ): if isinstance( args, RPNGenerator ): return calculateHarmonicMean( list( args ) ) elif isinstance( args, list ): if isinstance( args[ 0 ], ( list, RPNGenerator ) ): return [ calculateHarmonicMean( list( arg ) ) for arg in args ] else: sum = 0 for arg in args: sum = fadd( sum, fdiv( 1, arg ) ) return fdiv( len( args ), sum ) else: return args
def get_fit_rate(mi, prob_success): if (prob_success == 1): return 0 lna = mpmath.log(prob_success) lnasq = mpmath.fmul(lna, lna) term1 = mpmath.fdiv((mpmath.fsub(1, prob_success)), prob_success) term2 = mpmath.fdiv(term1, lnasq) mabf = term2 mtbf = mpmath.fdiv(mpmath.fmul(mabf, mi.period), 3600000) fitrate = mpmath.fdiv(1000000000, mtbf) return fitrate
def getPartitionNumber(n): ''' This version is, um, less recursive than the original, which I've kept. The strategy is to create a list of the smaller partition numbers we need to calculate and then start calling them recursively, starting with the smallest. This will minimize the number of recursions necessary, and in combination with caching values, will calculate practically any integer partition without the risk of a stack overflow. I can't help but think this is still grossly inefficient compared to what's possible. It seems that using this algorithm, calculating any integer partition ends up necessitating calculating the integer partitions of every integer smaller than the original argument. ''' debugPrint('partition', int(n)) if n in (0, 1): return 1 sign = 1 i = 1 k = 1 estimate = log10( fdiv(power(e, fmul(pi, sqrt(fdiv(fmul(2, n), 3)))), fprod([4, n, sqrt(3)]))) if mp.dps < estimate + 5: mp.dps = estimate + 5 partitionList = [] while n - k >= 0: partitionList.append((fsub(n, k), sign)) i += 1 if i % 2: sign *= -1 k = getNthGeneralizedPolygonalNumber(i, 5) partitionList = partitionList[::-1] total = 0 for partition, sign in partitionList: total = fadd(total, fmul(sign, getPartitionNumber(partition))) return total
def getSuperRootsOperator(n, k): '''Returns all the super-roots of n, not just the nice, positive, real one.''' k = fsub(k, 1) factors = [fmul(i, root(k, k)) for i in unitroots(int(k))] base = root(fdiv(log(n), lambertw(fmul(k, log(n)))), k) return [fmul(i, base) for i in factors]
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 distance_from_point(l0: Point, l1: Point, p: Point): ''' source: http://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html condition: distance l0, l1 can't be zero :param l0: :param l1: :param p: :return: ''' vec0 = Vector.create_from_points(l0, p) print("vec0", vec0) vec1 = Vector.create_from_points(l1, p) print("vec1", vec1) vec2 = Vector.create_from_points(l0, l1) print("vec2", vec2) vec_cx = vec0.cross(vec1) print("vec_cx", vec_cx) num_sq = vec_cx.dot(vec_cx) den_sq = vec2.dot(vec2) print("N:", num_sq) print("D:", den_sq) dist_sq = mpmath.fdiv(num_sq, den_sq) return mpmath.sqrt(dist_sq)
def getCombinationsOperator(n, r): if r > n: raise ValueError( 'number of elements {0} cannot exceed the size of the set {1}'. format(r, n)) return fdiv(fac(n), fmul(fac(fsub(n, r)), fac(r)))
def get_cycle_len(i): s = str(mp.fdiv(1, i, dps=100)) print(s) for j in range(7, 12): if s[4:j + 4] == s[j + 4:j + j + 4]: return j return 0
def compute_single_item_loss_list(u, node_capacity, n_seats, p0): u_to_the_n = math.power(u, node_capacity) C_fact = math.factorial(n_seats) C_to_the_n_minus_c = math.power(n_seats, (node_capacity - n_seats)) denominator = math.fmul(C_fact, C_to_the_n_minus_c) fraction = math.fdiv(u_to_the_n, denominator) return math.fmul(fraction, p0)
def pade_m(coef, e, m): # Calculation of analitical function on a arbitrary mesh for a given Pade coefficient # and first known momenta of function # e - energy mesh (can be complex or real) # coef - Pade coefficients # m - first three momenta of function nlines = len(e) r = len(coef) / 2 f = mp.zeros(nlines, 1) pq = mp.ones(r * 2 + 1, 1) # for i in range(0, r): # pq[i] = coef[i] # pq[i + r] = coef[i + r] for iw in range(0, nlines): p = mp.mpc(0.0) q = mp.mpc(0.0) for i in range(0, r): p += coef[i] * e[iw]**i for i in range(0, r + 1): q += coef[i + r] * e[iw]**i f[iw] = fdiv(p, q) # f[iw] = np.divide(p, q) f[iw] /= e[iw]**3 f[iw] += m[0] / e[iw] + m[1] / (e[iw]**2) + m[2] / (e[iw]**3) f = fp.matrix(f) return f
def divide( n, k ): if isinstance( n, RPNMeasurement ): return n.divide( k ) elif isinstance( k, RPNMeasurement ): return RPNMeasurement( n ).divide( k ) else: return fdiv( n, k )
def compute_formula_second_term(u_divided_by_nseat, node_capacity, n_seats, u): u_to_c_over_c_fact = math.fdiv(math.power(u, n_seats), math.factorial(n_seats)) second_fraction = 0 if u_divided_by_nseat == 1: second_fraction = node_capacity - n_seats + 1 else: u_div_C_to_K_minus_C_plus1 = math.power(u_divided_by_nseat, (node_capacity - n_seats + 1)) one_minus_u_div_C = math.fsub(1, u_divided_by_nseat) second_fraction_numerator = math.fsub(1, u_div_C_to_K_minus_C_plus1) second_fraction = math.fdiv(second_fraction_numerator, one_minus_u_div_C) return math.fmul(u_to_c_over_c_fact, second_fraction)
def combineUnits(self, units): if not g.unitConversionMatrix: loadUnitConversionMatrix() newUnits = RPNUnits(self) factor = mpmathify(1) for unit2 in units: if unit2 in newUnits: newUnits[unit2] += units[unit2] else: for unit1 in self: if unit1 == unit2: newUnits[unit2] += units[unit2] break if getUnitType(unit1) == getUnitType(unit2): factor = fdiv( factor, pow( mpmathify(g.unitConversionMatrix[(unit1, unit2)]), units[unit2])) newUnits[unit1] += units[unit2] break else: newUnits[unit2] = units[unit2] #print( 'newUnits', newUnits ) return factor, newUnits
def calculateHarmonicMean( args ): if isinstance( args, RPNGenerator ): return calculateHarmonicMean( list( args ) ) if isinstance( args, list ): if isinstance( args[ 0 ], ( list, RPNGenerator ) ): return [ calculateHarmonicMean( list( arg ) ) for arg in args ] result = 0 for arg in args: result = fadd( result, fdiv( 1, arg ) ) return fdiv( len( args ), result ) return args
def pade(coef, e): # Calculation of analitical function on a arbitrary mesh for a given Pade coefficient # e - energy mesh (can be complex or real) # coef - Pade coefficients nlines = len(e) r = len(coef) // 2 f = mp.zeros(nlines, 1) # pq = mp.ones(r * 2 + 1, 1) # for i in range(0, r): # pq[i] = coef[i] # pq[i + r] = coef[i + r] for iw in range(0, nlines): p = mp.mpc(0.0) q = mp.mpc(0.0) for i in range(0, r): p += coef[i] * e[iw]**i for i in range(0, r): # print(i, r, i+r) q += coef[i + r] * e[iw]**i # f[iw] = np.divide(p, q) f[iw] = fdiv(p, q) f = fp.matrix(f) return f
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)))