Example #1
0
    def test_time_init_gmpy(self):
        if gmpy is None: raise SkipTest

        t = param.Time(time_type=gmpy.mpq)
        self.assertEqual(t(), gmpy.mpq(0))
        t.advance(gmpy.mpq(0.25))
        self.assertEqual(t(), gmpy.mpq(1,4))
Example #2
0
    def processInvoice(self, doc):
        #
        #  Compute totals etc
        #

        self.lines = self.invoice.getLines()

        total_price = gmpy.mpq(0)
        for line in self.lines:
            total_price += line.getPriceVat0()

        # total price
        self.total_price_pre_discount_vat0 = total_price

        # partner discount
        self.partner_discount = invoicing.compute_partner_discount_oct2007(self.total_price_pre_discount_vat0)

        # total price after discount
        self.total_price_vat0 = self.total_price_pre_discount_vat0 - self.partner_discount

        # VAT
        self.total_vat = self.total_price_vat0 * self.vat_percentage / gmpy.mpq(100)

        # total after discount, with VAT
        self.total_price_vat = self.total_price_vat0 + self.total_vat

        #
        #  Process replacements and generate row elements
        #
        self._process_replacements(doc)
Example #3
0
    def test_time_init_gmpy(self):
        if gmpy is None: raise SkipTest

        t = param.Time(time_type=gmpy.mpq)
        self.assertEqual(t(), gmpy.mpq(0))
        t.advance(gmpy.mpq(0.25))
        self.assertEqual(t(), gmpy.mpq(1, 4))
Example #4
0
def bernoulli(n):
    """
    Returns recursively the nth bernoulli number as a fraction.
    """
    if n <= 0: return 1
    if n == 1: return gmpy.mpq(-1,2)
    if (n%2) == 1:  return 0
    return -gmpy.mpq(sum(map(lambda x:gmpy.bincoef(n+1, x)*bernoulli(x), range(n))), n+1)
Example #5
0
 def __init__(self, xx, yy):
     '''
     Initializes a Lagrange interpolation polynomial by supplying corresponding
     x and y values
     '''
     self.xx = [ gmpy.mpq(x) for x in xx ]
     self.yy = [ gmpy.mpq(y) for y in yy ]
     assert len(self.xx) == len(self.yy), "xx and yy have to be the same size"
Example #6
0
def gao(i=2,t=mpq('1/2')):
    if t==0:
        print 'found'
        return 1
    if i==N+1 or t<0 or psum[i]<t: return 0
#    hsh=(i,t)
#    if hsh in mem: return mem[hsh]
    total = gao(i+1,t) + gao(i+1,t-mpq(1)/mpq(i*i))
#    mem[hsh]=total
    return total
Example #7
0
def gao(i=2, t=mpq('1/2')):
    if t == 0:
        print 'found'
        return 1
    if i == N + 1 or t < 0 or psum[i] < t: return 0
    #    hsh=(i,t)
    #    if hsh in mem: return mem[hsh]
    total = gao(i + 1, t) + gao(i + 1, t - mpq(1) / mpq(i * i))
    #    mem[hsh]=total
    return total
Example #8
0
 def test_time_hashing_rationals_gmpy(self):
     """
     Check that hashes of fractions and gmpy mpqs match for some
     reasonable rational numbers.
     """
     if gmpy is None: raise SkipTest
     pi = "3.141592"
     hashfn = numbergen.Hash("test", input_count=1)
     self.assertEqual(hashfn(0.5), hashfn(gmpy.mpq(0.5)))
     self.assertEqual(hashfn(pi), hashfn(gmpy.mpq(3.141592)))
Example #9
0
 def test_time_hashing_rationals_gmpy(self):
     """
     Check that hashes of fractions and gmpy mpqs match for some
     reasonable rational numbers.
     """
     if gmpy is None: raise SkipTest
     pi = "3.141592"
     hashfn = numbergen.Hash("test", input_count=1)
     self.assertEqual(hashfn(0.5), hashfn(gmpy.mpq(0.5)))
     self.assertEqual(hashfn(pi), hashfn(gmpy.mpq(3.141592)))
Example #10
0
def bernoulli(n):
    """
    Returns recursively the nth bernoulli number as a fraction.
    """
    if n <= 0: return 1
    if n == 1: return gmpy.mpq(-1, 2)
    if (n % 2) == 1: return 0
    return -gmpy.mpq(
        sum(map(lambda x: gmpy.bincoef(n + 1, x) * bernoulli(x), range(n))),
        n + 1)
