Exemple #1
0
class Tempo:
    """
    tempo: the tempo value, relative to the referent
    referent: the value for which tempo is given. 1=quarter note, 1/2=8th note
    """
    tempo: F
    referent: F = F(1)

    @property
    def quarterTempo(self) -> F:
        return F(1)/self.referent*self.tempo
 def test_mixed_comparisons(self):
     test_values = [
         float('-inf'),
         D('-1e425000000'), -1e+308,
         F(-22, 7), -3.14, -2, 0.0, 1e-320, True,
         F('1.2'),
         D('1.3'),
         float('1.4'),
         F(275807, 195025),
         D('1.414213562373095048801688724'),
         F(114243, 80782),
         F(473596569, 84615), 7e+200,
         D('infinity')
     ]
     for i, first in enumerate(test_values):
         for second in test_values[i + 1:]:
             self.assertLess(first, second)
             self.assertLessEqual(first, second)
             self.assertGreater(second, first)
             self.assertGreaterEqual(second, first)
    def test_rational_unop(self):
        ''' test unary operators on constructible instances 
        representing rationals '''
        from constructible import Constructible
        from fractions import Fraction as F
        from operator import pos, neg

        for op in (pos, neg):
            with self.subTest(op=op):
                for a in [
                        F(1, 2),
                        F(-1, 2),
                        F(12, 25),
                        F(4, 3), 7, 0, -10,
                        F(0)
                ]:
                    result = op(Constructible(a))
                    self.assertEqual(result.a, op(a))
                    self.assertFalse(result.b)
                    self.assertFalse(result.field)
 def test_binary_floats(self):
     self.check_equal_hash(0.0, -0.0)
     self.check_equal_hash(0.0, D(0))
     self.check_equal_hash(-0.0, D(0))
     self.check_equal_hash(-0.0, D('-0.0'))
     self.check_equal_hash(0.0, F(0))
     self.check_equal_hash(float('inf'), D('inf'))
     self.check_equal_hash(float('-inf'), D('-inf'))
     for _ in range(1000):
         x = random.random() * math.exp(random.random() * 200.0 - 100.0)
         self.check_equal_hash(x, D.from_float(x))
         self.check_equal_hash(x, F.from_float(x))
Exemple #5
0
def legendrePn(n, x):
    """
	Legendre polynomials.
	"""
    from pyranha.math import factorial
    from fractions import Fraction as F
    temp = 0
    for k in range(0, int(n / 2) + 1):
        temp = temp + (-1)**k * F(
            factorial(2 * (n - k)), 2**n * factorial(k) * factorial(n - k) *
            factorial(n - 2 * k)) * x**(n - 2 * k)
    return temp
Exemple #6
0
 def __rsub__(self, o: object) -> ABSqrtC:
     if isinstance(o, ABSqrtC):
         radical = o.get_common_radical(self)
         return ABSqrtC(o._add - self._add, o._factor - self._factor,
                        radical)
     if isinstance(o, _NumTypes):
         return ABSqrtC(
             (o if isinstance(o, F) else F(o)) - self._add,
             -self._factor,
             self._radical,
         )
     return NotImplemented
Exemple #7
0
def sample_distribution(N: int):
    histories = itertools.product(DIRECTIONS, repeat=N)
    p_single = F(1, len(DIRECTIONS)**N)

    final_distribution = collections.defaultdict(F)
    for history in histories:
        time_function = {-(i + 1): h for (i, h) in enumerate(history)}
        outcome = monte_carlo_exact(time_function)
        final_distribution[outcome] += p_single

    assert sum(final_distribution.values()) == 1
    return dict(final_distribution)
