示例#1
0
文件: PyPi.py 项目: wxv/PiCalc
def chudnovsky(digits):
    # 20 safety digits because lots of calculations (only about 3 are needed)
    scale = 10**(mpz(digits+20))  

    gmpy2.get_context().precision = int(math.log2(10) * (digits + 20)) 
    
    k = mpz(1)
    a_k = scale
    a_sum = scale
    b_sum = mpz(0)
    C = mpz(640320)
    C_cubed_over_24 = C**3 // 24
    
    while True:
        a_k *= -(6*k-5) * (2*k-1) * (6*k-1)
        a_k //= k**3 * C_cubed_over_24
        a_sum += a_k
        b_sum += k * a_k
        k += 1
        if a_k == 0:
            break
    
    total_sum = mpfr(13591409 * a_sum + 545140134 * b_sum)
    pi = (426880 * gmpy2.sqrt(mpfr(10005))) / total_sum
 
    return pi*scale
示例#2
0
文件: llr.py 项目: dkull/rpt
def P_generic(m, _x, debug=False):
    """
        Used for finding s0, this is a generic implementation because m might be any value
        and optimizations aren't needed anyway since this is called once per number.

        Algorithm found in: https://vixra.org/pdf/1303.0195v1.pdf

        Test data can ve verified using:
        # for checking s0 for k=2001 b=2
        https://www.wolframalpha.com/input/?i=2+*+chebyshevT%282*2001%2F2%2C+chebyshevT%282%2F2%2C+2%29%29
    """
    print("M {} X {}".format(m, _x))
    m = mpz(m)
    x = mpz(_x)
    a = mpfr(mpfr(2)**-m)

    inner = pow(x, mpz(2))
    inner -= mpz(4)
    inner = sqrt(inner)
    #inner = x - (sqrt4 / x)  # potential replacement in cases x >= 5

    x += inner
    print("x before pow: {:.64f}".format(x))
    print("a before pow: {:.64f}".format(a))
    x **= m
    x *= a
    result = xmpz(round_away(x))

    if debug:
        print("P_gen: {} {}".format(m, _x))

    return result
示例#3
0
def find_max_mult_difference(alpha, n):
    # NOTE: n is the max_count
    L_n_reciprocal = gmpy2.mpfr((alpha**(2*n+2) + alpha**n) / (alpha**(2*n+1) + alpha**(n+1)), 128)
    U_0_reciprocal = gmpy2.mpfr((1 + alpha**(n+2)) / (alpha + alpha**(n+1)), 128)
    L_1 = gmpy2.mpfr((alpha**3 + alpha**(n+1)) / (alpha**4 + alpha**n), 128)
    U_n1 = gmpy2.mpfr((alpha**(2*n-1) + alpha**(n+1)) / (alpha**(2*n-2) + alpha**(n+2)), 128)
    return( float(max(L_n_reciprocal, U_0_reciprocal, L_1, U_n1)) )
def ibeta(a, b, x):
    if (x == 0.0 or x == 1.0):
        return x
    if x < ((a - 1.0) / (a + b - 2.0)):
        return ibeta_cf(0, a, b, x)
    else:
        return mpfr(1.0) - ibeta_cf(0, b, a, mpfr('1.0') - x)
    def value(self):
        if len(self.numerator) == 0 or len(self.denominator) == 0:
            return None
        numerator_index = 0
        denominator_index = 0
        while numerator_index < len(
                self.numerator) and denominator_index < len(self.denominator):
            if self.numerator[numerator_index] == self.denominator[
                    denominator_index]:
                del self.numerator[numerator_index]
                del self.denominator[denominator_index]
            elif self.numerator[numerator_index] < self.denominator[
                    denominator_index]:
                numerator_index += 1
            else:
                denominator_index += 1

        self.numerator.add(1)
        self.denominator.add(1)
        num_product = reduce(lambda x, y: mpfr(x) * y, self.numerator)
        den_product = reduce(lambda x, y: mpfr(x) * y, self.denominator)
        if num_product <= 0 or den_product <= 0:
            return 0
        val = num_product / den_product
        if val > 1:
            return 1

        return val
示例#6
0
    def __setitem__(self, key, val):
        """
        Cases:
        1. Key is a simple index, val is a simple mpfr.
        1a. Key is two ints: basic case.
        1b. Key is one int: coalesce to two ints.

        2. Key indexes a submatrix. Val is another MPMatrix of appropriate size.
        First, replace slices with index lists. Replace ints with index lists.
        2a. Key is two lists: good.
        2b. Key is a view: get p_rows, p_cols, case 2a.
        
        If Key is a view: we simply need to iterate and setitem.
        """
        rows, cols, is_view = self._cleankey(key)
        if not (is_view):  #simple index case
            i, j = rows[0], cols[0]
            assert isinstance(val, type(mpfr(0)))
            self.data[i, j] = val
            return

        errmsg = "Key shape: {}\n Val shape: {}".format((rows, cols),
                                                        val.shape)
        assert (len(rows), len(cols)) == val.shape, errmsg

        # Local data indices: a, b.
        # View indices: i, j
        for i, a in enumerate(rows):
            for j, b in enumerate(cols):
                datum = val[i, j]
                assert isinstance(datum, type(mpfr(0)))
                self.data[a, b] = val[i, j]
        return
示例#7
0
def computeLaplaceMatrix(sqdist, t, logeps=mp.mpfr("-10")):
    """
    Compute heat approximation to Laplacian matrix using logarithms and gmpy2.

    Use mpfr to gain more precision.

    This is slow, but more accurate.

    Cutoff for really small values, and row/column elimination if degenerate.
    """
    # cutoff ufunc
    cutoff = np.frompyfunc((lambda x: mp.inf(-1) if x < logeps else x), 1, 1)

    t2 = mp.mpfr(t)
    lt = mp.log(2 / t2)
    d = to_mpfr(sqdist)
    L = d * d
    L /= -2 * t2
    cutoff(L, out=L)
    logdensity = logsumexp(L)
    L = exp(L - logdensity[:, None] + lt)
    L[np.diag_indices(len(L))] -= 2 / t2
    L = np.array(to_double(L), dtype=float)
    # if just one nonzero element, then erase row and column
    degenerate = np.sum(L != 0.0, axis=1) <= 1
    L[:, degenerate] = 0
    L[degenerate, :] = 0
    return L
