예제 #1
0
def mp_binom(k, n, p):
    """
	Binomial function, returning the probability of k successes in n trials given the trial success probability p, and supporting multiprecission output.

	Parameters
	----------
	k : int, ndarray
		Successes.
	n : int, ndarray
		Trials.
	p : float,ndarray
		Trial (experiment) success probability.

	Returns
	-------
	val : float,ndarray
		Probability of k successes in n trials.

	Examples
	--------
	>>> k = 10
	>>> n = 10000
	>>> p = 0.9
	>>> mp_binom(k, n, p)
	9.56548769092821e-9958
	"""
    import mpmath as mp
    val = mp_comb(n, k) * mp.power(p, k) * mp.power(1 - p, n - k)
    return val
예제 #2
0
def mp_binom(k,n,p):
	"""
	Binomial function, returning the probability of k successes in n trials given the trial success probability p, and supporting multiprecission output.
	Parameters
	----------
	k : int, ndarray
		Successes.
	n : int, ndarray
		Trials.
	p : float,ndarray
		Trial (experiment) success probability.
	Returns
	-------
	val : float,ndarray
		Probability of k successes in n trials.
	Examples
	--------
	>>> k = 10
	>>> n = 10000
	>>> p = 0.9
	>>> mp_binom(k, n, p)
	9.56548769092821e-9958
	"""
	import mpmath as mp
	val = mp_comb(n,k) * mp.power(p,k) * mp.power(1-p,n-k)
	return val
예제 #3
0
def sign_test_precision(preds_system_A, preds_system_B, ground_truth, q=0.5):
    ties = 0
    plus = 0
    minus = 0

    for i, gt in enumerate(ground_truth):
        if preds_system_A[i] == preds_system_B[i]:
            ties += 1
            continue

        else:
            if preds_system_A[i] == gt:
                plus += 1
                continue

            else:
                minus += 1
                continue

    all_samples = len(ground_truth)
    k = np.ceil(ties / 2) + min(plus, minus)

    N = 2 * np.ceil(ties / 2) + plus + minus

    print("The k is: ", k)
    print("The N is: ", N)

    res = 0
    for idx in range(0, int(k)):
        res += (mpmath.binomial(N, idx) * mpmath.power(q, idx) * mpmath.power(
            (1 - q), (N - idx)))
        #res += (nCr(N, idx)*pow(q, idx)*pow((1-q), (N-idx)))

    return (2 * res)
예제 #4
0
 def _calculate_constant(self):
     """
         Calculates the normalization constant.
     :rtype:
     """
     return power(nsum(lambda n: self._internal_function(n) * power(n, -self._alpha), [1, inf],
                       method=self._summation_method), -1)
예제 #5
0
def sround(num, decimal_places):
    """
    Rounds away from 0. works for ints, floats and mpmath.mpf. 
    returns string. 
    """
    s = str(num)
    #get the digits after the decimal

    if s.find('.') == -1:
        after_d = '0'
    else:
        after_d = s.split('.')[1]

    #only worry about rounding if there's enough dps to make a difference
    if len(after_d) > decimal_places and after_d[decimal_places] >= '5':
        #we round away from 0
        if num >= 0:
            #e.g num: 234.23356 ; dp: 3 -> 234.23456
            num += mpmath.mpf(1.0) * mpmath.power(10, -decimal_places)
        else:
            num -= mpmath.mpf(1.0) * mpmath.power(10, -decimal_places)

    #there still might be trailing digits whcih we chop off
    #e.g num: 234.23456 -> 234.234
    return schop(num, decimal_places)
