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 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 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 ) ) )
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 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 _findLeaving(self, enteringPos): increase = mp.fsub(mp.inf,'1') idx = mp.inf pos = -1 # find the variable with the smaller upper bound to the increase in the entering variable # if there are multiple choices, set the one with the smaller index on the list of basic indexes for i in range(self.m): upperBound = self._getUpperBound(self.b[i], self.A[i, enteringPos]) # if this variable impose more constraint on the increase of the entering variable # than the current leaving variable, then this is the new leaving variable if upperBound <= mp.fsub(increase, self.tolerance): idx = self.basicIdx[i] pos = i increase = upperBound # if this variable impose the same constraint on the increase of the entering variable # than the current leaving variable (considering the tolerance) but has a lower index, # then this is the new leaving variable elif mp.almosteq(upperBound, increase, self.tolerance) and self.basicIdx[i] < idx: idx = self.basicIdx[i] pos = i if pos >= 0: return idx, pos else: return Dictionary.UNBOUNDEDCODE, Dictionary.UNBOUNDED
def _findLeaving(self, enteringPos): increase = mp.fsub(mp.inf, '1') idx = mp.inf pos = -1 # find the variable with the smaller upper bound to the increase in the entering variable # if there are multiple choices, set the one with the smaller index on the list of basic indexes for i in range(self.m): upperBound = self._getUpperBound(self.b[i], self.A[i, enteringPos]) # if this variable impose more constraint on the increase of the entering variable # than the current leaving variable, then this is the new leaving variable if upperBound <= mp.fsub(increase, self.tolerance): idx = self.basicIdx[i] pos = i increase = upperBound # if this variable impose the same constraint on the increase of the entering variable # than the current leaving variable (considering the tolerance) but has a lower index, # then this is the new leaving variable elif mp.almosteq(upperBound, increase, self.tolerance) and self.basicIdx[i] < idx: idx = self.basicIdx[i] pos = i if pos >= 0: return idx, pos else: return Dictionary.UNBOUNDEDCODE, Dictionary.UNBOUNDED
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 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 ) ) )
def getEulerPhi( n ): if real( n ) < 2: return n if g.ecm: return reduce( fmul, ( fmul( fsub( i[ 0 ], 1 ), power( i[ 0 ], fsub( i[ 1 ], 1 ) ) ) for i in getECMFactors( n ) ) ) else: return reduce( fmul, ( fmul( fsub( i[ 0 ], 1 ), power( i[ 0 ], fsub( i[ 1 ], 1 ) ) ) for i in getFactors( n ) ) )
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 subtract( self, other ): if isinstance( other, RPNMeasurement ): if self.units == other.units: return RPNMeasurement( fsub( self.value, other.value ), self.units ) else: return RPNMeasurement( fsub( self.value, other.convertValue( self ) ), self.units ) else: return RPNMeasurement( fsub( self.value, other ), self.units )
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 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 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)))
def subtract(self, other): if isinstance(other, RPNMeasurement): if self.units == other.units: return RPNMeasurement(fsub(self.value, other.value), self.units) return RPNMeasurement(fsub(self.value, other.convertValue(self)), self.units) return RPNMeasurement(fsub(self.value, other), self.units)
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 getNthMenageNumber( n ): if n < 0: raise ValueError( '\'menage\' requires a non-negative argument' ) elif n in [ 1, 2 ]: return 0 elif n in [ 0, 3 ]: return 1 else: return nsum( lambda k: fdiv( fprod( [ power( -1, k ), fmul( 2, n ), binomial( fsub( fmul( 2, n ), k ), k ), fac( fsub( n, k ) ) ] ), fsub( fmul( 2, n ), k ) ), [ 0, n ] )
def getNthSquareTriangularNumber( n ): neededPrecision = int( real_int( n ) * 3.5 ) # determined by experimentation if mp.dps < neededPrecision: setAccuracy( neededPrecision ) sqrt2 = sqrt( 2 ) return nint( power( fdiv( fsub( power( fadd( 1, sqrt2 ), fmul( 2, n ) ), power( fsub( 1, sqrt2 ), fmul( 2, n ) ) ), fmul( 4, sqrt2 ) ), 2 ) )
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 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 convertToSignedInt(n, k): newPrecision = (int(k) * 3 / 10) + 3 if mp.dps < newPrecision: setAccuracy(newPrecision) value = fadd(n, (power(2, fsub(k, 1)))) value = fmod(value, power(2, k)) value = fsub(value, (power(2, fsub(k, 1)))) return value
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 getStandardDeviation( args ): if isinstance( args, RPNGenerator ): return getStandardDeviation( list( args ) ) elif isinstance( args[ 0 ], ( list, RPNGenerator ) ): return [ getStandardDeviation( arg ) for arg in args ] if len( args ) < 2: return 0 mean = fsum( args ) / len( args ) dev = [ power( fsub( i, mean ), 2 ) for i in args ] return sqrt( fdiv( fsum( dev ), fsub( len( dev ), 1 ) ) )
def subtract( self, other ): if isinstance( other, RPNMeasurement ): if self.getUnits( ) == other.getUnits( ): return RPNMeasurement( fsub( self.value, other.value ), self.getUnits( ), self.getUnitName( ), self.getPluralUnitName( ) ) else: newOther = other.convertValue( self ) return RPNMeasurement( fsub( self.value, newOther ), self.getUnits( ), self.getUnitName( ), self.getPluralUnitName( ) ) else: return RPNMeasurement( fsub( self.value, other ), self.getUnits( ), self.getUnitName( ), self.getPluralUnitName( ) )
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 getNthSquareTriangularNumberOperator(n): neededPrecision = int(n * 3.5) # determined by experimentation if mp.dps < neededPrecision: mp.dps = neededPrecision sqrt2 = sqrt(2) return nint( power( fdiv( fsub(power(fadd(1, sqrt2), fmul(2, n)), power(fsub(1, sqrt2), fmul(2, n))), fmul(4, sqrt2)), 2))
def cross_product(a, b): a2b3 = mpmath.fmul(a.y, b.z) a3b2 = mpmath.fmul(a.z, b.y) a3b1 = mpmath.fmul(a.z, b.x) a1b3 = mpmath.fmul(a.x, b.z) a1b2 = mpmath.fmul(a.x, b.y) a2b1 = mpmath.fmul(a.y, b.x) c1 = mpmath.fsub(a2b3, a3b2) c2 = mpmath.fsub(a3b1, a1b3) c3 = mpmath.fsub(a1b2, a2b1) return Vector([c1, c2, c3])
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 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 getStandardDeviation( args ): if isinstance( args, RPNGenerator ): return getStandardDeviation( list( args ) ) if isinstance( args[ 0 ], ( list, RPNGenerator ) ): return [ getStandardDeviation( arg ) for arg in args ] if len( args ) < 2: return 0 mean = fsum( args ) / len( args ) dev = [ power( fsub( i, mean ), 2 ) for i in args ] return sqrt( fdiv( fsum( dev ), fsub( len( dev ), 1 ) ) )
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 interval_bisection(equation, lower, upper) -> str: """ Calculate the root of the equation using `Interval Bisection` method. Examples: >>> interval_bisection([1, 0, -3, -4], 2, 3)[0] '2.19582335' >>> interval_bisection([1, 0, 1, -6], 1, 2)[0] '1.63436529' >>> interval_bisection([1, 0, 3, -12], 1, 2)[0] '1.85888907' """ # Counts the number of iteration counter = 0 equation = mpfiy(equation) lower, upper = mpf(lower), mpf(upper) index_length = len(equation) x = mean(lower, upper) previous_alpha = alpha = None delta = fsub(upper, lower) while delta > power(10, -10) or previous_alpha is None: ans = mpf(0) # Summing the answer for i in range(index_length): index_power = index_length - i - 1 ans = fadd(ans, fmul(equation[i], power(x, index_power))) if ans > mpf(0): upper = x else: lower = x x = mean(lower, upper) previous_alpha, alpha = alpha, x if previous_alpha is None: continue elif previous_alpha == alpha: break delta = abs(fsub(alpha, previous_alpha)) counter += 1 return str(near(alpha, lower, upper)), counter
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 convertToFibBase( value ): 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 getPrimeRange( start, end ): result = list( ) for i in getNthPrimeRange( start, fadd( fsub( end, start ), 1 ) ): result.append( i ) return result
def single_segment_expect_pv(expect, raw=True): """ Compute p-value for an expect value of a single high scoring segment. Prob(E >= x) ~ 1 - exp(-E) This function is equivalent to single_segment_score_pv as long as identical units (log) are used to compute scores and expect :param expect: :param raw: return raw P-value instead of -log10(pv) :return: """ with mpm.workprec(NUM_PREC_KA_PV): x = mpm.convert(expect) complement = mpm.convert('1') res = mpm.fsub(complement, mpm.exp(mpm.fneg(x))) if not raw: res = mpm.fneg(mpm.log10(res)) res = float(res) return res
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 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 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 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 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 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 )
def findNthPolygonalNumber( n, k ): if real_int( k ) < 3: raise ValueError( 'the number of sides of the polygon cannot be less than 3,' ) return nint( fdiv( fsum( [ sqrt( fsum( [ power( k, 2 ), fprod( [ 8, k, real( n ) ] ), fneg( fmul( 8, k ) ), fneg( fmul( 16, n ) ), 16 ] ) ), k, -4 ] ), fmul( 2, fsub( k, 2 ) ) ) )
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 single_segment_score_pv(score, raw=True): """ Compute p-value for normalized local score of a single high scoring segment. Computes formula [1] in Karlin & Altschul, PNAS 1993 Prob(S' >= x) ~ 1 - exp(-exp(-x)) :param score: :param raw: return raw P-value instead of -log10(pv) :return: """ with mpm.workprec(NUM_PREC_KA_PV): x = mpm.convert(score) complement = mpm.convert('1') exponent = mpm.fneg(mpm.exp(mpm.fneg(x))) res = mpm.fsub(complement, mpm.exp(exponent)) if not raw: res = mpm.fneg(mpm.log10(res)) res = float(res) # Equivalent implementation using Python standard library: # # x = score # res = 1 - math.exp(-math.exp(-x)) # if not raw: # res = -1 * math.log10(res) return res
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 getNthPadovanNumber( arg ): n = fadd( real( arg ), 4 ) a = root( fsub( fdiv( 27, 2 ), fdiv( fmul( 3, sqrt( 69 ) ), 2 ) ), 3 ) b = root( fdiv( fadd( 9, sqrt( 69 ) ), 2 ), 3 ) c = fadd( 1, fmul( mpc( 0, 1 ), sqrt( 3 ) ) ) d = fsub( 1, fmul( mpc( 0, 1 ), sqrt( 3 ) ) ) e = power( 3, fdiv( 2, 3 ) ) r = fadd( fdiv( a, 3 ), fdiv( b, e ) ) s = fsub( fmul( fdiv( d, -6 ), a ), fdiv( fmul( c, b ), fmul( 2, e ) ) ) t = fsub( fmul( fdiv( c, -6 ), a ), fdiv( fmul( d, b ), fmul( 2, e ) ) ) return nint( re( fsum( [ fdiv( power( r, n ), fadd( fmul( 2, r ), 3 ) ), fdiv( power( s, n ), fadd( fmul( 2, s ), 3 ) ), fdiv( power( t, n ), fadd( fmul( 2, t ), 3 ) ) ] ) ) )
def my_forward_subst(L, i): """ This function performs the forward substitution for solution of the system Lx = e_i where L - is a lower triangular matrix with 1s on the main diagonal e_i - i-th identity vector All the computations are done exactly with MPMATH Parameters ---------- L - n x n lower-triangular matrix with ones on the diagonal i - index for the canonical vector Returns ------- x - n x 1 vector of the solution """ n = L.rows x = mpmath.zeros(n, 1) e = mpmath.zeros(n, 1) e[i, 0] = mpmath.mp.one x[0,0] = e[0,0] for i in range(1, n): x[i,0] = e[i] for j in range(0, i): tmp = mpmath.fmul(L[i,j], x[j,0], exact=True) x[i,0] = mpmath.fsub(x[i,0], tmp, exact=True) return x
def calc_model_evidence(self): vval = 0 mp.mp.dps = 50 for action in range(self.hparams.num_actions): # val=1 # aa = self.a[action] # for i in xrange(int(self.a[action]-self.a0)): # aa-=1 # val*=aa # val/=(2.0*math.pi) # val/=self.b[action] # val*=gamma(aa) # val/=(self.b[action]**aa) # val *= np.sqrt(np.linalg.det(self.lambda_prior * np.eye(self.hparams.context_dim + 1)) / np.linalg.det(self.precision[action])) # val *= (self.b0 ** self.a0) # val/= gamma(self.a0) # vval += val #val= 1/float((2.0 * math.pi) ** (self.a[action]-self.a0)) #val*= (float(gamma(self.a[action]))/float(gamma(self.a0))) #val*= np.sqrt(float(np.linalg.det(self.lambda_prior * np.eye(self.hparams.context_dim + 1)))/float(np.linalg.det(self.precision[action]))) #val*= (float(self.b0**self.a0)/float(self.b[action]**self.a[action])) val= mp.mpf(mp.fmul(mp.fneg(mp.log(mp.fmul(2.0 , mp.pi))) , mp.fsub(self.a[action],self.a0))) val+= mp.loggamma(self.a[action]) val-= mp.loggamma(self.a0) val+= 0.5*mp.log(np.linalg.det(self.lambda_prior * np.eye(self.hparams.context_dim + 1))) val -= 0.5*mp.log(np.linalg.det(self.precision[action])) val+= mp.fmul(self.a0,mp.log(self.b0)) val-= mp.fmul(self.a[action],mp.log(self.b[action])) vval+=mp.exp(val) vval/=float(self.hparams.num_actions) return vval
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 to_dSSmp(self): """ This function constructs a discrete state-space matrices in canonical controllable form[1]. Returns a dSSmp object. All operations are performed *exactly* Algorithm: 1. Extract a delay-free path D = h(0) = b_0 This is done by one stage of long division: H(z) = b_0 + { (beta_1 * z^-1 + ... + beta_N * z^-N} / {1 + a_1 * z^-1 + ... + a_N * z^-N}, where N = max(Na, Nb) a_i = 0 for i > Na b_i = 0 for i > Nb beta_i = b_i - b_0 * a_i for i=1...N 2. Controller canonical form is as follows: -a_1 -a_2 ... -a_N-1 -a_N 1 1 0 0 0 A = 0 1 0 B= 0 .... ... 0 0 1 0 0 C = [beta_1 beta_2 ... beta_N] D = b_0 [1] https://ccrma.stanford.edu/~jos/fp/Converting_State_Space_Form_Hand.html Returns ------- S - dSSmp object """ from fixif.LTI import dSSmp N = self.order + 1 A = mpmath.mp.zeros(N - 1, N - 1) A[0, :] = -self.den.transpose()[0, 1:N] for i in range(1, N - 1): A[i, i - 1] = mpmath.mp.one B = mpmath.mp.zeros(N - 1, 1) B[0, 0] = mpmath.mp.one # We compute matrix C exactly C = mpmath.mp.zeros(1, N - 1) for i in range(0, N - 1): tmp = mpmath.fmul(self.num[0, 0], self.den[i + 1, 0], exact=True) C[0, i] = mpmath.fsub(self.num[i + 1, 0], tmp, exact=True) D = mpmath.matrix([self.num[0, 0]]) return dSSmp(A, B, C, D)
def solveQuadraticPolynomial( a, b, c ): '''This function applies the quadratic formula to solve a polynomial with coefficients of a, b, and 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 cross(self, other_vector): # source https://en.wikipedia.org/wiki/Cross_product a = self b = other_vector a2b3 = mpmath.fmul(a.y, b.z) a3b2 = mpmath.fmul(a.z, b.y) a3b1 = mpmath.fmul(a.z, b.x) a1b3 = mpmath.fmul(a.x, b.z) a1b2 = mpmath.fmul(a.x, b.y) a2b1 = mpmath.fmul(a.y, b.x) c1 = mpmath.fsub(a2b3, a3b2) c2 = mpmath.fsub(a3b1, a1b3) c3 = mpmath.fsub(a1b2, a2b1) return Vector([c1, c2, c3])
def makeEulerBrick( _a, _b, _c ): a, b, c = sorted( [ real( _a ), real( _b ), real( _c ) ] ) if fadd( power( a, 2 ), power( b, 2 ) ) != power( c, 2 ): raise ValueError( "'euler_brick' requires a pythogorean triple" ) result = [ ] a2 = fmul( a, a ) b2 = fmul( b, b ) c2 = fmul( c, c ) result.append( fabs( fmul( a, fsub( fmul( 4, b2 ), c2 ) ) ) ) result.append( fabs( fmul( b, fsub( fmul( 4, a2 ), c2 ) ) ) ) result.append( fprod( [ 4, a, b, c ] ) ) return sorted( 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 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)))