示例#8
0
def factorial(n):
    f = mpfr(1)
    i = mpfr(2)
    while i < n+1:
        f = f*mpfr(i)
        i = i+1
    return f
示例#9
0
def most_probable_symbol_even(p01, p10, bitwidth):
    p00 = mpfr('1.0') - p01
    p11 = mpfr('1.0') - p10

    mps = 0

    if (most_probable_transition_pair(p01, p10) == "P000_MAX"):
        mps = 0
    elif (most_probable_transition_pair(p01, p10) == "P111_MAX"):
        for i in range(bitwidth >> 1):  #(i=0; i<((bitwidth-1)>>1); i++) {
            mps = mps << 2
            mps = mps + 3
    elif (most_probable_transition_pair(p01, p10) == "P010_MAX"):
        for i in range((bitwidth -
                        2) >> 1):  #(i=0; i<((bitwidth-1)>>1); i++) {
            mps = mps << 2
            mps = mps + 1
        mps = mps << 2
        if (p01 > p00):
            mps = mps + 1
        else:
            mps = mps + 0
    elif (most_probable_transition_pair(p01, p10) == "P101_MAX"):
        for i in range((bitwidth -
                        2) >> 1):  #(i=0; i<((bitwidth-1)>>1); i++) {
            mps = mps << 2
            mps = mps + 2
        mps = mps << 2
        if (p11 > p10):
            mps = mps + 3
        else:
            mps = mps + 2
    else:  #     // Equiprobable case, any value will do.
        mps = 0
    return mps
    def value(self):
        if len(self.numerator) == 0 or len(self.denominator) == 0:
            return None
        numerator_index = 0
        denominator_index = 0
        while numerator_index < len(self.numerator) and denominator_index < len(self.denominator):
            if self.numerator[numerator_index] == self.denominator[denominator_index]:
                del self.numerator[numerator_index]
                del self.denominator[denominator_index]
            elif self.numerator[numerator_index] < self.denominator[denominator_index]:
                numerator_index += 1
            else:
                denominator_index += 1

        self.numerator.add(1)
        self.denominator.add(1)
        num_product = reduce(lambda x, y: mpfr(x)*y, self.numerator)
        den_product = reduce(lambda x, y: mpfr(x)*y, self.denominator)
        if num_product <= 0 or den_product <= 0:
            return 0
        val = num_product/den_product
        if val > 1:
           return 1

        return val
示例#11
0
    def subtraction(self, interval):
        reset_default_precision()
        res_inc_left = False
        res_inc_right = False
        if self.include_lower and interval.include_lower:
            res_inc_left = True
        if self.include_upper and interval.include_upper:
            res_inc_right = True
        with gmpy2.local_context(gmpy2.context(),
                                 round=gmpy2.RoundDown,
                                 precision=mpfr_proxy_precision) as ctx:
            res_left = gmpy2.sub(mpfr(self.lower), mpfr(interval.upper))
        with gmpy2.local_context(gmpy2.context(),
                                 round=gmpy2.RoundUp,
                                 precision=mpfr_proxy_precision) as ctx:
            res_right = gmpy2.sub(mpfr(self.upper), mpfr(interval.lower))

        if res_left <= res_right:
            res_right = round_number_up_to_digits(res_right, self.digits)
            res_left = round_number_down_to_digits(res_left, self.digits)
            return Interval(res_left, res_right, res_inc_left, res_inc_right,
                            self.digits)
        else:
            res_right = round_number_down_to_digits(res_right, self.digits)
            res_left = round_number_up_to_digits(res_left, self.digits)
            return Interval(res_right, res_left, res_inc_right, res_inc_left,
                            self.digits)
示例#12
0
def _ptwise_vals_equal(mp_val, np_val, epsilon):
    """Pointwise value comparison"""
    ptwise_diff = abs(mp_val - mpfr(np_val))
    if epsilon == None:
        P = gmpy2.get_context().precision
        epsilon = mpfr("0b" + "0" * P + "1")
    return ptwise_diff < epsilon
示例#13
0
def calculateLatBitsEven():

    global evenMsg
    #lat = mpfr(raw_input(" Please enter required Latitude > "))
    #longitude =  mpfr(raw_input(" Please enter required longitude > "))
    lat = t_lat
    longitude = t_lon

    calculateLatBitsOdd(lat, longitude)

    #Calculate YZ which will be what is put into our message
    modHold = mpfr(modulus(lat, Dlat0))
    modHold = (modHold / Dlat0)
    modHold = modHold * math.pow(2, 17)
    modHold = modHold + 0.5
    YZ = mpfr(math.floor(modHold))

    #Calculate Rlatiude for airborne
    Rlat0 = mpfr(1.0)
    floorHold = 1
    Rlat0 = mpfr(YZ) / math.pow(2, 17)
    floorHold = (lat / mpfr(Dlat0))
    floorHold = math.floor(floorHold)
    Rlat0 = Rlat0 + mpfr(floorHold)
    Rlat0 = Rlat0 * mpfr(Dlat0)
    NlLat = 1
    NlLat = genNlatValue(Rlat0)

    #Calcule DLongitude
    Dlon0 = mpfr(1.0)
    if ((NlLat - 1) > 0):
        Dlon0 = (360 / (mpfr(NlLat)))
    else:
        Dlon0 = 360

    #calculate XZ the decimal representation of longitude
    XZ = mpfr(1.0)
    modHold = 0
    modHold = modulus(longitude, Dlon0)
    modHold = (modHold / Dlon0)
    modHold = modHold * math.pow(2, 17)
    modHold = modHold + 0.5
    XZ = math.floor(modHold)
    #print mpfr(XZ)

    #Ensure this fits into our 17 bit space
    YZ1 = mpz(modulus(YZ, math.pow(2, 17)))
    XZ1 = mpz(modulus(XZ, math.pow(2, 17)))
    #print YZ1
    LatLon = mpz(1)
    YZ1 = YZ1 << 17
    LatLon = (YZ1 | XZ1)
    #LatLon = (LatLon | 17179869184)

    #to be decided
    print "even message: " + hex(LatLon)
    evenMsg = LatLon

    return 0