예제 #6
0
def round5_fp_fast(n, h, q, p, t, f, mu, B, add_coeff=False, verbose=False):
    ## use this for full precision
    ###   dif = mp_zeros(q)
    ###   dif[0] = mp.mpf(1.0)
    ## use this for double precision
    dif = np.zeros(q)
    dif[0] = 1.0
    # determine number of times to convolve the term differences in term s*e.
    #If prime cyclotomic, it is h, if ring swithing or scaler, just h/2.
    # Only h(2h) convolutions as we start with probability gen function
    # for difference between two random variables with q-p rounding noise
    # This can be done as we consider balanced secrets
    w = h
    if add_coeff:
        w = 2 * w
    # computation of convolution of w variables (we have the sum of w variables)
    for i in range(w):
        dif = spec_conv_comb_qp(dif, q, p)
    # convert to mpf if we were double
    dif = np.array([mp.mpf(dif[i]) for i in range(len(dif))])
    # normalize, just in case
    dif /= dif.sum()
    # second convolution with the p to t noise. Single time to account for coefficient compression from p to t.
    dif = spec_conv_comb_pt(dif, q, p, t)
    # Decryption failure ranges for case when parameter B>1
    up_fail = (q + (1 << B)) // (1 << (B + 1))
    down_fail = (q * ((1 << (B + 1)) - 1) + (1 << B)) // (1 << (B + 1))
    # Bit failure probability (bfp). Distribution goes from 0 to q-1, highly provable values are centered around 0, thus, we sum the central part.
    bfp = dif[up_fail:down_fail].sum()
    # Failure probability after error correction
    ffp = mp.mpf(0)
    for j in range(f + 1, mu + 1):
        ffp += (mp.binomial(mu, j) * mp.power(bfp, j) *
                mp.power(mp.mpf(1) - bfp, (mu - j)))
    return float(mp.log(ffp, 2))
예제 #7
0
    def integrand(self, eta, l, p, n, kind="A"):
        if kind not in ("A", "B", "C", "D", "E"):
            raise NotImplementedError("Integrand types supported \
                                      go only from A to E")
        if kind == "C":
            return (mpmath.sqrt(self.k ** 2 - eta ** 2) / eta \
                    * self.integrand(eta, l, p, n, kind="A"))
        if kind == "D":
            return (mpmath.sqrt(self.k ** 2 - eta ** 2) / eta \
                    * self.integrand(eta, l, p, n, kind="B"))

        pm = 1
        exponent = n - 1
        if kind == "B":
            pm = -1
        elif kind == "E":
            pm = 0
            exponent = n

        if p == 0:
            lgr_factor = 1
        else:
            lgr_factor = (self.a(eta) ** 2 \
                       * mpmath.laguerre(p - 1, l, self.a(eta) ** 2))

        kz = mpmath.sqrt(self.k**2 - eta**2)
        return ( mpmath.power(eta, np.abs(l) + 1) / mpmath.sqrt(kz) \
               * mpmath.exp(-self.a(eta) ** 2 / 2) * (1 + pm * kz / self.k) \
               * mpmath.power(eta / self.k, exponent) * lgr_factor)
예제 #8
0
파일: rauch.py 프로젝트: bson/filtergen
    def __init__(self, pos, f, H0, Q, R1, annot, box=False, sim=False):
        super(Lowpass, self).__init__(pos)

        self.annot = annot
        self.box = box
        self.sim = sim

        # Calculate component values
        R3 = R1 / H0
        R2 = R1 / (1.0 + H0)
        w0 = 2.0 * f * mp.pi
        # The product C1*C2
        C1C2 = 1 / (mp.power(w0, 2.0) * R1 * R2)
        # The ratio C1/C2
        rC1C2 = mp.power(Q, 2.0) * mp.power(
            mp.sqrt(R2 / R1) * (1 + H0) + mp.sqrt(R1 / R2), 2.0)
        # C1, C2
        C1 = mp.sqrt(C1C2 * rC1C2)
        C2 = C1C2 / C1

        self.R1 = "%s" % sisuffix(R1)
        self.R2 = "%s" % sisuffix(R2)
        self.R3 = "%s" % sisuffix(R3)
        self.C1 = "%sF" % sisuffix(C1)
        self.C2 = "%sF" % sisuffix(C2)
        self.f = "%sHz" % sisuffix(f)

        if self.sim:
            self.OPAMP = "IDEAL"
        else:
            self.OPAMP = "LM358"  # Just a dummy value

        self.Build()