Exemple #8
0
def solution():
    f = F(1, 2)
    iteration_no = 1
    cnt = 0
    while iteration_no < 1000:
        n = f.numerator
        d = f.denominator
        if len(str(n + d)) > len(str(d)):
            cnt += 1
        f = 1 / (2 + f)
        iteration_no += 1
    return cnt
    def solve_rows(k, i, row_sum, partial_sum):
        if i == cols:
            if k == 0:  # 2
                return F(1, 2) == partial_sum + F(row_sum, primes_exp[0])
            if row_sum % primes_exp[k] == 0:
                return solve_rows(k - 1, 0, 0,
                                  partial_sum + row_sum // primes_exp[k])
            return 0
        if mat[k][i] == 0:
            return solve_rows(k, i + 1, row_sum, partial_sum)
        if res[i] != -1:
            return solve_rows(k, i + 1, row_sum + mat[k][i] * res[i],
                              partial_sum)

        count = 0
        res[i] = 0
        count += solve_rows(k, i + 1, row_sum, partial_sum)
        res[i] = 1
        count += solve_rows(k, i + 1, row_sum + mat[k][i], partial_sum)
        res[i] = -1
        return count
Exemple #10
0
 def V(self, phi, j):
     ans = P(0)
     Phi_p = numpy.exp(-phi[0].coef[0] * sqrt(2. / 3))
     s = F(2 * int(numpy.sign(phi[0].coef[1])), 3)
     if j == 2:
         ans = ans + 1
     if j >= 2 - s:
         ans = ans - 2 * Phi_p * BellC(-sqrt(2. / 3) * phi, j - (2 - s))
     if j >= 2 - 2 * s:
         ans = ans + Phi_p**2 * BellC(-2 * sqrt(2. / 3) * phi, j -
                                      (2 - 2 * s))
     return ans * self.L**4
Exemple #11
0
 def __mul__(self, o: object) -> ABSqrtC:
     if isinstance(o, ABSqrtC):
         radical = self.get_common_radical(o)
         return ABSqrtC(
             self._add * o._add + self._factor * o._factor * radical,
             self._add * o._factor + self._factor * o._add,
             radical,
         )
     if isinstance(o, _NumTypes):
         f_o = o if isinstance(o, F) else F(o)
         return ABSqrtC(self._add * f_o, self._factor * f_o, self._radical)
     return NotImplemented
Exemple #12
0
 def __rmul__(self, o: object) -> ABSqrtC:
     if isinstance(o, ABSqrtC):
         radical = o.get_common_radical(self)
         return ABSqrtC(
             o._add * self._add + o._factor * self._factor * radical,
             o._add * self._factor + o._factor * self._add,
             radical,
         )
     if isinstance(o, _NumTypes):
         f_o = o if isinstance(o, F) else F(o)
         return ABSqrtC(f_o * self._add, f_o * self._factor, self._radical)
     return NotImplemented
def BellC(x, j):
    """ Defines the complete ordinary Bell polynomial recursively. """
    indices = [i for i in x.j() if F(i) <= j]
    indices = [(p, q) for p, q in nloop(indices, 2) if p != 0 and p + q == j]
    if indices:
        s = sum(p / j * BellC(x, q) * x[p] for p, q in indices if x[p] != P(0))
        if s == 0:
            return P(0.)
        else:
            return s
    else:
        return P(1)
Exemple #14
0
 def __sub__(self, o: object) -> ABSqrtC:
     if isinstance(o, ABSqrtC):
         radical = self.get_common_radical(o)
         return ABSqrtC(self._add - o._add, self._factor - o._factor,
                        radical)
     if isinstance(o, _NumTypes):
         return ABSqrtC(
             self._add - (o if isinstance(o, F) else F(o)),
             self._factor,
             self._radical,
         )
     return NotImplemented
 def test_integers(self):
     for i in range(-1000, 1000):
         self.check_equal_hash(i, float(i))
         self.check_equal_hash(i, D(i))
         self.check_equal_hash(i, F(i))
     for i in range(100):
         n = 2**i - 1
         if n == int(float(n)):
             self.check_equal_hash(n, float(n))
             self.check_equal_hash(-n, -float(n))
         self.check_equal_hash(n, D(n))
         self.check_equal_hash(n, F(n))
         self.check_equal_hash(-n, D(-n))
         self.check_equal_hash(-n, F(-n))
         n = 2**i
         self.check_equal_hash(n, float(n))
         self.check_equal_hash(-n, -float(n))
         self.check_equal_hash(n, D(n))
         self.check_equal_hash(n, F(n))
         self.check_equal_hash(-n, D(-n))
         self.check_equal_hash(-n, F(-n))
     for _ in range(1000):
         e = random.randrange(300)
         n = random.randrange(-10**e, 10**e)
         self.check_equal_hash(n, D(n))
         self.check_equal_hash(n, F(n))
         if n == int(float(n)):
             self.check_equal_hash(n, float(n))
Exemple #16
0
    def me(self, reverse = False):
        '''
        return the R.E.F(row echelon form, in french m.e.) of the matrix'''
        i, j = 0, 0
        me = self.copy()

        while i < len(me[0]) and j < len(me)-1:
            found_non_zero = False
            for o in range(j, len(me)): #find a non-zero pivot, replace the current line.
                if me[o][i] != 0 and found_non_zero == False:
                    me[j], me[o] = me[o], me[j]
                    found_non_zero = True

            if found_non_zero:
                me[j] = [F(elem, me[j][i]) for elem in me[j]] #current pivot line: me[j]
                for k in range(j+1, len(me)):
                    #modifier tous les entrees au-desous du pivot a zero.
                    tmp_line = []
                    for q in range(len(me[k])):
                        tmp_line.append(me[k][q]-me[k][i]*me[j][q])
                    me[k] = tmp_line
                i += 1
                j += 1
            else:
                i += 1

        for line in me:
            i = 0
            while i < len(line) and line[i] == 0:
                i += 1
            if i < len(line) and line[i] != 1:
                coe = line[i]
                for p in range(len(line)):
                    line[p] = F(line[p], coe)

        if reverse == True:
            me = me[::-1]

        return Matrix(*me)
Exemple #17
0
def sin_f(e, M, order):
    """
	Celestial mechanics classical expansion of sinf.
	"""
    from pyranha.math import sin
    from fractions import Fraction as F
    temp = 0
    for k in range(1, order + 2):
        temp = temp + (besselJ(k - 1, k * e, order) -
                       besselJ(k + 1, k * e, order)) * sin(k * M)
    temp = temp * binomial_exp(1, -e**2, F(1, 2), int(order / 2))
    return temp.transform(
        lambda t: (t[0].filter(lambda u: u[1].degree(['e']) <= order), t[1]))
Exemple #18
0
    def test_complex(self):
        # comparisons with complex are special:  equality and inequality
        # comparisons should always succeed, but order comparisons should
        # raise TypeError.
        z = 1.0 + 0j
        w = -3.14 + 2.7j

        for v in 1, 1.0, F(1), D(1), complex(1):
            self.assertEqual(z, v)
            self.assertEqual(v, z)

        for v in 2, 2.0, F(2), D(2), complex(2):
            self.assertNotEqual(z, v)
            self.assertNotEqual(v, z)
            self.assertNotEqual(w, v)
            self.assertNotEqual(v, w)

        for v in (1, 1.0, F(1), D(1), complex(1), 2, 2.0, F(2), D(2),
                  complex(2), w):
            for op in operator.le, operator.lt, operator.ge, operator.gt:
                self.assertRaises(TypeError, op, z, v)
                self.assertRaises(TypeError, op, v, z)
Exemple #19
0
def gauss(A):
    n = len(A)
    for i in range(n):
        maxEl = abs(A[i][i])
        maxRow = i
        for k in range(i + 1, n):
            if abs(A[k][i]) > maxEl:
                maxEl = abs(A[k][i])
                maxRow = k
        for k in range(i, n + 1):
            A[maxRow][k], A[i][k] = A[i][k], A[maxRow][k]
        for k in range(i + 1, n):
            c = F(-A[k][i], A[i][i])
            for j in range(i, n + 1):
                if i == j: A[k][j] = F(0, 1)
                else: A[k][j] += c * A[i][j]
    x = [0] * n
    for i in range(n - 1, -1, -1):
        x[i] = F(A[i][n], A[i][i])
        for k in range(i - 1, -1, -1):
            A[k][n] -= A[k][i] * x[i]
    return x
Exemple #20
0
    def test_equal(self):
        '''
        hash of multiple representations of the same value must be equal
        '''
        from constructible import sqrt
        from fractions import Fraction as F

        for a, b in [(sqrt(2), 2 / sqrt(2)), (sqrt(2), 1 / sqrt(F(1, 2))),
                     (sqrt(2) + sqrt(3), sqrt(3) + sqrt(2))]:
            with self.subTest(a=a, b=b):
                self.assertEqual(a, b, 'precondition for this test')
                self.assertEqual(hash(a), hash(b),
                                 '%s == %s, but hash is different' % (a, b))
Exemple #21
0
def result():
    f = F(*map(int, n(str).split('/')))
    if f == 1:
        return 1
    g = 41
    for i in range(1, 41):
        f *= 2
        if f.numerator >= f.denominator and i < g:
            g = i
    if f.denominator != 1:
        return 'impossible'
    else:
        return g
Exemple #22
0
def test_durbin_recurrence_rational():
    # Test the reference using external and hand-calculated values.
    cdf = ks_unif_durbin_recurrence_rational
    small = lambda sp: (slow and sp < 40) or sp < 20
    for sp, st, pr in oconnor_values:
        if small(sp):
            assert abs(cdf(sp, F.from_float(st)) - pr) / pr <= F('.5e-4')
    for sp, st, pr in brown_values:
        if small(sp):
            assert abs(cdf(sp, F.from_float(st)) - pr) / pr <= F('.5e-5')
    for sp, st, pr in simard_values:
        if small(sp):
            assert abs(cdf(sp, F.from_float(st)) - pr) / pr <= F('.5e-13')
    for sp, st, pr in marsaglia_values:
        if small(sp):
            assert abs(cdf(sp, F.from_float(st)) - pr) / pr <= F('.5e-13')
    for sp, st, pr in exact_values:
        if small(sp):
            # Reference is supposed to compute an exact result, with
            # inaccuracies resulting only from the limited precison
            # of the stored test values.
            assert cdf(sp, st) == pr
Exemple #23
0
    def test_unify_types_to_custom_type(self):
        class MyNumber(object):
            def __init__(self, x):
                if isinstance(x, MyNumber):
                    self.x = x.x
                else:
                    self.x = int(x)

        l = [1, F(2), MyNumber(3)]
        u = util.unify_types(l)
        for i in u:
            self.assertIsInstance(i, MyNumber)
        self.assertEqual([i.x for i in u], [1, 2, 3])
Exemple #24
0
 def test_data_contained(self):  # internal data representation
     self.assertEqual(
         self.rhythm_dur.sequence,
         [F(1, 4),
          F(1, 4),
          F(1, 16),
          F(1, 8),
          F(1, 8),
          F(1, 16),
          F(1, 8)])
     self.assertTrue(self.rhythm_dur[1].rest)
     self.assertEqual(self.rhythm_dur[2].accent, 2)
Exemple #25
0
 def __truediv__(self, o: object) -> ABSqrtC:
     if isinstance(o, ABSqrtC):
         radical = self.get_common_radical(o)
         return ABSqrtC(
             (self._add * o._add - self._factor * o._factor * radical) /
             o._conjugate_product,
             (self._factor * o._add - self._add * o._factor) /
             o._conjugate_product,
             radical,
         )
     if isinstance(o, _NumTypes):
         f_o = o if isinstance(o, F) else F(o)
         return ABSqrtC(self._add / f_o, self._factor / f_o, self._radical)
     return NotImplemented
Exemple #26
0
 def test_resource_create_pieces(self):
     ''' test that we can create n pieces of the cake '''
     keys = ['red', 'blue', 'green', 'yellow', 'orange', 'purple']
     vals = dict((k, F(1,1)) for k in keys)
     cake = CollectionResource(keys)
     user = CollectionPreference('mark', vals)
     pieces = create_equal_pieces(user, cake, 3)
     actual = [
         CollectionResource(['red', 'blue']),
         CollectionResource(['green', 'yellow']),
         CollectionResource(['orange', 'purple'])
     ]
     for this,that in zip(pieces, actual):
         self.assertEqual(this.value, that.value)
Exemple #27
0
    def test_add(self):
        t1 = ABSqrtC(2, 0, 1)
        t2 = ABSqrtC(3, -5, 7)
        t3 = ABSqrtC(3, 5, 7)
        t4 = ABSqrtC(3, 10, 7)
        t5 = ABSqrtC(3, 5, 11)

        with pytest.raises(ValueError):
            t2 + t5

        assert t1 + t3 == ABSqrtC(5, 5, 7)
        assert t2 + t3 == ABSqrtC(6, 0, 1)
        assert t2 + t4 == ABSqrtC(6, 5, 7)
        assert t3 + 1 == t3 + D(1) == t3 + F(1) == t3 + "1" == ABSqrtC(4, 5, 7)
Exemple #28
0
  def sol():
    gre = F(0,1)
    les = float('inf')
    for i in range(n-1):
      a, b = mol[i]
      c, d = mol[i+1]
      if b == d:
        if a >= c: les = -float('inf')
        continue
      rat = F(a-c, d-b)
      if d-b > 0: gre = max(gre, rat)
      else: les = min(les, rat)
    if les <= gre:
      return -1, -1

    # print(gre, les)
    if les != float('inf'):
      rat = simplest_between(gre, les)
      ansy, ansx = rat.numerator, rat.denominator
    else:
      ansx = 1
      ansy = int(gre) + 1
    return ansx, ansy
Exemple #29
0
    def test_resource_clone(self):
        ''' test that the resource clone works correctly '''
        keys = ['red', 'blue', 'green', 'yellow', 'orange']
        vals = dict((k, F(1,1)) for k in keys)
        cake = CollectionResource(keys)
        user = CollectionPreference('mark', vals)
        copy = cake.clone()
        self.assertEqual(str(cake), str(copy))
        self.assertEqual(repr(cake), repr(copy))

        self.assertEqual(5, cake.actual_value(),)
        self.assertEqual(cake.actual_value(), copy.actual_value())

        self.assertEqual(CollectionResource('a'), CollectionResource(['a']))
Exemple #30
0
def calc_oowp(N, games, owp):
    oowp = {}
    for team1 in xrange(N):
        oowp_ = F()
        n_opponents = 0
        for team2 in xrange(N):
            if team1 == team2:
                continue
            team1_result = games.get((team1, team2), None)
            if team1_result is not None:
                n_opponents += 1
                oowp_ += owp[team2]
        oowp[team1] = oowp_ / n_opponents
    return oowp