示例#14
0
def calculateLatBitsEven():
    
    global evenMsg
    #lat = mpfr(raw_input(" Please enter required Latitude > "))
    #longitude =  mpfr(raw_input(" Please enter required longitude > "))
    lat = t_lat
    longitude = t_lon 
    
    calculateLatBitsOdd(lat,longitude)
    
    #Calculate YZ which will be what is put into our message
    modHold = mpfr(modulus(lat,Dlat0))
    modHold = (modHold/Dlat0)
    modHold = modHold * math.pow(2,17)
    modHold = modHold + 0.5
    YZ = mpfr(math.floor(modHold))
    
    #Calculate Rlatiude for airborne
    Rlat0 = mpfr(1.0)
    floorHold = 1
    Rlat0 = mpfr(YZ) / math.pow(2,17)
    floorHold = (lat/mpfr(Dlat0))
    floorHold = math.floor(floorHold)
    Rlat0 = Rlat0 + mpfr(floorHold)
    Rlat0 = Rlat0 * mpfr(Dlat0)
    NlLat = 1
    NlLat = genNlatValue(Rlat0)
    
    #Calcule DLongitude
    Dlon0 = mpfr(1.0)
    if((NlLat-1) > 0):
        Dlon0 = (360/(mpfr(NlLat)));
    else:
        Dlon0 = 360
        
    #calculate XZ the decimal representation of longitude
    XZ = mpfr(1.0)
    modHold = 0
    modHold = modulus(longitude, Dlon0)
    modHold = (modHold/Dlon0)
    modHold = modHold * math.pow(2,17)
    modHold = modHold + 0.5
    XZ = math.floor(modHold)
    #print mpfr(XZ)
    
    #Ensure this fits into our 17 bit space
    YZ1 = mpz(modulus(YZ,math.pow(2,17)))
    XZ1 = mpz(modulus(XZ,math.pow(2,17)))
    #print YZ1
    LatLon = mpz(1)
    YZ1 = YZ1 << 17
    LatLon = (YZ1 | XZ1)
    #LatLon = (LatLon | 17179869184)
    
    #to be decided
    print "even message: " + hex(LatLon)
    evenMsg = LatLon
    
    return 0
示例#15
0
 def __init__(self, plist=None):
     """
     """
     if plist is None:
         plist = []
     elif plist == []:
         plist = [mpfr(1.0)]
     self.plist = [mpfr (p) for p in plist]
示例#16
0
 def update():
     for i in range(51):
         GSConst.c[i] = mpfr(str(float(i)), GSParams.bits)
     for i in range(51):
         GSConst.e[i] = mpfr('1' + i * '0' + '.0', GSParams.bits)
     for i in range(1, 51):
         GSConst.e_[i] = mpfr('0.' + (i - 1) * '0' + '1', GSParams.bits)
     GSConst.pi = pi(GSParams.bits)
示例#17
0
文件: gslib.py 项目: PKizin/gsa
 def update():
     for i in range(51):
         GSConst.c[i] = mpfr(str(float(i)), GSParams.bits)
     for i in range(51):
         GSConst.e[i] = mpfr('1' + i * '0' + '.0', GSParams.bits)
     for i in range(1, 51):
         GSConst.e_[i] = mpfr('0.' + (i-1) * '0' + '1', GSParams.bits)
     GSConst.pi = pi(GSParams.bits)
示例#18
0
def naive_bayes(TrainSet, TestSet):
    print(
        "####################################################################")
    print

    # Priors
    NRC = 0
    for cls in xrange(nr_of_classes):
        NRC += TrainSet[cls][0]
    P = [float(TrainSet[cls][0]) / NRC for i in xrange(nr_of_classes)]

    # Compute number of unique training words
    D = {}
    nr_unique_words = 0
    for cls in xrange(nr_of_classes):
        for k, v in TrainSet[cls][2].iteritems():
            D[k] = 1
    nr_unique_words = len(D)

    print("UNIQUE WORDS:", nr_unique_words)
    print

    # Conditional Probabilities
    PC = [{} for _ in xrange(nr_of_classes)]
    for cls in xrange(nr_of_classes):
        DVD = TrainSet[cls][1] + nr_unique_words
        for k, v in TrainSet[cls][2].iteritems():
            PC[cls][k] = mpfr(v + 1) / DVD

    # Training set
    print("Training size")
    print[TrainSet[cls][0] for cls in xrange(nr_of_classes)]

    # Test Set
    success = [0] * nr_of_classes
    fail = [[0] * nr_of_classes for i in xrange(nr_of_classes)]

    for exp_cls, docs in enumerate(TestSet):
        for doc in docs:
            CLS = -1
            PR = [mpfr(P[cls]) for cls in xrange(nr_of_classes)]
            for cls in xrange(nr_of_classes):
                for k, v in doc.iteritems():
                    PR[cls] *= PC[cls][k]**v

            _, CLS = max(zip(PR, xrange(nr_of_classes)))

            if CLS == exp_cls:
                success[CLS] += 1
            else:
                fail[exp_cls][CLS] += 1

        print
        print "CLS: ", exp_cls, "\tSUCCESS:", success[exp_cls], "(", len(
            docs), ")"
        print "RATE:", float(success[exp_cls]) * 100 / len(docs)
    confusion_matrix(success, fail)
    print
示例#19
0
 def norma(self):
     m = mpfr(0)
     for i in range(1,self.rows):
         mi = mpfr(0)
         for j in range(1,self.columns):
             mi += abs(self.matrix[j][i])
         if (mi > m):
             m = mi
     return m