예제 #9
0
def calculateWindChillOperator( measurement1, measurement2 ):
    '''
    https://www.ibiblio.org/units/dictW.html
    '''

    validUnitTypes = [
        [ 'velocity', 'temperature' ],
    ]

    arguments = matchUnitTypes( [ measurement1, measurement2 ], validUnitTypes )

    if not arguments:
        raise ValueError( '\'wind_chill\' requires velocity and temperature measurements' )

    windSpeed = arguments[ 'velocity' ].convert( 'miles/hour' ).value
    temperature = arguments[ 'temperature' ].convert( 'degrees_F' ).value

    if windSpeed < 3:
        raise ValueError( '\'wind_chill\' is not defined for wind speeds less than 3 mph' )

    if temperature > 50:
        raise ValueError( '\'wind_chill\' is not defined for temperatures over 50 degrees fahrenheit' )

    result = fsum( [ 35.74, fmul( temperature, 0.6215 ), fneg( fmul( 35.75, power( windSpeed, 0.16 ) ) ),
                     fprod( [ 0.4275, temperature, power( windSpeed, 0.16 ) ] ) ] )

    # in case someone puts in a silly velocity
    if result < -459.67:
        result = -459.67

    return RPNMeasurement( result, 'degrees_F' ).convert( arguments[ 'temperature' ].units )
예제 #10
0
def test5():
    # Measure probability of at least 1 instance of T consecutive successes over P trials
    n = 100
    c = 80
    b = 20
    _range = list(range(int(c/2), c, 1))
    # _range = list(range(500, 1000, 1))
    for T in [110]:
        for trials in [10**15]:
            results = []
            # with Pool(8) as pool:
            #     results = pool.map(prob_atleast_k_identical_cons_n_trials_p_probability, [(trials, T, i) for i in _range])
            for i in _range:
                print(i)
                h = hyper(n, i+b, 40, 32)
                h = mp.power(h, T)
                results.append(mp.mp.mpf(1) - mp.power(mp.mp.mpf(1)-h, trials-T+1))
            for index, r in enumerate(results):
                if r >= 0.9:
                    print(_range[index], r)
            plt.semilogy(_range, results, label=(trials, T))
    plt.plot(_range, [1/(10**math.log(2**(32), 10))]*len(_range))
    plt.plot(_range, [0.5]*len(_range))
    # plt.ylim((10**-100,1))
    plt.legend()
    plt.show()
def binom(trials, successes, p):
    total = mp.mp.mpf(0)
    p_ = mp.mp.mpf(p)
    for i in range(successes, trials + 1):
        total += (binomial(trials, i) * mp.power(p_, i) *
                  mp.power(1 - p_, trials - i))
    return total
예제 #12
0
def hitungParabolaDrag(time, timeStep, gravitasi, nilaiVO, nilaiD, sudut,
                       massa):
    listSumbuY = []
    listSumbuX = []
    nilaiVx = nilaiVO * numpy.cos(numpy.deg2rad(sudut))
    nilaiVy = nilaiVO * numpy.sin(numpy.deg2rad(sudut))
    posisiSumbuY = nilaiVy * timeStep
    posisiSumbuX = nilaiVx * timeStep
    listSumbuX.append(posisiSumbuX)
    listSumbuY.append(posisiSumbuY)
    nilaiV = mpmath.sqrt(mpmath.power(nilaiVx, 2) + mpmath.power(nilaiVy, 2))
    nilaiAx = -(nilaiD / massa) * nilaiV * nilaiVx
    nilaiAy = gravitasi - (nilaiD / massa) * nilaiV * nilaiVy
    for i in numpy.arange(0, time, timeStep):
        nilaiAx = -(nilaiD / massa) * nilaiV * nilaiVx
        nilaiAy = gravitasi - (nilaiD / massa) * nilaiV * nilaiVy
        nilaiVx += nilaiAx * timeStep
        nilaiVy += nilaiAy * timeStep
        nilaiV = mpmath.sqrt(
            mpmath.power(nilaiVx, 2) + mpmath.power(nilaiVy, 2))
        posisiSumbuY += nilaiVy * timeStep
        posisiSumbuX += nilaiVx * timeStep
        if (posisiSumbuY < 0):
            break
        listSumbuX.append(posisiSumbuX)
        listSumbuY.append(posisiSumbuY)
    tampilGraph(listSumbuX, listSumbuY)