Example #11
0
def verify_sin_cos(N, PS, QS, bits):
    X = FixedPointBound(bits, mpq(1, 16), 0)
    m = 2
    while m * m < N:
        m += 2
    T = [None] * (m + 1)
    T[1] = X.mul(X)
    T[2] = T[1].mul(T[1])
    for k in range(4, m + 1, 2):
        T[k - 1] = T[k // 2].mul(T[k // 2 - 1])
        T[k] = T[k // 2].mul(T[k // 2])
    for cosorsin in range(2):
        S = FixedPointBound(bits, 0, 0)
        for k in range(N - 1, -1, -1):
            c, d, e = PS[2 * k + cosorsin], QS[2 * k +
                                               cosorsin], QS[2 * k + cosorsin +
                                                             2]
            if d != e and k < N - 1:
                # if alternating, adding e must give a nonnegative number
                S.check_le_int(e)
                # adding e must not overflow
                S.add(e).check_overflow_1()
                S = S.div(e)
                # if alternating, adding 1 must not overflow
                S.add(1).check_overflow_1()
            if k % m == 0:
                # if alternating, adding c must give a nonnegative number
                S.check_le_int(c)
                S = S.add(c)
                S.check_overflow_1()
                if k != 0:
                    S = S.mul(T[m])
                    S.check_overflow_1()
            else:
                S = S.addmul(T[k % m], c)
                S.check_overflow_1()
        if cosorsin == 0:
            S = S.div(mpq(QS[0]))
            S.check_overflow_1()
            # note: top limb must actually be 0 or 1;
            # but this follows by S.rad <= 2
            print N, float(S.mid), float(S.rad)
            assert S.rad <= 2
        else:
            S = S.div(mpq(QS[0]))
            S.check_overflow_1()
            S = S.mul(X)
            S.check_overflow_0()
            print N, float(S.mid), float(S.rad)
            assert S.rad <= 2
def HG_split_diode_coefficient_analytical(n1,n2):
    """ Using an analytical equation to compute beat coefficients
    betwween mode n1 and n2 on a split photo detector. Uses arbitrary
    precision (from gmpy) because otherwise errors get very large
    for n1,n2>30. This is for comparison with the numerical method
    HG_split_diode_coefficient_numerical only. """
    import gmpy
    
    temp=gmpy.mpq(0.0)
    for l in np.arange(0,n1/2+1):
        for k in np.arange(0,(n2-1)/2+1):
            temp +=  gmpy.mpq(pow((-1.0/4.0),l+k)*gmpy.mpz(factorial((n2+n1-1)/2-l-k))/gmpy.mpz((factorial(l)*factorial(k)*factorial(n1-2*l)*factorial(n2-2*k))))

    c_n1n2=gmpy.mpq(temp*gmpy.mpq(math.sqrt(2.0**(n1+n2)*gmpy.mpz(factorial(n1)*factorial(n2))/np.pi)))
    return float(gmpy.mpf(c_n1n2))
Example #13
0
    def test_time_hashing_integers_gmpy(self):
        """
        Check that hashes for gmpy values at the integers also matches
        those of ints, fractions and strings.
        """
        if gmpy is None: raise SkipTest
        hashfn = numbergen.Hash("test", input_count=1)
        hash_1 = hashfn(1)
        hash_42 = hashfn(42)

        self.assertEqual(hash_1, hashfn(gmpy.mpq(1)))
        self.assertEqual(hash_1, hashfn(1))

        self.assertEqual(hash_42, hashfn(gmpy.mpq(42)))
        self.assertEqual(hash_42, hashfn(42))
Example #14
0
    def test_time_hashing_integers_gmpy(self):
        """
        Check that hashes for gmpy values at the integers also matches
        those of ints, fractions and strings.
        """
        if gmpy is None: raise SkipTest
        hashfn = numbergen.Hash("test", input_count=1)
        hash_1 = hashfn(1)
        hash_42 = hashfn(42)

        self.assertEqual(hash_1, hashfn(gmpy.mpq(1)))
        self.assertEqual(hash_1, hashfn(1))

        self.assertEqual(hash_42, hashfn(gmpy.mpq(42)))
        self.assertEqual(hash_42, hashfn(42))
def verify_sin_cos(N, PS, QS, bits):
    X = FixedPointBound(bits, mpq(1,16), 0)
    m = 2
    while m * m < N:
        m += 2
    T = [None] * (m+1)
    T[1] = X.mul(X)
    T[2] = T[1].mul(T[1])
    for k in range(4, m + 1, 2):
        T[k-1] = T[k//2].mul(T[k//2-1])
        T[k] = T[k//2].mul(T[k//2])
    for cosorsin in range(2):
        S = FixedPointBound(bits, 0, 0)
        for k in range(N-1, -1, -1):
            c, d, e = PS[2*k+cosorsin], QS[2*k+cosorsin], QS[2*k+cosorsin+2]
            if d != e and k < N-1:
                # if alternating, adding e must give a nonnegative number
                S.check_le_int(e)
                # adding e must not overflow
                S.add(e).check_overflow_1()
                S = S.div(e)
                # if alternating, adding 1 must not overflow
                S.add(1).check_overflow_1()
            if k % m == 0:
                # if alternating, adding c must give a nonnegative number
                S.check_le_int(c)
                S = S.add(c)
                S.check_overflow_1()
                if k != 0:
                    S = S.mul(T[m])
                    S.check_overflow_1()
            else:
                S = S.addmul(T[k % m], c)
                S.check_overflow_1()
        if cosorsin == 0:
            S = S.div(mpq(QS[0]))
            S.check_overflow_1()
            # note: top limb must actually be 0 or 1;
            # but this follows by S.rad <= 2
            print N, float(S.mid), float(S.rad)
            assert S.rad <= 2
        else:
            S = S.div(mpq(QS[0]))
            S.check_overflow_1()
            S = S.mul(X)
            S.check_overflow_0()
            print N, float(S.mid), float(S.rad)
            assert S.rad <= 2
Example #16
0
 def share(cls, D, k, n, P=None):
     '''
     Generates shares for a secret consisting of a natural number z ∈ N
     D: Secret number
     k: Amount of shares needed to reconstruct D
     n: Amount of unique shares to create
     P: Finite field size, must be prime
        Constraints: P > D and P > n
        if P is None then a suitable prime will be generated
     
     Returns:
         (P, shares)
     '''
     
     if P is None or not is_probable_prime(P):            
         P = generate_prime_bigger_than(random.randint(max(D, n),100000000*max(D, n)))
     assert P > D, "P must be bigger than D"
     assert P > n, "P must be bigger than n"
     assert D >= 0, "D must be non-negative"
     if D > 0:
         a = [ random.randint(0, D-1) for _ in range(k-1) ] + [D]
     else:
         a = [ random.randint(0, 1000) for _ in range(k-1) ] + [D]
     shares = []
     for i in range(n):
         x = i+1
         D_i = gmpy.mpq(cls.polyval(a, P, x))
         if D_i.denominator == 1:
             D_i = int(gmpy.mpz(D_i))
         shares.append( (x, D_i) )
     return (P, shares)
Example #17
0
def _mpq_pickle_support():
    """Allow instances of gmpy.mpq to pickle."""
    from gmpy import mpq
    mpq_type = type(mpq(
        1, 10))  # gmpy doesn't appear to expose the type another way
    import copy_reg
    copy_reg.pickle(mpq_type, lambda q: (mpq, (q.digits(), )))
Example #18
0
def go(w, h, d, x, y):
    x = gmpy.mpq(x)
    y = gmpy.mpq(y)
    angles = set()
    four = list(itertools.product([x, 2 * w - x], [y, 2 * h - y]))
    for i in xrange(-55, 55):
        for j in xrange(-55, 55):
            for x1, y1 in four:
                x2, y2 = x1 + 2 * w * i, y1 + 2 * h * j
                if (x - x2) ** 2 + (y - y2) ** 2 <= d * d + 1e-9:
                    if x != x2:
                        angles.add((sign(x - x2), (y - y2) / (x - x2)))
                    else:
                        angles.add((sign(y - y2), "inf"))
    angles.remove((0, "inf"))
    return len(angles)
Example #19
0
 def polyval(cls, a, x):
     '''
     Evaluates secret polynomial consisting of coefficients a at x
     '''
     y = gmpy.mpq(0)
     for i, a_i in enumerate(reversed(a)):
         y += a_i*x**i
     return y
Example #20
0
def _mpq_pickle_support():
    """Allow instances of gmpy.mpq to pickle."""
    from gmpy import mpq

    mpq_type = type(mpq(1, 10))  # gmpy doesn't appear to expose the type another way
    import copy_reg

    copy_reg.pickle(mpq_type, lambda q: (mpq, (q.digits(),)))
Example #21
0
def pi_gen():
    x = 0
    n = 1
    while 1:
        p = mpq((120*n-89)*n+16, (((512*n-1024)*n+712)*n-206)*n+21)
        x = mod1(16*x + p)
        n += 1
        yield int(16*x)
Example #22
0
 def test_time_init_gmpy_advanced(self):
     if gmpy is None: raise SkipTest
     t = param.Time(time_type=gmpy.mpq,
                    timestep=gmpy.mpq(0.25),
                    until=1.5)
     self.assertEqual(t(), gmpy.mpq(0,1))
     t(0.5)
     self.assertEqual(t(), gmpy.mpq(1,2))
     with t:
         t.advance(0.25)
         self.assertEqual(t(), gmpy.mpq(3,4))
     self.assertEqual(t(), gmpy.mpq(1,2))
     tvals = [tval for tval in t]
     self.assertEqual(tvals, [gmpy.mpq(1,2),
                              gmpy.mpq(3,4),
                              gmpy.mpq(1,1),
                              gmpy.mpq(5,4),
                              gmpy.mpq(3,2)])
Example #23
0
def pi_gen():
    x = 0
    n = 1
    while 1:
        p = mpq((120 * n - 89) * n + 16,
                (((512 * n - 1024) * n + 712) * n - 206) * n + 21)
        x = mod1(16 * x + p)
        n += 1
        yield int(16 * x)
Example #24
0
 def test_time_init_gmpy_advanced(self):
     if gmpy is None: raise SkipTest
     t = param.Time(time_type=gmpy.mpq, timestep=gmpy.mpq(0.25), until=1.5)
     self.assertEqual(t(), gmpy.mpq(0, 1))
     t(0.5)
     self.assertEqual(t(), gmpy.mpq(1, 2))
     with t:
         t.advance(0.25)
         self.assertEqual(t(), gmpy.mpq(3, 4))
     self.assertEqual(t(), gmpy.mpq(1, 2))
     tvals = [tval for tval in t]
     self.assertEqual(tvals, [
         gmpy.mpq(1, 2),
         gmpy.mpq(3, 4),
         gmpy.mpq(1, 1),
         gmpy.mpq(5, 4),
         gmpy.mpq(3, 2)
     ])
Example #25
0
def atan_coefficients(NN, bits):
    ps = []
    qs = []
    temp = []
    Q = 1
    for k in range(2 * NN + 50):
        p = 1
        q = 2 * k + 1
        if lcm(Q, q) < 2**bits:
            temp.append(mpq(p, q))
            Q = lcm(Q, q)
        else:
            for a in temp:
                ps.append(int(a * Q))
                qs.append(int(Q))
            Q = q
            temp = [mpq(p, q)]
    return ps[:NN], qs[:NN]
Example #26
0
 def polyval(cls, a, p, x):
     '''
     Evaluates secret polynomial consisting of coefficients a at x modulo P
     '''
     y = gmpy.mpq(0)
     for i, a_i in enumerate(reversed(a)):
         y += (a_i * ((x**i) % p)) % p
         y %= p
     return y
def atan_coefficients(NN, bits):
    ps = []
    qs = []
    temp = []
    Q = 1
    for k in range(2*NN+50):
        p = 1
        q = 2*k+1
        if lcm(Q, q) < 2**bits:
            temp.append(mpq(p,q))
            Q = lcm(Q, q)
        else:
            for a in temp:
                ps.append(int(a * Q))
                qs.append(int(Q))
            Q = q
            temp = [mpq(p,q)]
    return ps[:NN], qs[:NN]
Example #28
0
def unpickle_mp(value):
    type, value = value
    if type == 'z':
        return mpz(value)
    elif type == 'q':
        return mpq(value)
    elif type == 'f':
        return g_mpf(value)
    else:
        return value
Example #29
0
def unpickle_mp(value):
    type, value = value
    if type == 'z':
        return mpz(value)
    elif type == 'q':
        return mpq(value)
    elif type == 'f':
        return g_mpf(value)
    else:
        return value
def test_sympify_gmpy():
    try:
        import gmpy
    except ImportError:
        pass
    else:
        value = sympify(gmpy.mpz(1000001))
        assert value == Integer(1000001) and type(value) is Integer

        value = sympify(gmpy.mpq(101, 127))
        assert value == Rational(101, 127) and type(value) is Rational
Example #31
0
def test_sympify_gmpy():
    try:
        import gmpy
    except ImportError:
        pass
    else:
        value = sympify(gmpy.mpz(1000001))
        assert value == Integer(1000001) and type(value) is Integer

        value = sympify(gmpy.mpq(101, 127))
        assert value == Rational(101, 127) and type(value) is Rational
Example #32
0
 def _at(self, x):
     '''
     Computes polynomial value L(x) modulo P
     '''
     k = len(self.xx)
     z = gmpy.mpq(0)
     for j in range(k):
         y = self.yy[j]
         b = self._base(j,x)
         z += (y*b)
         z %= self.P
     return z
Example #33
0
 def _format_gmpy_price(self, x, eurosign=True):
     t = x * gmpy.mpq(100)   # 123.4567 -> 12345.67
     t = int(gmpy.digits(t)) # 12345
     full = t / 100
     part = t % 100
     esign = ''
     if eurosign:
         esign = u' \u20ac'
     if full == 0:
         return u'0,%02d%s' % (part, esign)
     else:
         return u'%d,%02d%s' % (full, part, esign)
Example #34
0
def bernoulli(m):
    assert m >= 0
    if m == 0:
        return 1
    if m == 1:
        return -mpq(1, 2)
    if m % 6 == 0:
        return b0mod6(m)
    if m % 6 == 2:
        return b2mod6(m)
    if m % 6 == 4:
        return b4mod6(m)
    return 0
def verify_atan(N, PS, QS, bits):
    X = FixedPointBound(bits, mpq(1,16), 0)
    S = FixedPointBound(bits, 0, 0)
    m = 2
    while m * m < N:
        m += 2
    T = [None] * (m+1)
    T[1] = X.mul(X)
    T[2] = T[1].mul(T[1])
    for k in range(4, m + 1, 2):
        T[k-1] = T[k//2].mul(T[k//2-1])
        T[k] = T[k//2].mul(T[k//2])
    for k in range(N-1, -1, -1):
        c, d, e = PS[k], QS[k], QS[k+1]
        if d != e and k < N-1:
            # if alternating, adding e must give a nonnegative number
            S.check_le_int(e)
            # adding e must not overflow
            S.add(e).check_overflow_1()
            S = S.mul(d).div(e)
            # if alternating, adding d must not overflow
            S.add(d).check_overflow_1()
        if k % m == 0:
            # if alternating, adding c must give a nonnegative number
            S.check_le_int(c)
            S = S.add(c)
            S.check_overflow_1()
            if k != 0:
                S = S.mul(T[m])
                S.check_overflow_1()
        else:
            S = S.addmul(T[k % m], c)
            S.check_overflow_1()
    S = S.div(mpq(QS[0]))
    S = S.mul(X)
    S.check_overflow_0()
    print N, float(S.mid), float(S.rad)
    assert S.rad <= 2
Example #36
0
def verify_atan(N, PS, QS, bits):
    X = FixedPointBound(bits, mpq(1, 16), 0)
    S = FixedPointBound(bits, 0, 0)
    m = 2
    while m * m < N:
        m += 2
    T = [None] * (m + 1)
    T[1] = X.mul(X)
    T[2] = T[1].mul(T[1])
    for k in range(4, m + 1, 2):
        T[k - 1] = T[k // 2].mul(T[k // 2 - 1])
        T[k] = T[k // 2].mul(T[k // 2])
    for k in range(N - 1, -1, -1):
        c, d, e = PS[k], QS[k], QS[k + 1]
        if d != e and k < N - 1:
            # if alternating, adding e must give a nonnegative number
            S.check_le_int(e)
            # adding e must not overflow
            S.add(e).check_overflow_1()
            S = S.mul(d).div(e)
            # if alternating, adding d must not overflow
            S.add(d).check_overflow_1()
        if k % m == 0:
            # if alternating, adding c must give a nonnegative number
            S.check_le_int(c)
            S = S.add(c)
            S.check_overflow_1()
            if k != 0:
                S = S.mul(T[m])
                S.check_overflow_1()
        else:
            S = S.addmul(T[k % m], c)
            S.check_overflow_1()
    S = S.div(mpq(QS[0]))
    S = S.mul(X)
    S.check_overflow_0()
    print N, float(S.mid), float(S.rad)
    assert S.rad <= 2
 def mul(self, other):
     if isinstance(other, FixedPointBound):
         MAX_ULP = mpq(1, 2**self.bits)
         mid = self.mid * other.mid
         rad = 0
         rad += self.rad * other.mid  # ulp
         rad += self.mid * other.rad  # ulp
         rad += self.rad * other.rad * MAX_ULP  # ulp
         rad += 1   # ulp rounding
     else:
         assert other == int(other) and other >= 0
         mid = self.mid * int(other)
         rad = self.rad * int(other)
     return FixedPointBound(self.bits, mid, rad)
Example #38
0
 def _base(self, j, x):
     '''
     Compute value of base polynomial l_j at position x
     j: Index of base polynomial
     x: Position to evaluate polynomial at
     '''
     l = 1
     k = len(self.xx)
     x = gmpy.mpq(x)
     for m in range(k):
         if j==m:
             continue
         l *= (x-self.xx[m])/(self.xx[j]-self.xx[m])
     return l
Example #39
0
 def mul(self, other):
     if isinstance(other, FixedPointBound):
         MAX_ULP = mpq(1, 2**self.bits)
         mid = self.mid * other.mid
         rad = 0
         rad += self.rad * other.mid  # ulp
         rad += self.mid * other.rad  # ulp
         rad += self.rad * other.rad * MAX_ULP  # ulp
         rad += 1  # ulp rounding
     else:
         assert other == int(other) and other >= 0
         mid = self.mid * int(other)
         rad = self.rad * int(other)
     return FixedPointBound(self.bits, mid, rad)
Example #40
0
 def share(cls, D, k, n):
     '''
     Generates shares for a secret consisting of a natural number z ∈ N
     D: Secret number
     k: Amount of shares needed to reconstruct D
     n: Amount of unique shares to create
     
     Returns pairs of (x,f(x))
     '''
     
     # Prepare polynomial
     a = [ random.randint(-D,D) for _ in range(k-1) ] + [D]
     for i in range(n):
         x = i+1
         D_i = gmpy.mpq(cls.polyval(a, x))
         if D_i.denominator == 1:
             D_i = gmpy.mpz(D_i)
         yield (x, D_i)
Example #41
0
def perplexity(probs, words):
	global use_fractions
	print "perplexity use_fractions: %s" % use_fractions
	n = len(probs) - 1
	if use_fractions:
		prob = gmpy.mpq(1,1)
	else:
		prob = 0
	word_list = []
	i = 0
	for w in words:
		i += 1
		if i % 10000 == 0:
			print "processing word %d" % i
		word_list.append(w)
		if len(word_list) > n:
			word_list.pop(0)
		temp_words = list(word_list)
		while(True):
			if tuple(temp_words) in probs[len(temp_words)]:
				if use_fractions:
					prob *= probs[len(temp_words)][tuple(temp_words)]
				else:
					prob += probs[len(temp_words)][tuple(temp_words)]
				break
			else:
				unk_gram = list(temp_words[:-1])
				unk_gram.append(filters.UNK)
				if tuple(unk_gram) in probs[len(unk_gram)]:
					if use_fractions:
						prob *= probs[len(unk_gram)][tuple(unk_gram)]
					else:
						prob += probs[len(unk_gram)][tuple(unk_gram)]
					break
				else:
					temp_words.pop(0)
	print "prob= %s" % prob
	print "len(words)= %s" % len(words)
	if use_fractions:
		print "Computing perplexity with arbitrary precision"
		return mp.power((mp.mpf(prob.denom())/mp.mpf(prob.numer())), 1.0/len(words))
	else:
		print "Computing perplexity with logarithms"
		return math.exp(-prob/len(words))
Example #42
0
def intersects(i, j):
    xi1,yi1,xi2,yi2=p[i][0],p[i][1],p[i][2],p[i][3]
    xj1,yj1,xj2,yj2=p[j][0],p[j][1],p[j][2],p[j][3]
    if sgn(sgn((xj1-xi1)*(yi2-yi1)-(xi2-xi1)*(yj1-yi1)) * sgn((xj2-xi1)*(yi2-yi1)-(xi2-xi1)*(yj2-yi1))) >= 0: return False
    if sgn(sgn((xi1-xj1)*(yj2-yj1)-(xj2-xj1)*(yi1-yj1)) * sgn((xi2-xj1)*(yj2-yj1)-(xj2-xj1)*(yi2-yj1))) >= 0: return False
    xp=None
    if xi2==xi1: xp=xi1
    else: mi=mpq(yi2-yi1)/mpq(xi2-xi1)
    if xj2==xj1: xp=xj1
    else: mj=mpq(yj2-yj1)/mpq(xj2-xj1)
    if xp==None: xp=mpq(yj1-yi1+mi*xi1-mj*xj1)/mpq(mi-mj)
    if xi1!=xi2: yp=mi*(xp-xi1)+yi1
    else: yp=mj*(xp-xj1)+yj1
    return (xp,yp)
Example #43
0
def compute_partner_discount_oct2007(monthly_inv_vat0):
    t = gmpy.mpq(monthly_inv_vat0)

    disc = gmpy.mpq(0)

    # cumulative discount is computed starting from highest
    # discount rate
    for [limit, percentage] in [[10000, 30], [5000, 25], [2500, 20],
                                [1000, 15], [500, 10]]:
        excess = t - gmpy.mpq(limit)
        if excess > gmpy.mpq(0):
            disc += excess * gmpy.mpq(percentage) / gmpy.mpq(100)
            t = limit

    return disc
Example #44
0
def dec_to_str(x):
    '''
    Converts base 257 number to bytes
    '''
    l = []
    running = gmpy.mpq(x)
    
    if x > 0:
        # Find count of digits of number in base 257 by computing log_257(x)
        i = int(np.ceil(np.log10(float(x))/np.log10(257)))+1
    else:
        return ''
        # To account for float-inaccuracies, find correct bound via integer
        # based computations
    while x//257**i == 0:
        i -= 1
    
    while running > 0:
        q, r = divmod(running, 257**i)
        l.append(chr(int(q-1)))
        running = r
        i -= 1
    return "".join(l)
Example #45
0
def compute_partner_discount_oct2007(monthly_inv_vat0):
    t = gmpy.mpq(monthly_inv_vat0)

    disc = gmpy.mpq(0)

    # cumulative discount is computed starting from highest
    # discount rate
    for [limit, percentage] in [ [ 10000, 30 ],
                                 [ 5000, 25 ],
                                 [ 2500, 20 ],
                                 [ 1000, 15 ],
                                 [ 500, 10 ] ]:
        excess = t - gmpy.mpq(limit)
        if excess > gmpy.mpq(0):
            disc += excess * gmpy.mpq(percentage) / gmpy.mpq(100)
            t = limit

    return disc
Example #46
0
def probabilities(ngrams):
	global use_fractions
	print "probabilities use_fractions: %s" % use_fractions
	totals = [dict_sum(x) for x in ngrams]
	probabilities = []

	prevgram = None
	for ngram in ngrams:
		d = {}
		for k in ngram.keys():
			prefix = k[0:-1]
			numer = ngram[k]
			if prefix in prevgram:
				# more than unigram
				denom = prevgram[prefix]
			else:
				denom = totals[1]
			if use_fractions:
				d[k] = gmpy.mpq(numer, denom)
			else:
				d[k] = log(numer) - log(denom)
		probabilities.append(d)
		prevgram = ngram
	return probabilities
Example #47
0
def intersects(i, j):
    xi1, yi1, xi2, yi2 = p[i][0], p[i][1], p[i][2], p[i][3]
    xj1, yj1, xj2, yj2 = p[j][0], p[j][1], p[j][2], p[j][3]
    if sgn(
            sgn((xj1 - xi1) * (yi2 - yi1) - (xi2 - xi1) *
                (yj1 - yi1)) * sgn((xj2 - xi1) * (yi2 - yi1) - (xi2 - xi1) *
                                   (yj2 - yi1))) >= 0:
        return False
    if sgn(
            sgn((xi1 - xj1) * (yj2 - yj1) - (xj2 - xj1) *
                (yi1 - yj1)) * sgn((xi2 - xj1) * (yj2 - yj1) - (xj2 - xj1) *
                                   (yi2 - yj1))) >= 0:
        return False
    xp = None
    if xi2 == xi1: xp = xi1
    else: mi = mpq(yi2 - yi1) / mpq(xi2 - xi1)
    if xj2 == xj1: xp = xj1
    else: mj = mpq(yj2 - yj1) / mpq(xj2 - xj1)
    if xp == None: xp = mpq(yj1 - yi1 + mi * xi1 - mj * xj1) / mpq(mi - mj)
    if xi1 != xi2: yp = mi * (xp - xi1) + yi1
    else: yp = mj * (xp - xj1) + yj1
    return (xp, yp)
Example #48
0
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Aradığımız kesir 3/7'ye çok yakın olacağından n'i 1'den 10^6'ya kadar arttırırken m'i de n/m~=3/7 olacak şekilde m=7n/3 ile başlatıp 3/7'ye çok yakın olan 299999/700000 ile kıyaslıyoruz.
from gmpy import mpq

liste = set()
LIMIT = 10**6

for n in range(1, LIMIT+1):
    for m in range((7*n//3), LIMIT+1):
        if(mpq(n,m)<mpq(299999,700000)):
            break
        if(mpq(n,m)>mpq(3,7)):
            continue
        liste.add(mpq(n,m))
p = sorted(liste).index(mpq(3,7))

print(sorted(liste)[p-1])
        for k in [
                -1, 1, 7, 11, -(2**15), 2**16, 2**30, 2**31, 2**32, 2**33,
                2**61, -(2**62), 2**63, 2**64
        ]:
            val = k * (s + i)
            assert hash(val) == hash(gmpy.mpz(val))

print("hash tests for integer values passed")

for d in [1, -2, 3, -47, m, m * 2]:
    for s in [0, m // 2, m, m * 2, m * m]:
        for i in range(-10, 10):
            for k in [
                    -1, 1, 7, 11, -(2**15), 2**16, 2**30, 2**31, 2**32, 2**33,
                    2**61, -(2**62), 2**63, 2**64
            ]:
                val = k * (s + i)
                if val:
                    assert hash(fractions.Fraction(d, val)) == hash(
                        gmpy.mpq(d, val)), (d, val,
                                            hash(fractions.Fraction(d, val)),
                                            hash(gmpy.mpq(d, val)))
                if d:
                    assert hash(fractions.Fraction(val, d)) == hash(
                        gmpy.mpq(val,
                                 d)), (val, d, hash(fractions.Fraction(val,
                                                                       d)),
                                       hash(gmpy.mpq(val, d)))

print("hash tests for rational values passed")
Example #50
0
 def div(self, other):
     assert other == int(other) and other >= 0
     mid = self.mid / mpq(other)
     rad = self.rad / mpq(other) + 1
     return FixedPointBound(self.bits, mid, rad)
Example #51
0
 def __init__(self, bits, mid, rad):
     self.bits = bits
     self.mid = mpq(mid)
     self.rad = mpq(rad)  # rad is in ulp
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Aradığımız kesir 3/7'ye çok yakın olacağından n'i 1'den 10^6'ya kadar arttırırken m'i de n/m~=3/7 olacak şekilde m=7n/3 ile başlatıp 3/7'ye çok yakın olan 299999/700000 ile kıyaslıyoruz.
from gmpy import mpq

liste = set()
LIMIT = 10**6

for n in range(1, LIMIT + 1):
    for m in range((7 * n // 3), LIMIT + 1):
        if (mpq(n, m) < mpq(299999, 700000)):
            break
        if (mpq(n, m) > mpq(3, 7)):
            continue
        liste.add(mpq(n, m))
p = sorted(liste).index(mpq(3, 7))

print(sorted(liste)[p - 1])
Example #53
0
 def check_le_int(self, c):
     # check that |self| <= c
     MAX_ULP = mpq(1, 2**self.bits)
     assert self.mid + self.rad * MAX_ULP <= c
Example #54
0
def CalculateProbability(a, b, c, d):
    return mpq(bincoef(a + b, a) * bincoef(c + d, c), bincoef(a + b + c + d, a + c))
Example #55
0
#       or better to allow decimal/most-anything-else interoperability!-)
# relies on Tim Peters' "doctest.py" test-driver
r'''
>>> filter(lambda x: not x.startswith('__'), dir(f))
['_copy', 'binary', 'ceil', 'digits', 'f2q', 'floor', 'getprec', 'getrprec', 'qdiv', 'reldiff', 'round', 'setprec', 'sign', 'sqrt', 'trunc']
>>>
'''
try:
    import decimal as _d
except ImportError:
    _d = None

import gmpy as _g, doctest, sys
__test__ = {}
f = _g.mpf('123.456')
q = _g.mpq('789123/1000')
z = _g.mpz('234')
if _d: d = _d.Decimal('12.34')

__test__['elemop']=\
r'''
>>> print _g.mpz(23) == _d.Decimal(23)
True
>>> print _g.mpz(d)
12
>>> print _g.mpq(d)
617/50
>>> print _g.mpf(d)
12.34
>>> print f+d
135.796
Example #56
0
 def check_overflow_0(self):
     # check that self fits 0 integral limbs
     MAX_ULP = mpq(1, 2**self.bits)
     assert self.mid + self.rad * MAX_ULP < 1 - MAX_ULP
def CalculateProbability(a, b, c, d):
    return mpq(
        bincoef(a + b, a) * bincoef(c + d, c), bincoef(a + b + c + d, a + c))
Example #58
0
 def check_overflow_1(self):
     # check that self fits 1 integral limb
     MAX_ULP = mpq(1, 2**self.bits)
     assert self.mid + self.rad * MAX_ULP < 2**self.bits - MAX_ULP