示例#20
0
    def truncate():
        nonlocal pi_val
        nonlocal pi_cal

        i, p, d = str(pi_val).partition('.')
        pi_val = mpfr('{i}.{d}'.format(i=i, d=d[:dec]))

        i, p, d = str(pi_cal).partition('.')
        pi_cal = mpfr('{i}.{d}'.format(i=i, d=d[:dec]))
 def get_random_value(self, start_pow, p=None):
     """ Sample a random value based on self.rng of p bits between [0,2^(start_pow+1)). """
     if p == None:
         p = self.context.precision
     s = mpfr(0)
     nextbit = gmpy2.exp2(start_pow)
     for i in range(1, p):
         s = gmpy2.add(s, gmpy2.mul(nextbit, mpfr(self.rng())))
         nextbit = gmpy2.exp2(start_pow - i)
     return s
示例#22
0
 def add_all_coefficients_upper_abs(self):
     with gmpy2.local_context(gmpy2.context(),
                              round=gmpy2.RoundAwayZero,
                              precision=mpfr_proxy_precision) as ctx:
         res_right = mpfr("0.0")
         for coeff in self.coefficients:
             res_right = gmpy2.add(
                 res_right, abs(mpfr(self.coefficients[coeff].upper)))
         # now the number is positive so we can round up
         return round_number_up_to_digits(res_right, digits_for_range)
    def unziptxt(self, inputFile, outputFile):
        print("Decompressing")
        #读取二进制文件
        with open("./" + inputFile, "rb") as readFile:
            while True:
                i = readFile.read(1)
                if not i:
                    break
                i = int.from_bytes(i, byteorder='big', signed=False)
                self.readData *= 256
                self.readData += i

        #将其转化为十进制
        self.readData = self.readData.digits(10)

        #消除最前的1
        self.readData = self.readData[1:]

        #总长度
        size = len(self.readData)

        #cur表示当前需要运算的大整数
        self.cur = gmpy2.mpfr(1.0)

        #log10表示大整数的数位
        self.log10 = gmpy2.mpfr(1.0)

        #初始化
        self.len = min(100, len(self.readData))  # 最多为cur读取100位进行运算
        self.finish = self.len

        #更新cur和log10
        for i in range(self.len):
            self.log10 *= 10
        for i in range(self.len):
            self.cur *= 10
            self.cur += ord(self.readData[0]) - 48
            self.readData = self.readData[1:]

        #计算字符并写文件
        with tqdm(total=size) as pbar:
            with open("./" + outputFile, "w") as writeFile:
                while True:
                    c = self.get_c()
                    pbar.update(self.finish)
                    self.finish = 0
                    #末尾的结束标记
                    if c == chr(8):
                        break
                    writeFile.write(c)

        print("the size of the compressd file:" +
              str(os.path.getsize(inputFile)) + " bytes")
        print("the size of the source file:" +
              str(os.path.getsize(outputFile)) + " bytes")
示例#24
0
 def __init__(self):
     # Set number of bits to keep around
     gmpy2.get_context().precision = 2000
     # These are values taken from the OEIS which I use when
     # checking my results.
     self.lambdainf = mpfr(
         "3.5699456718709449018420051513864989367638369115148323781079755299213628875001367775263210342163"
     )
     self.delta = mpfr(
         "4.669201609102990671853203820466201617258185577475768632745651343004134330211314"
     )
示例#25
0
def find_specific_max_mult_difference(true_val, epsilon, alpha, max_count):
    # NOTE: min_count as 0 is implicit
    class_array = [i for i in range(31)]
    score_array = [30 - abs(true_val - i) for i in range(31)]
    true_val_est = exponential_mechanism(class_array, score_array, epsilon, sensitivity = 1)

    L = gmpy2.mpfr( (alpha**(2*true_val_est + 1) + alpha**(max_count + 1)) /
                    (alpha**(2*true_val_est + 2) + alpha**(max_count)), 128)
    U = gmpy2.mpfr( (alpha**(2*true_val_est + 1) + alpha**(max_count + 1)) /
                    (alpha**(2*true_val_est) + alpha**(max_count+2)), 128)
    return( float(max(1/L, L, 1/U, U)) )
示例#26
0
文件: PyPi.py 项目: wxv/PiCalc
def machin_gmpy2(digits):
    # Precision + 20 bits for safety
    gmpy2.get_context().precision = int(math.log2(10) * digits) + 20
        
    one_5th = mpfr("1") / 5
    one_239th = mpfr("1") / 239
        
    pi_fourths = 4*gmpy2.atan(one_5th) - gmpy2.atan(one_239th)
    pi = 4*pi_fourths
        
    return pi
示例#27
0
def identity(rows,columns):
    toReturn = []
    for i in range(0,rows):
        newRow = []
        for j in range(0,columns):
            if i != j:
                newRow.append(mpfr(0))
            else:
                newRow.append(mpfr(1))
        toReturn.append(newRow)
    return toReturn
示例#28
0
def find_min_abs_interval(interval):
    with gmpy2.local_context(gmpy2.context(),
                             round=gmpy2.RoundToZero,
                             precision=mpfr_proxy_precision) as ctx:
        left = abs(mpfr(interval.lower))
        right = abs(mpfr(interval.upper))
    if left < right:
        #Now the number is positive so we can round down
        return round_number_down_to_digits(left, digits_for_range)
    else:
        #Now the number is positive so we can round down
        return round_number_down_to_digits(right, digits_for_range)
示例#29
0
def check_interval_is_zero(interval):
    with gmpy2.local_context(gmpy2.context(),
                             round=gmpy2.RoundDown,
                             precision=mpfr_proxy_precision) as ctx:
        left = mpfr(interval.lower)
    with gmpy2.local_context(gmpy2.context(),
                             round=gmpy2.RoundUp,
                             precision=mpfr_proxy_precision) as ctx:
        right = mpfr(interval.upper)
    if gmpy2.is_zero(left) and gmpy2.is_zero(right):
        return True
    return False