예제 #13
0
 def B_01(Non, Noff, alpha):
     Ntot = Non + Noff
     gam = (1 + 2 * Noff) * power(alpha, (0.5 + Ntot)) * gamma(0.5 + Ntot)
     delta = ((2 * power((1 + alpha), Ntot)) * gamma(1 + Ntot) *
              hyp2f1(0.5 + Noff, 1 + Ntot, 1.5 + Noff, (-1 / alpha)))
     c1_c2 = sqrt(pi) / (2 * atan(1 / sqrt(alpha)))
     return gam / (c1_c2 * delta)
예제 #14
0
def calculateWindChill( measurement1, measurement2 ):
    validUnitTypes = [
        [ 'velocity', 'temperature' ],
    ]

    arguments = matchUnitTypes( [ measurement1, measurement2 ], validUnitTypes )

    if not arguments:
        raise ValueError( '\'wind_chill\' requires velocity and temperature measurements' )

    wind_speed = arguments[ 'velocity' ].convert( 'miles/hour' ).value
    temperature = arguments[ 'temperature' ].convert( 'degrees_F' ).value

    if wind_speed < 3:
        raise ValueError( '\'wind_chill\' is not defined for wind speeds less than 3 mph' )

    if temperature > 50:
        raise ValueError( '\'wind_chill\' is not defined for temperatures over 50 degrees fahrenheit' )

    result = fsum( [ 35.74, fmul( temperature, 0.6215 ), fneg( fmul( 35.75, power( wind_speed, 0.16 ) ) ),
                   fprod( [ 0.4275, temperature, power( wind_speed, 0.16 ) ] ) ] )

    # in case someone puts in a silly velocity
    if result < -459.67:
        result = -459.67

    return RPNMeasurement( result, 'degrees_F' ).convert( arguments[ 'temperature' ].units )
예제 #15
0
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
예제 #16
0
파일: rpnGeometry.py 프로젝트: flawr/rpn
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 ) )
예제 #17
0
def Ptrue(Qp, I, R, S, Q, b, replacement=True):
    """
    Returns the probability of testing with replacement,
    in which tested individuals can be retested on the same day.
    
    Args
    ----
    Qp (int): number of positive tests.
    I (int): number of infecteds.
    R (int): number of recovered.
    S (int): number of suceptibles.
    Q (int): number of tests.
    b (float): biased-testing factor.
    replacement (boolean): testing with/without replacement.
    
    """

    if replacement:
        f0 = (I + R) / (S + I + R)
        Ptrue = binomial(Q, Qp) * power(f0 * exp(b), Qp) * power(
            1 - f0, Q - Qp)
        Ptrue /= power(1 + (exp(b) - 1) * f0, Q)

    else:
        product = [(I + R - k) / (S - Q + Qp - k) for k in range(Qp)]

        Ptrue = binomial(Q, Qp) * fprod(product) * exp(Qp*b) * \
                1/hyp2f1( -I - R, -Q, S - Q + 1, exp(b) )

    return Ptrue
예제 #18
0
    def cdf(self, x, shape, loc, scale, dx='1e-10', precision=100):
        """
        Calculates cdf.

        Parameters
        ----------
        x : float or array_like
        shape : float
        loc : float
        scale : float
        dx : str, optional
        precision : int, optional
        """

        with mpmath.workdps(precision):
            # Make sure passed values are valid
            x = self.check_support(x, shape, loc, scale, dx, precision)
            z = self.__z(x, shape, loc, scale, dx, precision)

            part_2 = -(mpmath.mpf('1') / mpmath.mpf(shape))
            if np.isscalar(x):
                part_1 = mpmath.mpf('1') + mpmath.mpf(shape) * z
                return mpmath.mpf('1') - mpmath.power(part_1, part_2)
            else:
                parts_1 = [
                    mpmath.mpf('1') + mpmath.mpf(shape) * _z for _z in z
                ]
                return np.array([
                    mpmath.mpf('1') - mpmath.power(part_1, part_2)
                    for part_1 in parts_1
                ])
