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 expectResult( command, expected ): if g.testFilter: if g.testFilter not in command: return if g.timeIndividualTests: startTime = time.process_time( ) print( 'rpn', command ) result = rpn( shlex.split( command + ' -I' ) )[ 0 ] compare = None if isinstance( expected, list ): compare = [ ] for i in expected: if isinstance( i, ( int, float, complex ) ): compare.append( mpmathify( i ) ) else: compare.append( i ) else: if isinstance( expected, ( int, float, complex ) ): compare = mpmathify( expected ) else: compare = expected compareResults( result, compare ) print( ' test passed!' ) if g.timeIndividualTests: print( 'Test complete. Time elapsed: {:.3f} seconds'.format( time.process_time( ) - startTime ) ) print( '' )
def f(x, y, z): x = mp.mpmathify(x) y = mp.mpmathify(y) z = mp.mpmathify(z) R = radius(x, y, z) # solving 0 division problem here if x == 0 and z == 0 or y == 0: part1 = mp.mpmathify(0) else: part1 = mp.mpf('0.5') * y * (mp.power(z, 2) - mp.power( x, 2)) * mp.asinh(y / (mp.sqrt(mp.power(x, 2) + mp.power(z, 2)))) if x == 0 and y == 0 or z == 0: part2 = 0 else: part2 = mp.mpf('0.5') * z * (mp.power(y, 2) - mp.power( x, 2)) * mp.asinh(z / (mp.sqrt(mp.power(x, 2) + mp.power(y, 2)))) if x == 0 or y == 0 or z == 0: part3 = 0 else: part3 = x * y * z * mp.atan((y * z) / (x * R)) # solving 0 division problem here part4 = mp.mpf('1 / 6') * R * (2 * mp.power(x, 2) - mp.power(y, 2) - mp.power(z, 2)) return mp.mpmathify(part1 + part2 - part3 + part4)
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 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 simulate_single(self, energy, rate): if energy <= self.axion_mass: return br = mpmathify(self.branching_ratio(energy, self.axion_coupling)) axion_p = mp.sqrt(energy**2 - self.axion_mass**2) axion_v = mpmathify(axion_p / energy) axion_boost = mpmathify(energy / self.axion_mass) tau = mpmathify(64 * pi / (self.axion_coupling**2 * self.axion_mass**3) * axion_boost) surv_prob = mp.exp(-self.detector_distance / meter_by_mev / axion_v / tau) decay_in_detector = fsub( 1, mp.exp(-self.detector_length / meter_by_mev / axion_v / tau)) self.axion_velocity.append(axion_v) self.axion_energy.append(energy) self.axion_flux.append(rate * br / (4 * pi * self.detector_distance**2)) self.decay_axion_weight.append(rate * br * surv_prob * decay_in_detector / (4 * pi * self.detector_distance**2)) self.scatter_axion_weight.append(surv_prob * rate * br / (4 * pi * self.detector_distance**2))
def convertToBase10( integer, mantissa, inputRadix ): result = mpmathify( 0 ) base = mpmathify( 1 ) validNumerals = g.numerals[ : inputRadix ] for i in range( len( integer ) - 1, -1, -1 ): digit = validNumerals.find( integer[ i ] ) if digit == -1: raise ValueError( 'invalid numeral \'%c\' for base %d' % ( integer[ i ], inputRadix ) ) result += digit * base base *= inputRadix base = fdiv( 1, inputRadix ) for i in range( 0, len( mantissa ) ): digit = validNumerals.find( mantissa[ i ] ) if digit == -1: raise ValueError( 'invalid numeral \'%c\' for base %d' % ( mantissa[ i ], inputRadix ) ) result += digit * base base /= inputRadix return result
def stringExpressionValid(str): try: mpmath.mpmathify(str) return True except Exception as err: print(err) return False
def times_a(array1, array2): from mpmath import mp as math math.prec = 200 a1 = list(array1) a2 = list(array2) output = [math.fmul(math.mpmathify(a1[i]),math.mpmathify(a2[i])) for i in range(len(a1))] return output
def create_hexagonal_grid_nearestN(origin, d, point, N): """ Create a new coherent basis with basis states on a hexagonal grid. As basis states the nearest N grid points to the center are choosen. *Arguments* * *origin* A complex number defining the origin of the grid. * *d* A real number defining the lattice constant. * *point* A complex number used as reference point to which the nearest N lattice points are selected. * *N* An integer giving the number of basis states. """ origin = mpmath.mpmathify(origin) point = mpmath.mpmathify(point) d = mpmath.mpf(d) lat = lattice.HexagonalLattice(d, origin, dtype=mpmath.mpf) lat.select_nearestN(point, N) return CoherentBasis(lat)
def combineUnits( self, units ): if not g.unitConversionMatrix: loadUnitConversionMatrix( ) newUnits = RPNUnits( self ) factor = mpmathify( 1 ) for unit2 in units: if unit2 in newUnits: newUnits[ unit2 ] += units[ unit2 ] else: for unit1 in self: if unit1 == unit2: newUnits[ unit2 ] += units[ unit2 ] break elif getUnitType( unit1 ) == getUnitType( unit2 ): factor = fdiv( factor, pow( mpmathify( g.unitConversionMatrix[ ( unit1, unit2 ) ] ), units[ unit2 ] ) ) newUnits[ unit1 ] += units[ unit2 ] break else: newUnits[ unit2 ] = units[ unit2 ] #print( 'newUnits', newUnits ) return factor, newUnits
def convertToBase10(integer, mantissa, inputRadix): result = mpmathify(0) base = mpmathify(1) validNumerals = g.numerals[:inputRadix] for i in range(len(integer) - 1, -1, -1): digit = validNumerals.find(integer[i]) if digit == -1: raise ValueError('invalid numeral \'%c\' for base %d' % (integer[i], inputRadix)) result += digit * base base *= inputRadix base = fdiv(1, inputRadix) for i, numeral in enumerate(mantissa): digit = validNumerals.find(numeral) if digit == -1: raise ValueError('invalid numeral \'%c\' for base %d' % (mantissa[i], inputRadix)) result += digit * base base /= inputRadix 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 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 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 wme_gen(f, pYs_p, pZs_p, X, alpha, g_p, delta=0): # convert probabilities to mpmath.mpf pYs = [{k: mpmath.mpmathify(pY[k]) for k in pY} for pY in pYs_p] pZs = [{k: mpmath.mpmathify(pZ[k]) for k in pZ} for pZ in pZs_p] g = {w: {y: mpmath.mpmathify(g_p[w][y]) for y in g_p[w]} for w in g_p} delta = mpmath.mpmathify(delta) # precondition # bypass precondition if number of arguments == 0, i.e. if f is defined as a function of another function if len(X) + len(pYs) + len(pZs) != len(inspect.getargspec(f)[0]) and len( inspect.getargspec(f)[0]) != 0: sys.exit( "Aborted: Number of function arguments and inputs didn't match") if len(inspect.getargspec(f)[0]) == 0: try: a = f(*((0, ) * (len(X) + len(pYs) + len(pZs)))) except KeyError: # here we tolerate KeyError because merged functions might not recognise input (0, 0, ...) pass except: sys.exit( "Aborted: Number of function arguments and inputs didn't match" ) # joint distribution for Output and Y pOaY = dict() for Y in itertools.product(*pYs): for Z in itertools.product(*pZs): o = f(*(X + Y + Z)) p_o = prod((pYZ[yz] for (yz, pYZ) in zip(Y + Z, pYs + pZs))) # critical for distributions with a zero probability! # next line ensures that only possible events appear in pO (the if) if p_o > 0: if o in pOaY: if Y in pOaY[o]: pOaY[o][Y] += p_o else: pOaY[o][Y] = p_o else: pOaY[o] = {Y: p_o} # W[o] is the vector inside the norm (over guesses w) W = dict() for o in pOaY: W[o] = [ sum(pOaY[o][Y] * g[w][Y] for Y in g[w] if Y in pOaY[o]) + delta for w in g ] if alpha == -1: sum_o = sum(max(W[o]) for o in pOaY) result = -mpmath.log(sum_o, b=2) else: sum_o = sum(p_norm(W[o], alpha) for o in pOaY) result = (alpha / (1 - alpha)) * mpmath.log(sum_o, b=2) return result
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 getAzimuthAndAltitude( self, location=None, date=None ): if location and date: if isinstance( location, str ): location = getLocation( location ) location.observer.date = date.to( 'utc' ).format( ) self.object.compute( location.observer ) return RPNMeasurement( mpmathify( self.object.az ), 'radians' ), \ RPNMeasurement( mpmathify( self.object.alt ), 'radians' )
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 getAzimuthAndAltitude( self, location=None, date=None ): if location and date: if isinstance( location, str ): location = getLocation( location ) location.observer.date = date.to( 'utc' ).format( ) self.object.compute( location.observer ) return RPNMeasurement( mpmathify( self.object.az ), 'radians' ), \ RPNMeasurement( mpmathify( self.object.alt ), 'radians' ) return self.getAzimuthAndAltitude( )
def doubledouble2string(doubdoub,n=19): """ Convert a double-double tuple into a string with n decimal digits of precision. Default is n=19, which is the maximum precision that this longdouble-based double-double format can provide. min_fixed is the position of the leading digit such that any number with a leading digit less than or equal to min_fixed will be written in exponential format. e.g., 0.00123 has its leading digit in the -3 place, so if min_fixed>=-3 it will be printed as 1.23e-3, and if min_fixed<=-4 it will be printed as 0.00123. """ mpmath.mp.prec=105 hi=mpmath.mpmathify(doubdoub[0]) lo=mpmath.mpmathify(doubdoub[1]) tot=mpmath.fadd(hi,lo) return mpmath.nstr(tot,n)
def doubledouble2string(doubdoub, n=19): """ Convert a double-double tuple into a string with n decimal digits of precision. Default is n=19, which is the maximum precision that this longdouble-based double-double format can provide. min_fixed is the position of the leading digit such that any number with a leading digit less than or equal to min_fixed will be written in exponential format. e.g., 0.00123 has its leading digit in the -3 place, so if min_fixed>=-3 it will be printed as 1.23e-3, and if min_fixed<=-4 it will be printed as 0.00123. """ mpmath.mp.prec = 105 hi = mpmath.mpmathify(doubdoub[0]) lo = mpmath.mpmathify(doubdoub[1]) tot = mpmath.fadd(hi, lo) return mpmath.nstr(tot, n)
def polish(self, init_shapes, flag_initial_error=True): """Use Newton's method to compute precise shapes from rough ones.""" precision = self._precision manifold = self.manifold #working_prec = precision + 32 working_prec = precision + 64 mpmath.mp.prec = working_prec target_epsilon = mpmath.mpmathify(2.0)**-precision det_epsilon = mpmath.mpmathify(2.0)**(32 - precision) #shapes = [mpmath.mpmathify(z) for z in init_shapes] shapes = mpmath.matrix(init_shapes) init_equations = manifold.gluing_equations('rect') target = mpmath.mpmathify(self.target_holonomy) error = self._gluing_equation_error(init_equations, shapes, target) if flag_initial_error and error > 0.000001: raise GoodShapesNotFound( 'Initial solution not very good: error=%s' % error) # Now begin the actual computation eqns = enough_gluing_equations(manifold) assert eqns[-1] == manifold.gluing_equations('rect')[-1] for i in range(100): errors = self._gluing_equation_errors(eqns, shapes, target) if infinity_norm(errors) < target_epsilon: break derivative = [[ int(eqn[0][i]) / z - int(eqn[1][i]) / (1 - z) for i, z in enumerate(shapes) ] for eqn in eqns] derivative[-1] = [target * x for x in derivative[-1]] derivative = mpmath.matrix(derivative) #det = derivative.matdet().abs() det = abs(mpmath.det(derivative)) if min(det, 1 / det) < det_epsilon: raise GoodShapesNotFound( 'Gluing system is too singular (|det| = %s).' % det) delta = mpmath.lu_solve(derivative, errors) shapes = shapes - delta # Check to make sure things worked out ok. error = self._gluing_equation_error(init_equations, shapes, target) #total_change = infinity_norm(init_shapes - shapes) if error > 1000 * target_epsilon: raise GoodShapesNotFound('Failed to find solution') #if flag_initial_error and total_change > pari(0.0000001): # raise GoodShapesNotFound('Moved too far finding a good solution') self.shapelist = [Number(z, precision=precision) for z in shapes]
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
def downloadOEISSequence( id ): '''Downloads and formats data from oeis.org.''' keywords = downloadOEISText( id, 'K' ).split( ',' ) # If oeis.org isn't available, just punt everything if keywords == [ '' ]: return 0 result, success = downloadOEISTable( id ) if success: return result if 'nonn' in keywords: result = downloadOEISText( id, 'S' ) result += downloadOEISText( id, 'T' ) result += downloadOEISText( id, 'U' ) else: result = downloadOEISText( id, 'V' ) result += downloadOEISText( id, 'W' ) result += downloadOEISText( id, 'X' ) if 'cons' in keywords: offset = int( downloadOEISText( id, 'O' ).split( ',' )[ 0 ] ) result = ''.join( result.split( ',' ) ) return mpmathify( result[ : offset ] + '.' + result[ offset : ] ) else: #return [ mpmathify( i ) for i in result.split( ',' ) ] return [ int( i ) for i in result.split( ',' ) ]
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 downloadOEISSequence(aNumber): '''Downloads and formats data from oeis.org.''' keywords = downloadOEISText(aNumber, 'K').split(',') # If oeis.org isn't available, just punt everything if keywords == ['']: return 0 result, success = downloadOEISTable(aNumber) if success: return result if 'nonn' in keywords: result = downloadOEISText(aNumber, 'S') result += downloadOEISText(aNumber, 'T') result += downloadOEISText(aNumber, 'U') else: result = downloadOEISText(aNumber, 'V') result += downloadOEISText(aNumber, 'W') result += downloadOEISText(aNumber, 'X') if 'cons' in keywords: offset = int(downloadOEISText(aNumber, 'O').split(',')[0]) result = ''.join(result.split(',')) return mpmathify(result[:offset] + '.' + result[offset:]) # return [ mpmathify( i ) for i in result.split( ',' ) ] return [int(i) for i in result.split(',')]
def nu_linregress(x, y): """ Refactor of the scipy linregress with numba and less checks for speed sake :param x: array for independent :param y: :return: """ cols = ['slope', 'intercept', 'rvalue', 'pvalue', 'stderr'] #LinregressResult = namedtuple('LinregressResult', cols) #TINY = 1.0e-20 x = np.asarray(x) y = np.asarray(y) arr = np.array([x, y]) n = len(x) xmean = np.mean(x, None) ymean = np.mean(y, None) # average sum of squares: ssxm, ssxym, ssyxm, ssym = (np.dot(arr, arr.T) / n).flat r_num = mp.mpmathify(ssxym) r_den = mp.sqrt(ssxm * ssym) r = r_num / r_den # test for numerical error propagation if r > 1.0: r = 1.0 elif r < -1.0: r = -1.0 df = n - 2 slope = r_num / ssxm intercept = ymean - slope * xmean t = r * np.sqrt(df / ((1.0 - r) * (1.0 + r))) prob = t_sf(np.abs(t), df) sterrest = np.sqrt((1 - r**2) * ssym / ssxm / df) return dict(zip(cols, [slope, intercept, r, prob, sterrest]))
def create_hexagonal_grid_rings(center, d, rings): """ Create a new coherent basis with basis states on a hexagonal grid. The basis states are choosen in rings around the center on a hexagonal grid with lattice constant d. *Arguments* * *center* A complex number defining the center of the rings. * *d* A real number defining the lattice constant. * *rings* An integer giving the number of rings. """ center = mpmath.mpmathify(center) d = mpmath.mpf(d) lat = lattice.HexagonalLattice(d, center, dtype=mpmath.mpf) for i in range(-rings,rings+1): if i<0: start = -rings-i end = rings else: start = -rings end = rings-i for j in range(start,end+1): lat.select((i, j)) return CoherentBasis(lat)
def lifeDist(vMin=-35, vMax=15, tMin=14, tMax=17, mean=0, sigma=14): V = (mpmathify(10**(vMin)), mpmathify(10**(vMax))) t = (mpmathify(10**(tMin)), mpmathify(10**(tMax))) mp.dps = 230 val = mpf('1') r = np.random.lognormal(mean, sigma) #r = np.random.normal(mean,sigma) val *= r val *= sampleU(V) val *= sampleU(t) val = 0 - val expo = mp.exp(val) val = mpf('1') - expo mp.dps = 15 return val
def getRightTruncations( n ): if n < 0: raise ValueError( '\'get_right_truncations\' requires a positive argument' ) str = getMPFIntegerAsString( n ) for i in range( len( str ), 0, -1 ): yield mpmathify( str[ 0 : i ] )
def getLeftTruncations( n ): if n < 0: raise ValueError( '\'get_left_truncations\' requires a positive argument' ) str = getMPFIntegerAsString( n ) for i, e in enumerate( str ): yield mpmathify( str[ i : ] )
def runYAFU(n): fullOut = subprocess.run([ g.userConfiguration['yafu_path'] + os.sep + g.userConfiguration['yafu_binary'], '-xover', '120' ], input='factor(' + str(int(n)) + ')\n', encoding='ascii', stdout=subprocess.PIPE, cwd=g.userConfiguration['yafu_path'], check=True).stdout #print( 'out', fullOut ) out = fullOut[fullOut.find('***factors found***'):] if len(out) < 2: if log10(n) > 40: raise ValueError('yafu seems to have crashed trying to factor ' + str(int(n)) + '.\n\nyafu output follows:\n' + fullOut) debugPrint( 'yafu seems to have crashed, switching to built-in factoring code') return factorise(int(n)) result = [] while True: prime = '' out = out[out.find('P'):] if len(out) < 2: break out = out[out.find('='):] index = 2 while out[index] >= '0' and out[index] <= '9': prime += out[index] index += 1 result.append(mpmathify(prime)) if not result: raise ValueError('yafu seems to have failed.') answer = fprod(result) if answer != n: debugPrint('\nyafu has barfed') for i in result: n = fdiv(n, i) result.extend(runYAFU(n)) return sorted(result)
def sph_kn_exact(n, z): """Return the value of k_n computed using the exact formula. The expression used is http://dlmf.nist.gov/10.49.E12 . """ zm = mpmathify(z) s = sum(_a(k, n)/zm**(k+1) for k in xrange(n+1)) return pi*exp(-zm)/2*s
def getThueMorseConstant( ): result = 0 factor = mpmathify( '0.5' ) for i in arange( 0, mp.prec + 1 ): result = fadd( result, fmul( getNthThueMorseNumber( i ), factor ) ) factor = fdiv( factor, 2 ) return result
def sph_kn_exact(n, z): """Return the value of k_n computed using the exact formula. The expression used is http://dlmf.nist.gov/10.49.E12 . """ zm = mpmathify(z) s = sum(_a(k, n) / zm**(k + 1) for k in xrange(n + 1)) return pi * exp(-zm) / 2 * s
def sph_h2n_exact(n, z): """Return the value of h^{(2)}_n computed using the exact formula. The expression used is http://dlmf.nist.gov/10.49.E7 . """ zm = mpmathify(z) s = sum(mpc(0,-1)**(k-n-1)*_a(k, n)/zm**(k+1) for k in xrange(n+1)) return exp(mpc(0,-1)*zm)*s
def getThueMorseConstant( ): result = 0 factor = mpmathify( '0.5' ) for i in arange( 0, mp.prec + 1 ): result = fadd( result, fmul( getNthThueMorse( i ), factor ) ) factor = fdiv( factor, 2 ) return result
def __init__(self, value, units=RPNUnits()): if isinstance(value, (str, int)): self.value = mpmathify(value) self.units = RPNUnits(units) elif isinstance(value, RPNMeasurement): self.value = value.value self.units = RPNUnits(value.units) else: self.value = value self.units = RPNUnits(units)
def sph_i2n_exact(n, z): """Return the value of i^{(2)}_n computed using the exact formula. The expression used is http://dlmf.nist.gov/10.49.E10 . """ zm = mpmathify(z) s1 = sum(mpc(-1,0)**k * _a(k, n)/zm**(k+1) for k in xrange(n+1)) s2 = sum(_a(k, n)/zm**(k+1) for k in xrange(n+1)) return exp(zm)/2 * s1 + mpc(-1,0)**n*exp(-zm)/2 * s2
def sph_yn_exact(n, z): """Return the value of y_n computed using the exact formula. The expression used is http://dlmf.nist.gov/10.49.E4 . """ zm = mpmathify(z) s1 = sum((-1)**k*_a(2*k, n)/zm**(2*k+1) for k in xrange(0, int(n/2) + 1)) s2 = sum((-1)**k*_a(2*k+1, n)/zm**(2*k+2) for k in xrange(0, int((n-1)/2) + 1)) return -cos(zm - n*pi/2)*s1 + sin(zm - n*pi/2)*s2
def getCyclicPermutationsOperator(n): result = [n] n = getMPFIntegerAsString(n) for _ in range(len(n) - 1): n = n[1:] + n[:1] result.append(mpmathify(n)) return result
def sph_i2n_exact(n, z): """Return the value of i^{(2)}_n computed using the exact formula. The expression used is http://dlmf.nist.gov/10.49.E10 . """ zm = mpmathify(z) s1 = sum(mpc(-1, 0)**k * _a(k, n) / zm**(k + 1) for k in xrange(n + 1)) s2 = sum(_a(k, n) / zm**(k + 1) for k in xrange(n + 1)) return exp(zm) / 2 * s1 + mpc(-1, 0)**n * exp(-zm) / 2 * s2
def __init__( self, value, units = RPNUnits( ) ): if isinstance( value, str ): self.value = mpmathify( value ) self.units = RPNUnits( units ) elif isinstance( value, RPNMeasurement ): self.value = value.value self.units = RPNUnits( value.units ) else: self.value = value self.units = RPNUnits( units )
def replaceDigitsOperator(n, source, replace): n = getMPFIntegerAsString(n) if source < 0: raise ValueError('source value must be a positive integer') if replace < 0: raise ValueError('replace value must be a positive integer') return mpmathify(n.replace(str(int(source)), str(int(replace))))
def sph_h1n_exact(n, z): """Return the value of h^{(1)}_n computed using the exact formula. The expression used is http://dlmf.nist.gov/10.49.E6 . """ zm = mpmathify(z) s = sum( mpc(0, 1)**(k - n - 1) * _a(k, n) / zm**(k + 1) for k in xrange(n + 1)) return exp(mpc(0, 1) * zm) * s
def formatOutput( output ): # filter out text strings for c in output: if c in '+-.': continue # anything with embedded whitespace is a string if c in string.whitespace or c in string.punctuation: return output #print( ) #print( 'formatOutput 1:', output ) # override settings with temporary settings if needed # if g.tempCommaMode: # comma = True # else: # comma = g.comma # output settings, which may be overrided by temp settings outputRadix = g.outputRadix integerGrouping = g.integerGrouping leadingZero = g.leadingZero if g.tempHexMode: integerGrouping = 4 leadingZero = True outputRadix = 16 if g.tempLeadingZeroMode: leadingZero = True if g.tempOctalMode: integerGrouping = 3 leadingZero = True outputRadix = 8 mpOutput = mpmathify( output ) imaginary = im( mpOutput ) real = re( mpOutput ) result, negative = formatNumber( real, outputRadix, leadingZero, integerGrouping ) if negative: result = '-' + result if imaginary != 0: strImaginary, negativeImaginary = formatNumber( imaginary, outputRadix, leadingZero ) result = '( ' + result + ( ' - ' if negativeImaginary else ' + ' ) + strImaginary + 'j )' #print( 'formatOutput 2:', output ) #print( ) return result
def formatOutput( output ): # filter out text strings for c in output: if c in '+-.': continue # anything with embedded whitespace is a string if c in string.whitespace or c in string.punctuation: return output # output settings, which may be overrided by temp settings outputRadix = g.outputRadix integerGrouping = g.integerGrouping leadingZero = g.leadingZero integerDelimiter = g.integerDelimiter # override settings with temporary settings if needed if g.tempCommaMode: integerGrouping = 3 # override whatever was set on the command-line leadingZero = False # this one, too integerDelimiter = ',' if g.tempHexMode: integerGrouping = 4 leadingZero = True outputRadix = 16 if g.tempLeadingZeroMode: leadingZero = True if g.tempOctalMode: integerGrouping = 3 leadingZero = True outputRadix = 8 mpOutput = mpmathify( output ) imaginary = im( mpOutput ) real = re( mpOutput ) result, negative = formatNumber( real, outputRadix, leadingZero, integerGrouping, integerDelimiter, g.decimalDelimiter ) if negative: result = '-' + result if imaginary != 0: strImaginary, negativeImaginary = \ formatNumber( imaginary, outputRadix, leadingZero, integerGrouping, integerDelimiter, g.DecimalDelimiter ) result = '( ' + result + ( ' - ' if negativeImaginary else ' + ' ) + strImaginary + 'j )' #print( 'formatOutput 2:', output ) #print( ) return result
def g(x, y, z): x = mp.mpmathify(x) y = mp.mpmathify(y) z = mp.mpmathify(z) R = radius(x, y, z) if x == 0 and y == 0: part1 = mp.mpf('0') else: part1 = x * y * z * mp.asinh( z / (mp.sqrt(mp.power(x, 2) + mp.power(y, 2)))) if y == 0 and z == 0: part2 = mp.mpf('0') else: part2 = mp.mpf('1 / 6') * y * (3 * mp.power(z, 2) - mp.power( y, 2)) * mp.asinh(x / (mp.sqrt(mp.power(y, 2) + mp.power(z, 2)))) if x == 0 and z == 0: part3 = 0 else: part3 = mp.mpf('1 / 6') * x * (3 * mp.power(z, 2) - mp.power( x, 2)) * mp.asinh(y / (mp.sqrt(mp.power(x, 2) + mp.power(z, 2)))) if y == 0: part4 = 0 else: part4 = mp.mpf('0.5') * mp.power(y, 2) * z * mp.atan((x * z) / (y * R)) if x == 0: part5 = 0 else: part5 = mp.mpf('0.5') * mp.power(x, 2) * z * mp.atan((y * z) / (x * R)) if z == 0: part6 = 0 else: part6 = mp.mpf('1 / 6') * mp.power(z, 3) * mp.atan((x * y) / (z * R)) part7 = mp.mpf('1 / 3') * x * y * R return mp.mpmathify(part1 + part2 + part3 - part4 - part5 - part6 - part7)
def interpretAsBase( args, base ): if isinstance( args, list ): args.reverse( ) else: args = [ args ] if isinstance( base, list ): return [ interpretAsBase( args, i ) for i in base ] value = mpmathify( 0 ) multiplier = mpmathify( 1 ) for i in args: if i >= real_int( base ): raise ValueError( 'invalid value for base', int( base ) ) value = fadd( value, fmul( i, multiplier ) ) multiplier = fmul( multiplier, base ) return value
def click(event): global waiting #convert click location to pix address x = (event.x - centerx * z) / z + 1 y = (event.y - centery * z) / z + 1 qev = mpmath.mpmathify(complex(x, y)) if event.type == 4 or not eventqueue or eventqueue[-1] != qev: eventqueue.append(qev) if waiting: waiting = False master.after_idle(main)
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 getAngularSeparation( self, other, location, date ): if isinstance( location, str ): location = getLocation( location ) location.observer.date = date.to( 'utc' ).format( ) self.object.compute( location.observer ) other.object.compute( location.observer ) return RPNMeasurement( mpmathify( ephem.separation( ( self.object.az, self.object.alt ), ( other.object.az, other.object.alt ) ) ), 'radian' )
def logHistogramAdd(start, end, size, dist, value): start = mpf(start) end = mpf(end) step = mpf((end - start) / size) for i in range(1, size): current = mpmathify(10**(start + step * i)) if value < current: dist[i - 1] += 1 return dist dist[-1] += 1 return dist
def getConstant( name ): if name not in g.constantOperators: raise ValueError( 'Invalid constant: ', name ) unit = g.constantOperators[ name ].unit value = g.constantOperators[ name ].value if unit == '': return mpmathify( value ) else: return RPNMeasurement( value, unit )
def getConstant( name ): if name not in g.constantOperators: raise ValueError( 'Invalid constant: ', name ) unit = g.constantOperators[ name ].unit value = g.constantOperators[ name ].value if unit == '': return mpmathify( value ) return RPNMeasurement( value, unit )
def runYAFU( n ): import subprocess full_out = subprocess.run( [ g.userConfiguration[ 'yafu_path' ] + os.sep + g.userConfiguration[ 'yafu_binary' ], str( int( n ) ), '-xover', '120' ], stdout=subprocess.PIPE, cwd=g.userConfiguration[ 'yafu_path' ] ).stdout.decode( 'ascii' ) #print( 'out', full_out ) out = full_out[ full_out.find( '***factors found***' ) : ] if len( out ) < 2: if log10( n ) > 40: raise ValueError( 'yafu seems to have crashed trying to factor ' + str( int( n ) ) + '.\n\nyafu output follows:\n' + full_out ) else: debugPrint( 'yafu seems to have crashed, switching to built-in factoring code' ) from rpn.factorise import factorise return factorise( int( n ) ) result = [ ] while True: prime = '' out = out[ out.find( 'P' ) : ] if len( out ) < 2: break out = out[ out.find( '=' ) : ] index = 2 while out[ index ] >= '0' and out[ index ] <= '9': prime += out[ index ] index += 1 result.append( mpmathify( prime ) ) if not result: raise ValueError( 'yafu seems to have failed.' ) answer = fprod( result ) if answer != n: debugPrint( '\nyafu has barfed' ) for i in result: n = fdiv( n, i ) result.extend( runYAFU( n ) ) return sorted( result )