示例#30
0
 def random(cls, allow_inf=True) -> 'FPVector':
     bias = (1 << (cls.exponent_size - 1)) - 1
     if allow_inf:
         sign = random.choice([-1, 1])
         mantissa = gmpy2.mpfr_random(gmpy2.random_state()) + 1
         exp = random.randint(1 - bias, bias + 1)
         return cls(mantissa * sign * (gmpy2.mpfr(2)**gmpy2.mpfr(exp)))
     else:
         sign = random.choice([-1, 1])
         mantissa = gmpy2.mpfr_random(gmpy2.random_state()) + 1
         exp = random.randint(1 - bias, bias)
         return cls(mantissa * sign * (gmpy2.mpfr(2)**gmpy2.mpfr(exp)))
示例#31
0
 def round_value_to_interval(str_value):
     with gmpy2.local_context(gmpy2.context(),
                              round=gmpy2.RoundDown,
                              precision=mpfr_proxy_precision) as ctx:
         res_left = mpfr(str_value)
     with gmpy2.local_context(gmpy2.context(),
                              round=gmpy2.RoundUp,
                              precision=mpfr_proxy_precision) as ctx:
         res_right = mpfr(str_value)
     return Interval(
         round_number_down_to_digits(res_left, digits_for_range),
         round_number_up_to_digits(res_right, digits_for_range), True, True,
         digits_for_range)
示例#32
0
 def __init__(self, processId, primeNumber):
     super(Process, self).__init__()
     self.processId = processId
     self.primeNumber = mpfr(primeNumber)
     self.logicalTime = 0
     self.vectorClock = [0 for index in range(1, number_of_processes + 1)]
     self.primeClock = mpfr(1)
     self.logClock = gmpy2.log(1)
     self.logPrime = gmpy2.log(primeNumber)
     self.queue = deque()
     self.receiver_queue = deque()
     self.receivedPrimes = list()
     self.receivedPrimes.append(self.primeNumber)
示例#33
0
    def union(self, interval):
        check_intervals_digits_coincide(self, interval)
        with gmpy2.local_context(gmpy2.context(),
                                 round=gmpy2.RoundDown,
                                 precision=mpfr_proxy_precision) as ctx:
            if mpfr(self.lower) < mpfr(interval.lower):
                min = self.lower
                include_min = self.include_lower
            elif mpfr(self.lower) > mpfr(interval.lower):
                min = interval.lower
                include_min = interval.include_lower
            else:
                min = interval.lower
                include_min = interval.include_lower or self.include_lower

        with gmpy2.local_context(gmpy2.context(),
                                 round=gmpy2.RoundUp,
                                 precision=mpfr_proxy_precision) as ctx:
            if mpfr(self.upper) < mpfr(interval.upper):
                max = interval.upper
                include_max = interval.include_upper
            elif mpfr(self.upper) > mpfr(interval.upper):
                max = self.upper
                include_max = self.include_upper
            else:
                max = self.upper
                include_max = self.include_upper or interval.include_upper
        return Interval(min, max, include_min, include_max, self.digits)
示例#34
0
def calculateX(b,L,U,n):
    x = newVector(n)
    y = newVector(n)
    for i in range(0,n):
        LIKYKsum = mpfr(0)
        for k in range(0,i-1):
            LIKYKsum = LIKYKsum + L[i][k]*y[k]
        y[i] = (b[i] - LIKYKsum)/L[i][i]
    for i in range(n-1,-1,-1):
        UIKXKsum = mpfr(0)
        for k in range(i,n-1):
            UIKXKsum = UIKXKsum + U[i][k]*x[k]
        x[i] = y[i]-UIKXKsum
    return x
示例#35
0
def powers_of_two_spacing():
    exp_spacing=[]
    with gmpy2.local_context(gmpy2.context(), round=gmpy2.RoundToNearest, precision=mpfr_proxy_precision) as ctx:
        exponent=gmpy2.mpfr("0")
        while abs(exponent)<discretization_points:
            value=gmpy2.exp2(exponent)
            exp_spacing.insert(0, round_number_nearest_to_digits(value, digits_for_input_discretization))
            exponent=gmpy2.sub(exponent,gmpy2.mpfr("1"))
        exp_spacing.insert(0, "0.0")
    for index, value in enumerate(exp_spacing[:-1]):
        if value==exp_spacing[index+1]:
            print("Problem with digits in powers of 2")
            exit(-1)
    return exp_spacing
示例#36
0
文件: timing.py 项目: wxv/PiCalc
def division_test():
    start_timer()
    for i in range(1000):
        x = scale // 3
    print_timer()
    
    start_timer()
    for i in range(1000):
        x = gmpy2.mpfr(1) / 3
    print_timer()
    
    start_timer()
    for i in range(1000):
        x = gmpy2.mpfr(1) / gmpy2.mpfr(3)
    print_timer()
示例#37
0
    def reinterpret_from_bv(cls, value: BitVector) -> 'FPVector':
        if cls.size != value.size:
            raise TypeError()

        mantissa = value[:cls.mantissa_size]
        exp = value[cls.mantissa_size:-1]
        sign = value[-1:]
        assert exp.size == cls.exponent_size

        bias = (1 << (cls.exponent_size - 1)) - 1

        if exp == 0:
            if mantissa != 0:
                if not cls.ieee_compliance:
                    warnings.warn('denorm will be flushed to 0')
                    if sign[0]:
                        return cls('-0')
                    else:
                        return cls('0')
                else:
                    exp = 1 - bias
                    s = ['-0.' if sign[0] else '0.', mantissa.binary_string()]
                    s.append('e')
                    s.append(str(exp))
                    return cls(gmpy2.mpfr(''.join(s), cls.mantissa_size + 1,
                                          2))
            elif sign[0]:
                return cls('-0')
            else:
                return cls('0')
        elif exp == -1:
            if mantissa == 0:
                if sign:
                    return cls('-inf')
                else:
                    return cls('inf')
            else:
                if not cls.ieee_compliance:
                    warnings.warn('NaN will be flushed to infinity')
                return cls('nan')
        else:
            #unbias the exponent
            exp = exp - bias

            s = ['-1.' if sign[0] else '1.', mantissa.binary_string()]
            s.append('e')
            s.append(str(exp.as_sint()))
            return cls(gmpy2.mpfr(''.join(s), cls.mantissa_size + 1, 2))