예제 #19
0
파일: rpnPolytope.py 프로젝트: flawr/rpn
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 ) ) )
예제 #20
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)
예제 #21
0
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))
예제 #22
0
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
예제 #23
0
def getNthDecagonalCenteredSquareNumberOperator(n):
    sqrt10 = sqrt(10)

    dps = 7 * int(n)

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

    return nint(
        floor(
            fsum([
                fdiv(1, 8),
                fmul(fdiv(7, 16),
                     power(fsub(721, fmul(228, sqrt10)), fsub(n, 1))),
                fmul(
                    fmul(fdiv(1, 8),
                         power(fsub(721, fmul(228, sqrt10)), fsub(n, 1))),
                    sqrt10),
                fmul(
                    fmul(fdiv(1, 8),
                         power(fadd(721, fmul(228, sqrt10)), fsub(n, 1))),
                    sqrt10),
                fmul(fdiv(7, 16),
                     power(fadd(721, fmul(228, sqrt10)), fsub(n, 1)))
            ])))
예제 #24
0
def regularHoeffding(n, D, N):
    alpha = mp.mp.mpf(0.8)
    n = mp.mp.mpf(n)
    D = mp.mp.mpf(D)
    N = mp.mp.mpf(N)
    p = D/N
    t = alpha - p
    return mp.power(mp.power(mp.e, -2*mp.power(t, 2)*n), 1550)
예제 #25
0
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 ) ) )
예제 #26
0
def getNthDecagonalTriangularNumberOperator(n):
    return nint(
        floor(
            fdiv(
                fmul(fadd(9, fprod([4, sqrt(2),
                                    power(-1, fadd(n, 1))])),
                     power(fadd(1, sqrt(2)), fsub(fmul(4, fadd(n, 1)), 6))),
                64)))
예제 #27
0
 def distance(self, another):
     """
     This method computes the Euclidean distance with another opinion and returns it
     """
     return mpmath.sqrt(mpmath.power(self.getBelief() - another.getBelief(), mpmath.mpf("2")) + \
                        mpmath.power(self.getDisbelief() - another.getDisbelief(), mpmath.mpf("2")) + \
                        mpmath.power(self.getUncertainty() - another.getUncertainty(), mpmath.mpf("2"))\
                        )
예제 #28
0
def getNthOctagonalTriangularNumberOperator(n):
    sign = power(-1, n)

    return nint(
        floor(
            fdiv(
                fmul(fsub(7, fprod([2, sqrt(6), sign])),
                     power(fadd(sqrt(3), sqrt(2)), fsub(fmul(4, n), 2))), 96)))
예제 #29
0
def getNthAperyNumber( n ):
    result = 0

    for k in arange( 0, real( n ) + 1 ):
        result = fadd( result, fmul( power( binomial( n, k ), 2 ),
                                     power( binomial( fadd( n, k ), k ), 2 ) ) )

    return result
예제 #30
0
 def __call__(self, y):
     """
     This function should be used by the root finder.
     If the brentq root finder is used then the derivative does not help.
     """
     r = self.r2 / self.r1
     lhs = self.a1 - self.b1 * mp.root(y, 2)
     rhs = self.a2 * mp.power(y, r - 1) + self.b2 * mp.power(y, 1.5 * r - 1)
     return rhs - lhs
예제 #31
0
def get_prob_correct_async(k, pc, rprime):
    """prob = \sum_{l=0}^{k-rprime} (k_choose_l) * (pc)^l * (1 - pc)^(k-l)
    """
    retval = 0
    lmax = k - rprime
    for l in range(0, lmax + 1):
        retval += mpmath.binomial(k,l) * mpmath.power(pc, l) * \
            mpmath.power(1 - pc, k - l)
    return retval
예제 #32
0
def get_prob_correct_sync(k, pc):
    """prob = \sum_{l=0}^{ceil(k/2)-1} (k_choose_l) * (pc)^l * (1 - pc)^(k-l)
    """
    retval = 0
    lmax = mpmath.ceil(float(k)/2) - 1
    for l in range(0, lmax + 1):
        retval += mpmath.binomial(k,l) * mpmath.power(pc, l) * \
            mpmath.power(1 - pc, k - l)
    return retval
예제 #33
0
    def convertToPrimitiveUnits(self):
        debugPrint()
        debugPrint('convertToPrimitiveUnits:', self.value, self.units)

        if not g.unitConversionMatrix:
            loadUnitConversionMatrix()

        value = self.value
        units = RPNUnits()

        debugPrint('value', value)

        for unit in self.units:

            if self.units[unit] == 0:
                continue

            newUnits = g.basicUnitTypes[getUnitType(unit)].primitiveUnit

            debugPrint('unit', unit, 'newUnits', newUnits)

            if unit != newUnits:
                debugPrint('unit vs newUnits:', unit, newUnits)

                if (unit, newUnits) in g.unitConversionMatrix:
                    value = fmul(
                        value,
                        power(mpf(g.unitConversionMatrix[(unit, newUnits)]),
                              self.units[unit]))
                elif (unit, newUnits) in specialUnitConversionMatrix:
                    value = power(
                        specialUnitConversionMatrix[(unit, newUnits)](value),
                        self.units[unit])
                else:
                    if unit == '1' and newUnits == '_null_unit':
                        reduced = RPNMeasurement(value, units)
                        debugPrint('convertToPrimitiveUnits 2:', reduced.value,
                                   reduced.units)
                        return reduced

                    raise ValueError('cannot find a conversion for ' + unit +
                                     ' and ' + newUnits)

            newUnits = RPNUnits(newUnits)

            for newUnit in newUnits:
                newUnits[newUnit] *= self.units[unit]

            units.update(newUnits)

            debugPrint('value', value)

        baseUnits = RPNMeasurement(value, units)
        debugPrint('convertToPrimitiveUnits 3:', baseUnits.value,
                   baseUnits.units)
        debugPrint()
        return baseUnits
예제 #34
0
파일: rpnPolytope.py 프로젝트: flawr/rpn
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 ) ) )
예제 #35
0
def hoeffding(n, D, N, lamb):
    n = mp.mp.mpf(n)
    D = mp.mp.mpf(D)
    N = mp.mp.mpf(N)
    lamb = mp.mp.mpf(lamb)
    p = D/N
    t = (lamb/(n*mp.sqrt(n))) + (p/n) - p
    print(lamb, t)
    return mp.power(mp.e, -2*mp.power(t, 2)*n)
예제 #36
0
파일: rpnPolytope.py 프로젝트: flawr/rpn
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 ) ) )
예제 #37
0
 def __call__(self, y):
     """
     This function should be used by the root finder.
     If the brentq root finder is used then the derivative does not help.
     """
     r = self.r2 / self.r1
     lhs = self.a1 - self.b1 * mp.root(y, 2)
     rhs = self.a2 * mp.power(y, r - 1) + self.b2 * mp.power(y, 1.5*r - 1)
     return rhs - lhs