示例#38
0
def home(request):
    """
	:param Input range
	:purpose Inputs a range and calls the function to calculate the fibonacci number
	:return The nth fibonacci number and total time taken to calculate the fibonacci number
	"""
    context = RequestContext(request)
    input_range = ''
    if request.method == 'POST':
        input_range = request.POST['range']
        print type(input_range)
        print "given range: ", input_range
        start_time = time.time()
        print "starting time: ", start_time
        fib = fibonacci(int(input_range))
        response = mpfr(fib)
        end_time = time.time()
        print "result: ", response
        total_time = float(end_time) - float(start_time)
        time_taken = "{0:.6f}".format(total_time)
        print "total taken time: ", time_taken
        return HttpResponse(
            json.dumps({
                'response': str(response),
                'total_time': time_taken
            }))
    else:
        return render_to_response('home.html', context)
示例#39
0
def test(m):
    rx, ry = mpfr(0), mpfr(0)
    for M in P:
        dx = m[0] - M[0]
        dy = m[1] - M[1]
        
        if dx == 0 and dy == 0:
            continue

        dist = gmpy2.sqrt(dx**2 + dy**2)
        forc = force(M, m)
        rate = forc / dist
        rx += dx * rate
        ry += dy * rate

    return (rx, ry)
def challenge(p, g, h):

    # Equation:
    #   [h/g^(x1) = (g^B)^x0] in Zp

    B = pow(2, 20)

    # Compute hash table of values for:
    #   h/g^(x1)
    hashTableX1 = {}
    for x1 in range(B):
        x = gmpy2.divm(h, gmpy2.powmod(g, x1, p), p)
        hashTableX1[x] = x1

    print("Pre compute complete!")

    # Compare values by computing
    #   (g^B)^x0
    for x0 in range(B):
        t = gmpy2.mpfr(gmpy2.powmod(gmpy2.powmod(g, B, p), x0, p)) % p

        if t in hashTableX1:

            x1 = hashTableX1[t]

            # Calculates x
            x = x0 * B + x1

            print("Value found!")
            print(x)
            break
    else:
        print("## No value found! ##")
示例#41
0
 def likelihood(self, params):
     '''
     log-likelihood function
     
     :argument params: a list of 2 parameters:
     
       * theta = params[0]
       * m     = params[1]
     :returns: log likelihood of given theta and I
     
     '''
     kda       = self._kda
     theta     = params[0]
     immig     = float(params[1]) / (1 - params[1]) * (self.community.J - 1)
     log_immig = log(immig)
     theta_s   = theta + self.community.S
     poch1 = exp(self._factor + log(theta) * self.community.S - \
                 lpoch(immig, self.community.J) + \
                 log_immig * self.community.S + lngamma(theta))
     gam_theta_s = gamma(theta_s)
     lik = mpfr(0.0)
     for abd in xrange(int(self.community.J - self.community.S)):
         lik += poch1 * exp(kda[abd] + abd * log_immig) / gam_theta_s
         gam_theta_s *= theta_s + abd
     return -log(lik)
示例#42
0
文件: utils.py 项目: fransua/ecolopy
def fast_etienne_likelihood(mod, params, kda=None, kda_x=None):
    '''
    same as Abundance inner function, but takes advantage of constant
    m value when varying only theta.

    :argument abd: Abundance object
    :argument params: list containing theta and m
    :argument kda_x: precomputed list of exp(kda + ind*immig)
    '''
    theta     = params[0]
    immig     = float (params[1]) / (1 - params[1]) * (mod.community.J - 1)
    log_immig = log (immig)
    theta_s   = theta + mod.community.S
    if not kda_x:
        kda_x = [exp(mod._kda[val] + val * log_immig) for val in \
                 xrange (mod.community.J - mod.community.S)]
    poch1 = exp (mod._factor + log (theta) * mod.community.S - \
                 lpoch (immig, mod.community.J) + \
                 log_immig * mod.community.S + lngamma(theta))
    gam_theta_s = gamma (theta_s)
    lik = mpfr(0.0)
    for val in xrange (mod.community.J - mod.community.S):
        lik += poch1 * kda_x[val] / gam_theta_s
        gam_theta_s *= theta_s + val
    return ((-log (lik)), kda_x)
    def factorization(n, delta):
        gmpy2.get_context().precision=1000000
        t = gmpy2.mpz(gmpy2.sqrt(n))
        res = gmpy2.mpfr('0.0', 1000000)
        steps = delta-t
        print "Steps: %d" % steps

        while True:

            res = gmpy2.sqrt(t**2 - n)

            if gmpy2.is_integer(res):
                break
            if res >= n/2:
                sys.stderr.write('I can\'t solve')
                exit()

            t += 1
            steps -= 1
            if steps % 1000 == 0:
                print steps

        p = t - gmpy2.mpz(res)
        q = n/p

        return {
            'p': int(q),
            'q': int(p)
        }
示例#44
0
 def _get_kda (self, verbose=True):
     '''
     compute K(D,A) according to etienne formula
     '''
     specabund = [sorted(list(set(self.community.abund))),
                  table_mpfr(self.community.abund)]
     sdiff     = len(specabund[1])
     polyn     = []
     # compute all stirling numbers taking advantage of recurrence function
     needed = {0: True}
     for i in xrange(sdiff):
         for k in xrange(1, int(specabund[0][i] + 1)):
             needed[int(specabund[0][i])] = True
     if verbose:
         stdout.write('  Getting some stirling numbers...\n')
     pre_get_stirlings(int(max(specabund[0])), needed, verbose=verbose)
     for i in xrange(sdiff):
         if verbose:
             stdout.write("\r  Computing K(D,A) at species %s out of %s" \
                          % (i+1, sdiff))
             stdout.flush ()
         sai = int(specabund[0][i])
         polyn1 = [stirling(sai, k) * factorial_div(k, sai) \
                   for k in xrange(1, sai+1)]
         polyn1 = power_polyn(polyn1, specabund[1][i]) \
                  if polyn1 else [mpfr(1.)]
         polyn = mul_polyn(polyn, polyn1)
     self._kda = [log(i) for i in polyn]
     if verbose:
         stdout.write('\n')