예제 #38
0
파일: r5fp.py 프로젝트: r5embed/r5embed
def round5_fp_fast(d, n, h, q, p, t, f, mu, B, add_coeff=False, verbose=False):

    #   dif = mp_zeros(q)                   # full precision
    #   dif[0] = mp.mpf(1.0)

    dif = np.zeros(q)  # double precision approximation
    dif[0] = 1.0

    scale = 0
    for w in h:  # w = weight of +-scale
        scale += 1
        if add_coeff:
            w = 2 * w  # closer to 2 * w - 1 if h ~= w/2
        w *= 2  # double it here; can use floats
        if verbose:
            print "\nw" + str(scale), "=", w

        for i in range(w):
            dif = conv_comb_qp(dif, q, p, scale)
            if verbose:
                sys.stdout.write('.')
                sys.stdout.flush()
    if verbose:
        print "done"

    # convert to mpf if we were double
    dif = np.array([mp.mpf(dif[i]) for i in range(len(dif))])
    dif /= dif.sum()  # normalize, just in case

    if verbose:
        print "eqp*R + eqp'*S".ljust(16) + str_stats(dif)

    dif = conv_comb_pt(dif, q, p, t)
    if verbose:
        print "rounded p->t".ljust(16) + str_stats(dif)

    # Decryption failure ranges for case when parameter B>1
    up_fail = (q + (1 << B)) // (1 << (B + 1))
    down_fail = (q * ((1 << (B + 1)) - 1) + (1 << B)) // (1 << (B + 1))

    bfp = dif[up_fail:down_fail].sum()

    if verbose:
        print "per bit failure probability:", str_log2(bfp)
        print bfp

    ffp = mp.mpf(0)
    for j in range(f + 1, mu + 1):
        ffp += (mp.binomial(mu, j) * mp.power(bfp, j) *
                mp.power(mp.mpf(1) - bfp, (mu - j)))

    if verbose:
        print "more than", f, "errors in", mu, "bits:", str_log2(ffp)
        print ffp

    return float(mp.log(ffp, 2))
    def get_rudder_force(
            self, rudder_angle,
            velocity):  # hydrodynamic force in the fixed body frame

        self.rudder_force.x = self.RUDDER_LIFT_COEF * (mpmath.power(
            velocity.x, 2)) * math.sin(rudder_angle)
        self.rudder_force.y = self.RUDDER_LIFT_COEF * (mpmath.power(
            velocity.y, 2)) * math.cos(rudder_angle)

        return self.rudder_force
예제 #40
0
파일: rpnPolytope.py 프로젝트: flawr/rpn
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 ) ) ] ) ] ) )
예제 #41
0
def pmf(k, n, p):
    """
    Probability mass function of the binomial distribution.
    """
    _validate_np(n, p)
    with mpmath.extradps(5):
        p = mpmath.mpf(p)
        return (mpmath.binomial(n, k) *
                mpmath.power(p, k) *
                mpmath.power(1 - p, n - k))
def fibSum(n):    
    if n == 0 or n == 1:
        return 0
    elif n == 2:
        return 1
    else:
        n = n+1
        a = math.sqrt(5) ; b =1+a ; c = 1-a
        e = (mp.power(b,n)-mp.power(c,n))/(mp.power(2,n)*a)
        return e-1
예제 #43
0
파일: rpnPolytope.py 프로젝트: flawr/rpn
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 ) )
예제 #44
0
    def pdf_eval(self, x):
        if x < 0:
            return 0
        elif x < self.location:
            return 0
        else:
            x = mpf(x)
            a = self.shape/self.scale
            b = (x-self.location)/self.scale
            b = mpmath.power(b, self.shape-1)
            c = mpmath.exp(-mpmath.power(((x-self.location)/self.scale), self.shape))

            return a * b *c
예제 #45
0
파일: rpnPolytope.py 프로젝트: flawr/rpn
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 ) ) ) ] ) ) )
예제 #46
0
def getNthAperyNumber( n ):
    '''
    http://oeis.org/A005259

    a(n) = sum(k=0..n, C(n,k)^2 * C(n+k,k)^2 )
    '''
    result = 0

    for k in arange( 0, real( n ) + 1 ):
        result = fadd( result, fmul( power( binomial( n, k ), 2 ),
                                     power( binomial( fadd( n, k ), k ), 2 ) ) )

    return result