示例#45
0
文件: misc.py 项目: jmikulka/hpni
def _float(number):
    """
    Convert the input `number` to gmpy2.mpf2 float with high precision.

    In the gmpy2 documentation it is said that the best performance
    of the gmpy2 module is when the numbers are given as strings
    and not as Python built-in integers or floats.

    Parameters
    ----------
    number : float or str
        Float value (given as built-in float or as string) to be
        converted into gmpy2.mpfr float.

    Returns
    -------
    gmpy2.mpfr
        Input `number` converted to gmpy2.mpfr float.

    Raises
    ------
    error.NumberError
        If `number` is not convertible to gmpy2.mpfr number.

    """

    try:
        return gmpy2.mpfr(str(number))
    except:
        raise error.NumberError
    def check(self, i):
        #区间大小
        diff = self.right - self.left

        #新的左右区间
        curleft = self.left + diff * self.lp1[i]
        curright = self.left + diff * self.rp1[i]

        #读取的数转化为小数
        decimal = gmpy2.mpfr(self.cur / self.log10)
        decimal = decimal - gmpy2.floor(decimal)

        #判断是否满足要求
        if curleft > decimal:
            return False
        if curright < decimal:
            return False

        #更新区间
        self.left = curleft
        self.right = curright

        #通过decimal计算新的cur,抛弃掉cur前导多余数字,cur维持为整数防止精度缺失
        self.cur = decimal*self.log10
        self.cur = gmpy2.rint_round(self.cur)
        return True
示例#47
0
文件: bfp_gmpy2.py 项目: s390guy/SATK
    def create(self):
        ctx = gmpy2.ieee(self.length * 8)  # Emulate IEEE for requested format size
        ctx.round = self.rmodeo  # Set the requested gmpy2 rounding mode
        gmpy2.set_context(ctx)  # Make this the active context.

        # Convert the floating point string to an mpfr object
        return gmpy2.mpfr(self.fpstr)
示例#48
0
def prime_gen(dimension):
    """
    Используем алгоритм Диемитко для генерации чисел нужного порядка
    """
    start_prime = chose_start_prime(dimension)

    current_prime = mpz(start_prime)

    p = mpz(start_prime)

    repit_flag = True

    U = 0

    while p.num_digits() <= dimension:
        if repit_flag:
            repit_flag = False
            N = f_div(mpz(10**(dimension - 1)), mpz(current_prime)) + \
                f_div(mpz(10**(dimension - 1) * mpfr(random())),
                      mpz(current_prime))
            N = N + 1 if N.is_odd() else N
            U = 0
        p = (N + U) * current_prime + 1
        if pow(2, p - 1, p) == 1 and pow(2, N + U, p) != 1:
            repit_flag = True
            break
        else:
            U += 2

    return p
示例#49
0
    def factorization(n, delta):
        gmpy2.get_context().precision = 1000000
        t = gmpy2.mpz(gmpy2.sqrt(n))
        res = gmpy2.mpfr('0.0', 1000000)
        steps = delta - t
        print "Steps: %d" % steps

        while True:

            res = gmpy2.sqrt(t**2 - n)

            if gmpy2.is_integer(res):
                break
            if res >= n / 2:
                sys.stderr.write('I can\'t solve')
                exit()

            t += 1
            steps -= 1
            if steps % 1000 == 0:
                print steps

        p = t - gmpy2.mpz(res)
        q = n / p

        return {'p': int(q), 'q': int(p)}
示例#50
0
def freeTerms(A):
    b = newVector(len(A[0]))
    for i in range(0,len(A[0])):
        b[i] = mpfr(0)
        for j in range(0,len(A[0])):
            b[i] = b[i] + A[i][j]
    return b
示例#51
0
def calculateLatBitsOdd( lat,longitude):
    
    global oddMsg
    
    #calculate YZ which is to be put into message
    modHold = mpfr(modulus(lat,Dlat1))
    modHold = (modHold/Dlat1)
    modHold = modHold * math.pow(2,17)
    modHold = modHold + 0.5
    YZ = mpfr(math.floor(modHold))
    
    #calculate Rlatitude for Airborne
    Rlat1 = mpfr(1.0)
    floorHold = 1
    Rlat1 = mpfr(YZ) / math.pow(2,17)
    floorHold = (lat/mpfr(Dlat1))
    floorHold = math.floor(floorHold)
    Rlat1 = Rlat1 + mpfr(floorHold)
    Rlat1 = Rlat1 * Dlat1
    NlLat = 1
    NlLat = genNlatValue(Rlat1)
    
    #calculate Dlongitude
    Dlon1 = mpfr(1.0)
    if((NlLat-1) > 0):
        Dlon1 = (360/(mpfr(NlLat)-1));
    else:
        Dlon1 = 360
        
    #calculate XZ the decimal representation of longitude
    XZ = mpfr(1.0)
    modHold = 0
    modHold = modulus(longitude, Dlon1)
    modHold = (modHold/Dlon1)
    modHold = modHold * math.pow(2,17)
    modHold = modHold + 0.5
    XZ = math.floor(modHold)
    
    #Ensure this fits into our 17 bit space
    YZ1 = mpz(modulus(YZ,math.pow(2,17)))
    XZ1 = mpz(modulus(XZ,math.pow(2,17)))
    LatLon = mpz(1)
    YZ1 = YZ1 << 17
    LatLon = (YZ1 | XZ1)
    LatLon = (LatLon | 17179869184)
    
    #to be decided
    print "odd message : " + hex(LatLon)
    oddMsg = LatLon
    
    return 0