예제 #47
0
파일: rpnPolytope.py 프로젝트: flawr/rpn
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 ) )
예제 #48
0
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
예제 #49
0
def get_prob_schedulable(msgs, mi, boot_time, sync = True):
    """Returns the probability that message m is successfully transmitted even
    in the presence of omission, commission, transmission faults. Here, although
    m represents a single message, we compute the probability of successful
    transmission collectively for all replicas of m, identified by a common
    'tid' field. """
    r = msgs.get_replication_factor(mi)
    rprime = int(mpmath.floor(r / 2.0) + 1)

    prob_msg_corrupted = 1 - br.get_prob_poisson(0, mi.deadline, msgs.po)
    prob_msg_omitted = 1 - br.get_prob_poisson(0, boot_time, msgs.po)

    # since pr(correct) is just a function of k <= r and pc,
    # we compute it beforehand for all values (pc is commission fault prob.)
    prob_correct = []
    for k in range(0, r + 1):
        if sync:
            prob_correct.append(get_prob_correct_sync(k, prob_msg_corrupted))
        else:
            prob_correct.append(get_prob_correct_async(k, prob_msg_corrupted, rprime))

    # need to iterate over all subsets of replica set of m
    replica_ids = []
    for mk in msgs:
        if mk.tid == mi.tid:
            replica_ids.append(mk.id)
    assert r == len(replica_ids)

    prob_success = 0
    for omitted_ids in powerset(replica_ids):
        for mk in msgs:
            if mk.id in omitted_ids:
                mk.omitted = True
            else:
                mk.omitted = False

        s = r - len(omitted_ids)
        prob_omitted = mpmath.power(prob_msg_omitted, r - s) * \
            mpmath.power(1 - prob_msg_omitted, s)

        prob_time_correct = 0
        for k in range(1, s + 1):
            prob_time_correct += get_prob_time_periodic(msgs, mi, k) * \
                                 prob_correct[k]

        prob_success += prob_omitted * prob_time_correct

    return min(prob_success, 1)
예제 #50
0
def multiplyDigits( n, exponent = 1, dropZeroes = False ):
    if exponent < 1:
        raise ValueError( 'multiplyDigits( ) expects a positive integer for \'exponent\'' )
    elif exponent == 1:
        return fprod( getDigits( n, dropZeroes ) )
    else:
        return fprod( [ power( i, exponent ) for i in getDigits( n, dropZeroes ) ] )
예제 #51
0
def getSigma( target ):
    '''
    Returns the sum of the divisors of n, including 1 and n.

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

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

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

    result = 1

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

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

    return result
예제 #52
0
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 ) ) ] ) ) )
예제 #53
0
def getNthKFibonacciNumber( n, k ):
    if real( n ) < 0:
        raise ValueError( 'non-negative argument expected' )

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

    if n < k - 1:
        return 0

    nth = int( n ) + 4

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

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

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

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

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

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

    return floor( fadd( re( result ), fdiv( 1, 2 ) ) )
예제 #54
0
def getNthLucasNumber( n ):
    if real( n ) == 0:
        return 2
    elif n == 1:
        return 1
    else:
        return floor( fadd( power( phi, n ), 0.5 ) )
예제 #55
0
def tetrateRight( i, j ):
    result = i

    for x in arange( 1, j ):
        result = power( i, result )

    return result
예제 #56
0
def tetrate( i, j ):
    result = i

    for x in arange( 1, j ):
        result = power( result, i )

    return result
예제 #57
0
def stirling(x):
    #uses Stirling's approximation
    # x**y = e**(y log x) in essentially constant time
    n = mpmath.mpf(x)
    coeff = mpmath.sqrt(2 * mpmath.pi * n)
    expon = mpmath.power(n/mpmath.e, n) 
    return coeff * expon
예제 #58
0
def packInteger( values, fields ):
    if isinstance( values, RPNGenerator ):
        return packInteger( list( values ), fields )
    elif not isinstance( values, list ):
        return unpackInteger( [ values ], fields )

    if isinstance( fields, RPNGenerator ):
        return packInteger( values, list( fields ) )
    elif not isinstance( fields, list ):
        return unpackInteger( values, [ fields ] )

    if isinstance( values[ 0 ], list ):
        return [ unpackInteger( value, fields ) for value in values ]

    result = 0

    count = min( len( values ), len( fields ) )

    size = 0

    for i in range( count, 0, -1 ):
        result = fadd( result, fmul( values[ i - 1 ], power( 2, size ) ) )
        size += fields[ i - 1 ]

    return result