示例#52
0
def Numbers(n):
    i = pow(gmpy2.mpfr(3 + gmpy2.sqrt(5)), n)
    #print(i)
    i = int(gmpy2.rint_trunc(i)) % 1000
    o = i - ((i // 10) * 10)
    t = (i - ((i // 100) * 100) - o) / 10
    h = (i - t - o) / 100
    return str(h)+str(t)+str(o)
示例#53
0
文件: bfp.py 项目: mstram/SATK
 def create(self,string,round=0):
     ctx=gmpy2.ieee(self.format)
     ctx.round=MPFR_Data.rounding[round]
     gmpy2.set_context(ctx)
     fpo=gmpy2.mpfr(string)
     ctx=gmpy2.get_context()     # Get the results
     self.ctx=ctx.copy()         # Copy the context for later status
     return fpo
示例#54
0
def matrixVectorMultiplication(X, V):
    result = []
    for row in X:
        localResult = mpfr(0)
        for matrixElement,vectorElement in zip(row,V):
            localResult = localResult + matrixElement*vectorElement
        result.append(localResult)
    return result
示例#55
0
def newMatrix(n):
    matrix = []
    for i in range(0,n):
        row = []
        for j in range(0,n):
            row.append(mpfr(0))
        matrix.append(row)
    return matrix
示例#56
0
def Carpenter(p, q,r, s):
	p = gmpy2.mpfr(p)
	q = gmpy2.mpfr(q)
	r = gmpy2.mpfr(r)
	s = gmpy2.mpfr(s)
	"""
	Solves for all roots of the quartic polynomial P(x) = x^4 + px^3 + qx^2 + rx + s.
	"""
	#print "@@@ inside Carpenter", p,q,r,s
	pby4 = p/4.0
	C = ((6 * pby4) - 3*p)*pby4 + q
	D = (((-4*pby4) + 3*p)*pby4 - 2*q)*pby4 + r
	E = (((pby4 - p)* pby4 + q)*pby4 - r)*pby4 + s
	#print "C, D, E=",C, D, E
	root = None
	for zero in polyCubicRoots(2*C, (C**2 - 4*E), -D**2):
		#print "zero = ", zero
		if type(zero)== type(gmpy2.mpfr(1.0)) and zero > 0.0:
		   root = zero
		   #print "found a positive root."
		   break
	if root == None:
		return None
	sqroot = gmpy2.sqrt(root)
	Q1 = -root/4.0 - C/2.0 - D/2.0 / sqroot
	Q2 = -root/4.0 - C/2.0 + D/2.0 / sqroot
	#print "Q1,Q2=", Q1, Q2
	sqy2 = sqroot/2.0
	if Q1 >= 0.0:
	   sqQ1 = gmpy2.sqrt(Q1)
	   z1 = sqy2 + sqQ1 -pby4
	   z2 = sqy2 - sqQ1 -pby4
	else:
	   sqQ1 = gmpy2.sqrt(-Q1)
	   z1 = (sqy2-pby4,   sqQ1)
	   z2 = (sqy2-pby4, - sqQ1)
	if Q2 >= 0.0:
	   sqQ2 = gmpy2.sqrt(Q2)
	   z3 = -sqy2 - sqQ2 -pby4
	   z4 = -sqy2 + sqQ2 -pby4
	else:
	   sqQ2 = gmpy2.sqrt(-Q2)
	   z3 = (-sqy2-pby4, sqQ2)
	   z4 = (-sqy2-pby4, -sqQ2)
	return (z1, z2,z3, z4)
示例#57
0
文件: utils.py 项目: fransua/ecolopy
def mul_polyn(polyn_a, polyn_b):
    '''
    computes the product of 2 polynomials, depending of the differences in length
    of the two polynomials, this function will call one of:
    * _mul_uneq_polyn: when length of polyn_a is >= length of polyn_b, will iterate over coefficient.
    * _mul_simil_polyn: in case both polynomials have equal length, will iterate over factors.

    to test multiplication of pylnomials try equality of the two functions:
    mul_uneq_polyn(polyn_a, polyn_b, len_a, len_b) == _mul_simil_polyn(polyn_a, polyn_b, len_a, len_b)

    **Example:**
    ::

      from ecolopy_dev.utils import mul_polyn
      # (2 + 3^x + 5x^2)  * (x)
      mul_polyn([2,3,5], [0,1])
      # will return: [mpfr('0.0'), mpfr('2.0'), mpfr('3.0'), mpfr('5.0')]
      # that is: 0 + 2x + 3x^2 + 5x^3
      
    :argument polyn_a: list of indices of polynomial
    :argument polyn_b: list of indices of polynomial (e.g.: [1,3,5,0,2] for :math:`2 + 3^x + 5x^2 + 0x^3 + 2x^4`)
    :returns: a list representing multiplication of the two polynomials

    '''
    if not polyn_a:
        return polyn_b
    if not polyn_b:
        return polyn_a
    # set default values
    len_a = len (polyn_a)
    len_b = len (polyn_b)
    diff = abs (len_a - len_b)
    if len_a >= len_b:
        polyn_b = polyn_b + [mpfr(0)] * (diff)
    else:
        _  = polyn_a + [mpfr(0.)] * (diff)
        polyn_a = polyn_b[:]
        polyn_b = _
        len_a = len_b
        len_b = len (polyn_b)
    # switcher
    if len_a > len_b*2: # most
        return _mul_uneq_polyn(polyn_a, polyn_b, len_a, len_b)
    return _mul_simil_polyn(polyn_a, polyn_b, len_a, len_b)
示例#58
0
文件: timing.py 项目: wxv/PiCalc
def squareroot_test():
    start_timer()
    for i in range(100):
        x = gmpy2.isqrt(3 * scale**2)
    print_timer()
    
    start_timer()
    for i in range(100):
        x = gmpy2.sqrt(gmpy2.mpfr(3))
    print_timer()
示例#59
0
 def sentence_probability(self, token_list):
     if not token_list:
         return None
     sent_prob   = 1.0
     for token in token_list:
         word_prob = self.word_probability(token)
         if word_prob is None:
             return None
         sent_prob = gmpy2.mpfr(sent_prob * word_prob)
     return sent_prob
示例#60
0
文件: utils.py 项目: fransua/ecolopy
def factorial_div (one, two):
    '''
    computes a!/b!
    '''
    if one < two:
        return div(1., reduce (mul, xrange(one, two)))
    elif one > two:
        return reduce (mul, xrange(two, one))
    else:
        return mpfr (1.)