Example #1
0
def calc(expresión=0, precisión=1000):
    '''
    Calculadora de expresiones con números complejos.

    expresión: expresión númerica válida.
    precisión: precisión de la simplificación.

    Uso:
    >>> from calc_comp import calc
    >>> from numpy import conjugate as c
    >>> z1 =  3-2j
    >>> z2 = -5-6j
    >>> z3 = -4+2j
    >>> exp = ((z1 - c(z2)) / z2) * ((2*z1) / z3)
    >>> calc(exp)
    (-0.49836065573770494-2.281967213114754j) =
         -152             -696
    ------------- + ------------- i
         305             305
    '''
    z = expresión
    frac_real = F.from_float(z.real).limit_denominator(precisión)
    frac_imag = F.from_float(z.imag).limit_denominator(precisión)
    print(dd('''\
             {0} =
                  {1}             {2}
             ------------- + ------------- i
                  {3}             {4}'''.format(expresión,
                                                frac_real.numerator,
                                                frac_imag.numerator,
                                                frac_real.denominator,
                                                frac_imag.denominator)))
Example #2
0
	def __init__(self, infreq, outfreq):
		self.clkin = Signal()
		self.clkout = Signal()
		
		ratio = Fraction(outfreq)/Fraction(infreq)
		appr = ratio.limit_denominator(32)
		m = appr.numerator
		if m < 2 or m > 32:
			raise OverflowError
		d = appr.denominator
		
		in_period = float(Fraction(1000000000)/Fraction(infreq))
		
		self._inst = Instance("DCM_SP",
			[("CLKFX", self.clkout)],
			[("CLKIN", self.clkin),
			("PSEN", BV(1)),
			("RST", BV(1))],
			[("CLKDV_DIVIDE", 2.0),
			("CLKFX_DIVIDE", d),
			("CLKFX_MULTIPLY", m),
			("CLKIN_DIVIDE_BY_2", "FALSE"),
			("CLKIN_PERIOD", in_period),
			("CLKOUT_PHASE_SHIFT", "NONE"),
			("CLK_FEEDBACK", "NONE"),
			("DESKEW_ADJUST", "SYSTEM_SYNCHRONOUS"),
			("DUTY_CYCLE_CORRECTION", "TRUE"),
			("PHASE_SHIFT", 0),
			("STARTUP_WAIT", "TRUE")]
		)
Example #3
0
def seleciona_Coeficientes(matriz_Fxn, matriz):

	print "\nPolinômio P"+str(colunas-1)+":"

	fator = ""

	for i in range(colunas):
		for j in range(colunas):
			#pula se der 0
			if i==j and i==0:
				print BOLD+str(Fraction.from_float(matriz_Fxn[i][j]).limit_denominator(NUMERADOR))+fator+END,
			
			#coeficiente diferente de 0 
			elif i==j:
				#imprime a diferenca
				if matriz[0][j-1] != 0.0:
					if matriz[0][j-1] > 0.0:
						fator += "(x-"+str(Fraction.from_float(abs(matriz[0][j-1])).limit_denominator(NUMERADOR))+")"
					else:
						fator += "(x+"+str(Fraction.from_float(abs(matriz[0][j-1])).limit_denominator(NUMERADOR))+")"
				else:
					fator += "(x)"

				#coeficiente da matriz com sinal
				if matriz_Fxn[i][j] > 0.0:
					print BOLD+"+"+str(Fraction.from_float(matriz_Fxn[i][j]).limit_denominator(NUMERADOR))+fator+END,
				else:
					print BOLD+str(Fraction.from_float(matriz_Fxn[i][j]).limit_denominator(NUMERADOR))+fator+END,
	print "\n"
Example #4
0
def variance(series, weights, mean):
   """Precisely calculates the variance of a series of floats
   
   Note: uses N-1 as correction factor.
   Note: assumes mean to be an instance of Fraction"""

   if len(series) <> len(weights):
      return float("NaN")

   if not isinstance(mean, Fraction):
      return float("NaN")

   factor = Fraction(0)
   total_weight = Fraction(-1)

   i = 0
   length = len(series)
   while (i < length):
      
      delta = Fraction.from_float(series[i]) - mean
      weight = Fraction.from_float(weights[i])
      factor += delta*delta*weight

      total_weight += weight

      i += 1

   if total_weight <= 0:
      return float("NaN")

   return factor/total_weight
Example #5
0
def _msec_to_numden(delay):
    """
    delay is the time delay in milliseconds.

    Return value is the tuple (delay_num, delay_den) representing
    the delay in seconds as the fraction delay_num/delay_den.
    Each value in the tuple is an integer less than 65536.
    """
    if delay == 0:
        return (0, 1)
    # Convert delay to seconds.
    delay = delay/1000.0
    if delay > 1:
        f = Fraction.from_float(1.0/delay).limit_denominator(65535)
        num = f.denominator
        den = f.numerator
    else:
        f = Fraction.from_float(delay).limit_denominator(65535)
        num = f.numerator
        den = f.denominator
    if (num, den) == (1, 0):
        raise ValueError("delay=%r is too large to convert to "
                         "delay_num/delay_den" % (delay,))
    if (num, den) == (0, 1):
        raise ValueError("delay=%r is too small to convert to "
                         "delay_num/delay_den" % (delay,))
    return num, den
Example #6
0
def solve(n, m):
  total_cases = nCr(n+m, n)
  failed_cases = fail(n, m)
  
  from fractions import Fraction
  f = Fraction(total_cases - failed_cases, total_cases)
  f.limit_denominator()
  return float(f)
Example #7
0
def output_dynamics(message):
    i = struct.unpack("!dd", message)
    acc_fr = Fraction(i[0])
    acc_fr = acc_fr.limit_denominator(8)
    brk_fr = Fraction(i[1])
    brk_fr = brk_fr.limit_denominator(8)
    return struct.pack("<hhhh", int(acc_fr.numerator), int(acc_fr.denominator),
                       int(brk_fr.numerator), int(brk_fr.denominator))
Example #8
0
 def rational(arg, max_denominator=1000000):
     # return nominator and denominator from float or two integers
     try:
         f = Fraction.from_float(arg)
     except TypeError:
         f = Fraction(arg[0], arg[1])
     f = f.limit_denominator(max_denominator)
     return f.numerator, f.denominator
Example #9
0
def to_frac(v):
    v = Fraction(v)
    v = v.limit_denominator(1000)
    v = str(v)
    if "/" in v:
        v = v.split("/")
        v = "\\frac{%s}{%s}" % (v[0], v[1])
    return v
Example #10
0
def fraction_cheating(n=3,d=7,limit = 1000000):
    '''
    find the reduced proper fraction directly
    to the left of the given target
    problem 71
    '''
    real = Fraction(n,d)
    approx = Fraction(n/d)
    while approx.limit_denominator(limit) == real: #Fraction(7720456504063707, 18014398509481984)
        approx = Fraction(approx.numerator-1,approx.denominator)
    return approx #Fraction(3595117, 8388608)???
Example #11
0
def data_averaging_coeffs(fh1, fh2):
    """
    return the time-and-frequency averaging parameters
    which help get the data on the same grid(s)

    """
    ## read the two filestreams in chunks of equal time
    sr = Fraction(fh1.dtsample.to(u.s).value * fh1.blocksize
                  / fh1.recordsize)
    sr /= Fraction(fh2.dtsample.to(u.s).value * fh2.blocksize
                   / fh2.recordsize)
    sr = sr.limit_denominator(1000)
    nf1 = sr.denominator
    nf2 = sr.numerator

    ## used for re-sizing hdf5 x-corr output
    raw1_nrows = int(fh1.blocksize * nf1 / fh1.recordsize)
    raw2_nrows = int(fh2.blocksize * nf2 / fh2.recordsize)

    ## time averaging params
    Tavg = Fraction(raw1_nrows, raw2_nrows).limit_denominator(1000)
    Tden = Tavg.denominator
    Tnum = Tavg.numerator

    ## channel averaging params
    f1info = (fh1.freq.max(), fh1.freq.min(), len(fh1.freq),
              np.sign(np.diff(fh1.freq).mean()))
    f2info = (fh2.freq.max(), fh2.freq.min(), len(fh2.freq),
              np.sign(np.diff(fh2.freq).mean()))
    f1keep = (fh1.freq > max(f1info[1], f2info[1])) \
        & (fh1.freq < min(f1info[0], f2info[0]))
    f2keep = (fh2.freq > max(f1info[1], f2info[1])) \
        & (fh2.freq < min(f1info[0], f2info[0]))

    Favg = abs(Fraction(np.diff(fh1.freq.value).mean()
                        / np.diff(fh2.freq.value).mean()))
    Favg = Favg.limit_denominator(200)
    Fden = Favg.denominator
    Fnum = Favg.numerator
    # the frequencies we keep
    freq1 = fh1.freq[f1keep]
    freq1 = freq1.reshape(freq1.size / Fden, Fden).mean(axis=-1)
    freq2 = fh2.freq[f2keep]
    freq2 = freq2.reshape(freq2.size / Fnum, Fnum).mean(axis=-1)
    # sort low freq to high freq
    if f1info[3] < 0:
        freq1 = freq1[::-1]
    if f2info[3] < 0:
        freq2 = freq2[::-1]

    return ((nf1, nf2), (Tnum, Tden), (Fden, Fnum), (f1keep, f2keep),
            (freq1, freq2), (raw1_nrows, raw2_nrows))
 def test_createNodeWithInitialValue(self):
     """
     Generates 100 random values from -1 to 2 and creates nodes with them as
     initial values. Checks, that for values below zero and above one a
     ValueError is raised.
     :return:
     """
     for val in [self.rand.uniform(-1, 2) for _ in range(100)]:
         if val < 0 or val > 1:
             with self.assertRaises(ValueError):
                 Node(Fraction.from_float(val))
         else:
             node = Node(Fraction.from_float(val))
             self.assertEqual(val, node.initial_value)
             self.assertEqual(val, node.value)
Example #13
0
def print_file(A):
    file = open("matrix_show.txt", "a")
    for i in range(len(A)):
        for j in range(len(A[i])):
            file.write("%6s " % Fraction.limit_denominator(A[i][j]))
        file.write("\n")
    file.write("\n\n")
Example #14
0
 def rep_as_fraction(self):
     frac = Fraction.from_float(self.radius)
     whole = int(frac.numerator)/int(frac.denominator)
     remainder = int(frac.numerator)%int(frac.denominator)
     self.rational_num = str(whole) + " " + str(remainder) + "/" + str(frac.denominator)
     
     
 def test_addSuccessor(self):
     """
     Generates 100 random values from -1 to 2. Creates new nodes for every
     value and adds them using the generated value as the weight.
     Checks, that for values below zero and above one a
     ValueError is raised.
     :return:
     """
     test_node = Node()
     for val in [self.rand.uniform(-1, 2) for _ in range(100)]:
         new_node = Node()
         if val < 0 or val > 1:
             with self.assertRaises(ValueError):
                 test_node.add_successor(new_node, Fraction.from_float(val))
         else:
             test_node.add_successor(new_node, Fraction.from_float(val))
    def test_fireCycles(self):
        """
        Generates a list of nodes and weights, and a test node and their initial
        value. Then adds the list as cycle_successors to the node and calls
        fire.
        Checks that all values are calculated correctly.
        Also checks that firing multiple times sums the values.
        :return:
        """
        # TODO: check for transformation function
        value_list = [self.rand.uniform(0, 1) for _ in range(100)]
        node_list = [
            (CycleNode(float(Fraction(0))), Fraction.from_float(val))
            for val in value_list
            ]
        test_node = CycleNode(float(Fraction(0)), float(Fraction(1, 2)))
        test_node.add_successors(node_list)

        # Creates a copy of the node list and manually calculates their values
        # after firing the test node
        fired_node_list = node_list.copy()
        for node, value in fired_node_list:
            node.add_value(0.5 * value)

        test_node.fire()
        self.assertListEqual(node_list, fired_node_list)
Example #17
0
    def Real(self, value):
        """ Returns a Real-type constant of the given value.

        value can be:
          - A Fraction(n,d)
          - A tuple (n,d)
          - A long or int n
          - A float
        """
        if value in self.real_constants:
            return self.real_constants[value]

        if type(value) == Fraction:
            val = value
        elif type(value) == tuple:
            val = Fraction(value[0], value[1])
        elif is_python_integer(value):
            val = Fraction(value, 1)
        elif type(value) == float:
            val = Fraction.from_float(value)
        else:
            raise TypeError("Invalid type in constant. The type was:" + \
                            str(type(value)))

        n = self.create_node(node_type=op.REAL_CONSTANT,
                             args=tuple(),
                             payload=val)
        self.real_constants[value] = n
        return n
Example #18
0
    def __init__(self, *args):

        self.value = Fraction(*args).limit_denominator()
        super(Rational, self).__init__()

        self.numerator = self.value.numerator
        self.denominator = self.value.denominator
Example #19
0
def simplify(numer, denom, approximate=False):
    """
    Simplifies the fraction, returning a tuple. If ``approximate`` is true,
    then the resulting fraction is only an approximation of the input number
    by limiting the denominator of the fraction to ``10``.

    :param numer: The numerator
    :param denom: The denominator
    :param approximate: Whether to approximate or not.
    """
    fract = Fraction(numer, denom)
    if approximate:
        tmp = fract.limit_denominator(10)
        if fract != tmp:
            LOG.debug("{0} reduced to {1}".format(fract, tmp))
        fract = tmp
    return fract.numerator, fract.denominator
Example #20
0
 def fromFraction(fraction):
     ''' static method, returns a ProbFraction numerically
         equivalent to the given Fraction instance
     '''
     probFraction = Fraction.__new__(ProbFraction)
     probFraction._numerator = fraction._numerator
     probFraction._denominator = fraction._denominator
     return probFraction
Example #21
0
def cubic_sym_span_matrix():
  """
  Compute a symbolic span matrix for B-Splines.

  Based on "A practical review of uniform b-splines" by Kristin Branson
  Notation used: [1 s s^2 s^3] Bi Pi^T
  See: http://vision.ucsd.edu/~kbranson/research/bsplines.html
  """

  # Symbolic variables
  i = sp.Symbol('i')
  s = sp.Symbol('s')
  P = sp.MatrixSymbol('p', 4, 1)

  # Use the result given in the paper
  # TODO: implement the part that leads to this result
  res = Fraction(1,6)*( (1-(s-i))**3 * P[0,0]
            + (3*(s-i)**3 - 6*(s-i)**2 + 4) * P[1,0]
            + (-3*(s-i)**3 + 3*(s-i)**2 + 3*(s-i) + 1) * P[2,0]
            + (s-i)**3 * P[3,0]
            )
  res = res.expand()
  # Handle as a symbolic polynomial
  res = sp.Poly(res, P[0,0], P[1,0], P[2,0], P[3,0])

  # Span matrix Bi
  Bi = sp.Matrix(4,4, lambda i,j: 0)

  # For each column (control points Pj)
  for col in xrange(4):
    basis = sp.zeros(4)
    basis[col] = 1
    # Substitute by the right vector to get the proper coefficient
    # (there may be a better way to achieve that with sympy)
    p_ctrl_pt = res.subs( {P[0,0]: basis[0],
                           P[1,0]: basis[1],
                           P[2,0]: basis[2],
                           P[3,0]: basis[3]})
    coeffs = sp.Poly(p_ctrl_pt, s).as_poly().all_coeffs()[::-1]

    # For each row (s^k)
    for row in xrange(len(coeffs)):
      # Store the factorized result in Bi
      Bi[row,col] = coeffs[row].factor(i)

  return Bi
Example #22
0
    def fechar(self):
        """
        Torna a venda fechada -- o cliente já pagou a conta.

        Cria/sobrescreve a transação de 10% referente à venda.

        """

        if self.fechada:
            return

        if self.transacao_10p:
            self.transacao_10p.delete()

        if self.gorjeta:
            registro_10p = Registro.objects.get(nome=NOME_DO_REGISTRO)

            self.transacao_10p = Transacao(
                registro=registro_10p,
                data=self.dia.data,
                descricao="10% a pagar do dia {0}".format(self.dia.data)
            )

            self.transacao_10p.save()

            config = get_config()

            a_pagar = Decimal(
                float(
                    Fraction.from_decimal(self.gorjeta) \
                     * Fraction(9, 10) \
                     * config.fracao_10p_funcionarios
                 )
            )

            self.transacao_10p.lancamentos.create(
                valor=a_pagar * -1,
                conta=join("entrada", "vendas", "10% funcionarios"),
            )

            self.transacao_10p.lancamentos.create(
                valor=a_pagar,
                conta=join("bens", "caixa"),
            )

            self.transacao_10p.lancamentos.create(
                valor=a_pagar,
                conta=join("gastos", "funcionarios", "10%"),
            )

            self.transacao_10p.lancamentos.create(
                valor=a_pagar * -1,
                conta=join("dividas", "contas a pagar", "10%"),
            )


        self.fechada = True
        self.save()
Example #23
0
    def parse_set(self, value, from_db):
        if (from_db and isinstance(value, (text_type, binary_type))
                or isinstance(value, float) or isinstance(value, Decimal)):
            if isinstance(value, float):
                value = Fraction(Decimal(str(value)))
            elif isinstance(value, (binary_type, text_type)):
                if _PY3 and isinstance(value, binary_type):
                    value = Fraction(Decimal(value.decode()))
                else:
                    value = Fraction(Decimal(value))

            value = Fraction(value - 1)  # already a Decimal
        elif not isinstance(value, Fraction):
            raise TypeError('Expected Fraction, found {}: {}'.format(
                type(value), value
            ))

        return value
Example #24
0
File: vfr.py Project: glorizen/vfr
def parse_tc(tcfile, max=0, otc=None, first=0):
    """Parses a timecodes file or cfr fps.
    
    tcfile = timecodes file or cfr fps to parse
    max = number of frames to be created in v1 parsing
    otc = output v2 timecodes filename
    
    """

    cfr_re = compile('(\d+(?:\.\d+)?)(?:/|:)?(\d+(?:\.\d+)?)?')
    vfr_re = compile('# timecode format (v1|v2)')

    ret = cfr_re.search(tcfile)
    if ret and not isfile(tcfile):
        type = 'cfr'
        num = Fraction(ret.group(1))
        den = Fraction(ret.group(2)) if ret.group(2) else 1
        timecodes = Fraction(num, den)
        if otc:
            convert_v1_to_v2([], max + 2, timecodes, otc, first)

    else:
        type = 'vfr'
        with open(tcfile) as tc:
            v1 = tc.readlines()
        ret = vfr_re.search(v1.pop(0))
        version = ret.group(1) if ret else exit('File is not in a supported '
                                                'format.')

        if version == 'v1':
            ret = v1.pop(0).split(' ')
            asm = ret[1] if len(ret) == 2 else exit('there is no assumed fps')
            if v1:
                ret = convert_v1_to_v2(v1, max, asm, otc, first)
                timecodes = ['{0:3.6f}\n'.format(i) for i in ret]
            else:
                timecodes = correct_to_ntsc(asm)
                type = 'cfr'
                if otc:
                    convert_v1_to_v2([], max + 2, timecodes, otc, first)

        elif version == 'v2':
            if max > len(v1):
                temp_max = len(v1)
                sample = temp_max // 100
                average = 0
                for i in range(-sample, 0):
                    average += round(float(v1[i]) - float(v1[i - 1]), 6)
                fps = correct_to_ntsc(Fraction.from_float(sample / average *
                                        1000))
                ret = convert_v1_to_v2([], max - len(v1) + 1, fps, first=1)
                if v1[-1][-1] is not '\n':
                    v1[-1] += '\n'
                v1 += ['{0:3.6f}\n'.format(i + float(v1[-1])) for i in ret]
            timecodes = v1

    return (timecodes, type), max
Example #25
0
File: fmt.py Project: wmayner/pyphi
def fmt_number(p):
    """Format a number.

    It will be printed as a fraction if the denominator isn't too big and as a
    decimal otherwise.
    """
    formatted = '{:n}'.format(p)

    if not config.PRINT_FRACTIONS:
        return formatted

    fraction = Fraction(p)
    nice = fraction.limit_denominator(128)
    return (
        str(nice) if (abs(fraction - nice) < constants.EPSILON and
                      nice.denominator in NICE_DENOMINATORS)
        else formatted
    )
Example #26
0
 def __mul__(self, frac):
     """
     Multiply the amount by the given fraction, using bankers rounding
     to round to the nearest value
     """
     if isinstance(frac, Decimal):
         frac = Fraction.from_decimal(frac)
     elif not isinstance(frac, Rational):
         raise TypeError('Expected a Decimal or a numbers.Rational value')
     return MoneyAmount(self.code, frac * self.value)
def read_matrix(filename):
    with open(filename, 'r') as f:
        n = int(f.readline().strip())
        b = int(f.readline().strip())
        matrix = []
        for i in range(n):
            line = f.readline().strip()
            raw_nums = line.split()
            if len(raw_nums) != n:
                raise ValueError('row %d length must be %d numbers' % (i+1, n))
            row = tuple(Fraction.from_float(float(x)) for x in raw_nums)
            matrix.append(row)
        line = f.readline().strip()
        raw_nums = line.split()
        if len(raw_nums) != n:
            raise ValueError('c vector length must be %d numbers' % n)
        c = tuple(Fraction.from_float(float(x)) for x in raw_nums)

        return n,b,matrix,c
Example #28
0
def show(header, mtrx):
	print header, "-------"
	for i in range(0, len(mtrx)):
		for j in range(0, len(mtrx)):
			if mtrx[i][j] == int(mtrx[i][j]):
				print "{0:8d}".format(int(mtrx[i][j])),
			else:
				tmp = Fraction.from_float(mtrx[i][j]).limit_denominator()
				print " "*(7-len(str(tmp))),
				print tmp,
		print ""
	print ""
Example #29
0
    def as_fraction(self):
        """ Return a string that represents the unit as a fraction """

        return_string = []
        if int(self.value) > 0:
            return_string.append(str(int(self.value)))
            return_string.append(' ')

        return_string.append(str(Fraction.from_float(self.value % 1). \
                        limit_denominator(1024)))

        return ''.join(return_string)
 def to_html(self):
     """Render the problem in a form that is convertable to
        TeX by MathJax. Note that inline MathJax equations are 
        bracketed by \(...\). Prepends a prompt"""
     prompt = "Reduce"
     fractions = re.findall('\d+/\d+',self.problem)
     h = '\('+self.problem+'\)'
     for f in fractions:
         a,b = f.split('/')
         text = r'\\frac{%s}{%s}'%(a,b)
         h = re.sub('\d+/\d+',text,h,count = 1)
     return [prompt,h]
Example #31
0
class LineConstructor(object):
    """
    Line and HarmonicContextTrack constructor. Used by LineGrammar.g4 to assemble parts for each entity.
    """

    DURATION_MAP = {
        'W': Fraction(1),
        'H': Fraction(1, 2),
        'Q': Fraction(1, 4),
        'I': Fraction(1, 8),
        'S': Fraction(1, 16),
        'T': Fraction(1, 32),
        'X': Fraction(1, 64)
    }

    NUMERAL_MAP = {
        'i': 1,
        'I': 1,
        'ii': 2,
        'II': 2,
        'iii': 3,
        'III': 3,
        'iv': 4,
        'IV': 4,
        'v': 5,
        'V': 5,
        'vi': 6,
        'VI': 6,
        'vii': 7,
        'VII': 7
    }

    # Map short names to actual modalities.
    MODALITY_SHORT_NAME_MAP = {
        'Minor': ModalityType.MelodicMinor,
        'Natural': ModalityType.NaturalMinor,
        'Harmonic': ModalityType.HarmonicMinor,
        'Melodic': ModalityType.MelodicMinor
    }

    DEFAULT_BEAM_DURATION = Duration(1, 8)
    DEFAULT_LINE_DURATION = Duration(1, 4)
    DEFAULT_TONALITY = Tonality.create(ModalityType.Major, DiatonicToneCache.get_tone('C'))

    def __init__(self):
        """
        Constructor.
        """
        self.tie_list = list()
        self.__line = Line()
        self.current_level = Level(self.__line, LineConstructor.DEFAULT_LINE_DURATION)
        self.level_stack = list()
        self.current_tonality = LineConstructor.DEFAULT_TONALITY
        self.harmonic_tag_list = list()
        self.current_harmonic_tag = None

        # Set up a default harmonic tag. In cases where a tag is immediately specified, this is discarded
        self.construct_harmonic_tag(LineConstructor.DEFAULT_TONALITY,
                                    ChordTemplate.generic_chord_template_parse('ti'))

    @property
    def line(self):
        return self.__line

    @property
    def hct(self):
        return self.build_harmonic_context_track()

    def start_level(self, duration=None, dur_int=None):
        level = Level(Tuplet(duration, dur_int) if duration is not None else Beam(),
                      duration if duration is not None else LineConstructor.DEFAULT_BEAM_DURATION)
        self.current_level.collector.append(level.collector)
        self.level_stack.append(self.current_level)
        self.current_level = level

    def end_level(self):
        self.current_level = self.level_stack.pop()

    def construct_note(self, pitch, duration, dots, tied):
        dur = duration if duration is not None else self.current_level.default_duration
        note = Note(pitch, dur, dots)
        if tied:
            self.tie_list.append(note)
        if duration is not None:
            self.current_level.default_duration = duration
        return note

    @staticmethod
    def construct_tone_from_tone_letters(letters):
        if letters == 'R' or letters == 'r':
            return None
        return DiatonicToneCache.get_tone(letters)

    def construct_pitch(self, tone, partition):
        part = partition if partition is not None else self.current_level.default_register
        if partition is not None:
            self.current_level.default_register = partition
        if tone is None:
            return None
        return DiatonicPitch(part, tone)

    @staticmethod
    def construct_duration_by_shorthand(shorthand):
        shorthand = shorthand.upper()
        if shorthand not in LineConstructor.DURATION_MAP:
            raise Exception('\'{0}\' not a valid duration shorthand.'.format(shorthand))
        return Duration(LineConstructor.DURATION_MAP[shorthand])

    @staticmethod
    def construct_duration(numerator, denominator):
        return Duration(numerator, denominator)

    def construct_tonality(self, tone, modality_str, modal_index=0):
        if modality_str[0] == '!':
            modality_type = ModalityType(modality_str[1:])
        elif modality_str in LineConstructor.MODALITY_SHORT_NAME_MAP:
            modality_type = LineConstructor.MODALITY_SHORT_NAME_MAP[modality_str]
        else:
            modality_type = ModalityType(modality_str)

        if ModalityFactory.is_registered(modality_type):
            return Tonality.create_on_basis_tone(tone, modality_type, modal_index)
        else:
            raise Exception('Modality \'{0}\' is not registered in ModalityFactory.'.format(modality_str))

    def construct_chord_template(self, tone, chord_type_str, chord_modality):
        if tone:
            chord_template_str = 't' + tone.diatonic_symbol + (chord_modality if chord_modality else '')
        else:
            chord_template_str = 't' + chord_type_str + (chord_modality if chord_modality else '')
        return ChordTemplate.generic_chord_template_parse(chord_template_str)

    def construct_secondary_chord_template(self, primary_template, secondary_numeral_str, secondary_modality):
        numeral = LineConstructor.NUMERAL_MAP[secondary_numeral_str]

        if secondary_modality is not None:
            if secondary_modality in LineConstructor.MODALITY_SHORT_NAME_MAP:
                modality = LineConstructor.MODALITY_SHORT_NAME_MAP[secondary_modality]
            elif secondary_modality[0] == '!':
                modality = ModalityType(secondary_modality[1:])
            else:
                modality = ModalityType(secondary_modality)
        else:
            modality = None

        return SecondaryChordTemplate(primary_template, numeral, modality)

    def construct_harmonic_tag(self, tonality, chord_template):
        tonality = tonality if tonality is not None else self.current_tonality
        chord = chord_template.create_chord(tonality)

        self.current_harmonic_tag = HarmonicTag(tonality, chord)
        self.harmonic_tag_list.append(self.current_harmonic_tag)

        self.current_tonality = tonality

    def build_harmonic_context_track(self):
        # Prune superfluous harmonic tags.
        new_tag_list = [tag for tag in self.harmonic_tag_list if tag.first_note is not None]
        self.harmonic_tag_list = new_tag_list

        hct = HarmonicContextTrack()
        for i in range(0, len(self.harmonic_tag_list)):
            harmonic_tag = self.harmonic_tag_list[i]
            duration = (self.harmonic_tag_list[i + 1].first_note.get_absolute_position()
                        if i < len(self.harmonic_tag_list) - 1 else Position(self.__line.duration)) - \
                       self.harmonic_tag_list[i].first_note.get_absolute_position()
            harmonic_context = HarmonicContext(harmonic_tag.tonality, harmonic_tag.chord, duration,
                                               harmonic_tag.first_note.get_absolute_position())
            hct.append(harmonic_context)
        return hct

    def add_note(self, note):
        self.current_level.collector.append(note)
        if self.current_harmonic_tag:
            self.current_harmonic_tag.first_note = note

    def note_list(self):
        return self.current_level.collector

    def __str__(self):
        return str(self.current_level.collector)
Example #32
0
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name:     5-2-decimal
   Description :
   Author :      'Sam Yong'
   date:          2018/7/2
-------------------------------------------------
   Change Activity:
                   2018/7/2:
-------------------------------------------------
"""
__author__ = 'Sam Yong'
# 设置精度 从实验结果来看不对?python3 的问题?
import decimal
decimal.getcontext().prec = 4 # 设置精度为4
vale = decimal.Decimal(3.333333)
print(vale)

# 分数
from fractions import Fraction
y = Fraction(4,6)
print(y)
Example #33
0
import math
from fractions import Fraction


def cancels(numer, denom):
    num = Fraction(numer, denom)
    numer = str(numer)
    denom = str(denom)
    for i in range(2):
        for j in range(2):
            if numer[i] == denom[j] and Fraction(int(numer[1 - i]),
                                                 int(denom[1 - j])) == num:
                return True
    return False


solution = 1
for numerator in range(10, 100):
    for denominator in range(numerator + 1, 100):
        if numerator % 10 != 0 and denominator % 10 != 0 and numerator % 11 != 0 and denominator % 11 != 0 and cancels(
                numerator, denominator):
            solution *= Fraction(numerator, denominator)
print(solution.denominator)
Example #34
0
def check_dyad(w, w_dyad):
    """Check that w_dyad is a valid dyadic completion of w.

    Parameters
    ----------
    w : Sequence
        Tuple of nonnegative fractional or integer weights that sum to 1.
    w_dyad : Sequence
        Proposed dyadic completion of w.

    Returns
    -------
    bool
        True if w_dyad is a valid dyadic completion of w.


    Examples
    --------
    >>> w = (Fraction(1,3), Fraction(1,3), Fraction(1,3))
    >>> w_dyad =(Fraction(1,4), Fraction(1,4), Fraction(1,4), Fraction(1,4))
    >>> check_dyad(w, w_dyad)
    True

    If the weight vector is already dyadic, it is its own completion.

    >>> w = (Fraction(1,4), 0, Fraction(3,4))
    >>> check_dyad(w, w)
    True

    Integer input should also be accepted

    >>> w = (1, 0, 0)
    >>> check_dyad(w, w)
    True

    w is not a valid weight vector here because it doesn't sum to 1

    >>> w = (Fraction(2,3), 1)
    >>> check_dyad(w, w)
    False

    w_dyad isn't the correct dyadic completion.

    >>> w = (Fraction(2,5), Fraction(3,5))
    >>> w_dyad = (Fraction(3,8), Fraction(4,8), Fraction(1,8))
    >>> check_dyad(w, w_dyad)
    False

    The correct dyadic completion.

    >>> w = (Fraction(2,5), Fraction(3,5))
    >>> w_dyad = (Fraction(2,8), Fraction(3,8), Fraction(3,8))
    >>> check_dyad(w, w_dyad)
    True

    """
    if not (is_weight(w) and is_dyad_weight(w_dyad)):
        return False
    if w == w_dyad:
        # w is its own dyadic completion
        return True
    if len(w_dyad) == len(w) + 1:
        return w == tuple(Fraction(v, 1-w_dyad[-1]) for v in w_dyad[:-1])
    else:
        return False
Example #35
0
 def add_to_phase(self, vertex, phase):
     self._phase[vertex] = (self._phase.get(vertex,Fraction(1)) + Fraction(phase)) % 2
from itertools import product
from fractions import Fraction

for t in range(int(input())):
    tmp = input().split()
    A, B, C = [int(i) for i in tmp]
    if A + B <= C: fr = Fraction(1, 1)
    elif C <= A and C <= B: fr = Fraction(C**2, (2 * A * B))
    elif C <= B: fr = Fraction(2 * C * A - A**2, (2 * A * B))
    elif C <= A: fr = Fraction(2 * C * B - B**2, (2 * A * B))
    else: fr = Fraction((2 * C * (A + B) - A**2 - B**2 - C**2), (2 * A * B))
    print(fr.numerator, '/', fr.denominator, sep='')
Example #37
0
def fracify(a, max_denom: int = 1024, force_dyad: bool = False):
    """ Return a valid fractional weight tuple (and its dyadic completion)
        to represent the weights given by ``a``.

        When the input tuple contains only integers and fractions,
        ``fracify`` will try to represent the weights exactly.

    Parameters
    ----------
    a : Sequence
        Sequence of numbers (ints, floats, or Fractions) to be represented
        with fractional weights.

    max_denom : int
        The maximum denominator allowed for the fractional representation.
        When the fractional representation is not exact, increasing
        ``max_denom`` will typically give a better approximation.

        Note that ``max_denom`` is actually replaced with the largest power
        of 2 >= ``max_denom``.

    force_dyad : bool
        If ``True``, we force w to be a dyadic representation so that ``w == w_dyad``.
        This means that ``w_dyad`` does not need an extra dummy variable.
        In some cases, this may reduce the number of second-order cones needed to
        represent ``w``.

    Returns
    -------
    w : tuple
        Approximation of ``a/sum(a)`` as a tuple of fractions.

    w_dyad : tuple
        The dyadic completion of ``w``.

        That is, if w has fractions with denominators that are not a power of 2,
        and ``len(w) == n`` then w_dyad has length n+1, dyadic fractions for elements,
        and ``w_dyad[:-1]/w_dyad[n] == w``.

        Alternatively, the ratios between the
        first n elements of ``w_dyad`` are equal to the corresponding ratios between
        the n elements of ``w``.

        The dyadic completion of w is needed to represent the weighted geometric
        mean with weights ``w`` as a collection of second-order cones.

        The appended element of ``w_dyad`` is typically a dummy variable.

    Examples
    --------
    >>> w, w_dyad = fracify([1, 2, 3])
    >>> w
    (Fraction(1, 6), Fraction(1, 3), Fraction(1, 2))
    >>> w_dyad
    (Fraction(1, 8), Fraction(1, 4), Fraction(3, 8), Fraction(1, 4))

    >>> w, w_dyad = fracify((1, 1, 1, 1, 1))
    >>> w
    (Fraction(1, 5), Fraction(1, 5), Fraction(1, 5), Fraction(1, 5), Fraction(1, 5))
    >>> w_dyad
    (Fraction(1, 8), Fraction(1, 8), Fraction(1, 8), Fraction(1, 8), Fraction(1, 8), Fraction(3, 8))

    >>> w, w_dyad = fracify([.23, .56, .87])
    >>> w
    (Fraction(23, 166), Fraction(28, 83), Fraction(87, 166))
    >>> w_dyad
    (Fraction(23, 256), Fraction(7, 32), Fraction(87, 256), Fraction(45, 128))

    >>> w, w_dyad = fracify([3, Fraction(1, 2), Fraction(3, 5)])
    >>> w
    (Fraction(30, 41), Fraction(5, 41), Fraction(6, 41))
    >>> w_dyad
    (Fraction(15, 32), Fraction(5, 64), Fraction(3, 32), Fraction(23, 64))

    Can also mix integer, Fraction, and floating point types.

    >>> w, w_dyad = fracify([3.4, 8, Fraction(3, 2)])
    >>> w
    (Fraction(34, 129), Fraction(80, 129), Fraction(5, 43))
    >>> w_dyad
    (Fraction(17, 128), Fraction(5, 16), Fraction(15, 256), Fraction(127, 256))

    Forcing w to be dyadic makes it its own dyadic completion.

    >>> w, w_dyad = fracify([3.4, 8, Fraction(3, 2)], force_dyad=True)
    >>> w
    (Fraction(135, 512), Fraction(635, 1024), Fraction(119, 1024))
    >>> w_dyad
    (Fraction(135, 512), Fraction(635, 1024), Fraction(119, 1024))

    A standard basis unit vector should yield itself.

    >>> w, w_dyad = fracify((0, 0.0, 1.0))
    >>> w
    (Fraction(0, 1), Fraction(0, 1), Fraction(1, 1))
    >>> w_dyad
    (Fraction(0, 1), Fraction(0, 1), Fraction(1, 1))

    A dyadic weight vector should also yield itself.

    >>> a = (Fraction(1,2), Fraction(1,8), Fraction(3,8))
    >>> w, w_dyad = fracify(a)
    >>> a == w == w_dyad
    True

    Be careful when converting floating points to fractions.

    >>> a = (Fraction(.9), Fraction(.1))
    >>> w, w_dyad = fracify(a)
    Traceback (most recent call last):
    ...
    ValueError: Can't reliably represent the input weight vector.
    Try increasing `max_denom` or checking the denominators of your input fractions.

    The error here is because ``Fraction(.9)`` and ``Fraction(.1)``
    evaluate to ``(Fraction(8106479329266893, 9007199254740992)`` and
    ``Fraction(3602879701896397, 36028797018963968))``.

    """
    if any(v < 0 for v in a):
        raise ValueError('Input powers must be nonnegative.')

    if not (isinstance(max_denom, numbers.Integral) and max_denom > 0):
        raise ValueError('Input denominator must be an integer.')

    if isinstance(a, np.ndarray):
        a = a.tolist()

    max_denom = next_pow2(max_denom)
    total = sum(a)

    if force_dyad is True:
        w_frac = make_frac(a, max_denom)
    elif all(isinstance(v, (numbers.Integral, Fraction)) for v in a):
        w_frac = tuple(Fraction(v, total) for v in a)
        d = max(v.denominator for v in w_frac)
        if d > max_denom:
            msg = ("Can't reliably represent the input weight vector."
                   "\nTry increasing `max_denom` or checking the denominators "
                   "of your input fractions.")
            raise ValueError(msg)
    else:
        # fall through code
        w_frac = tuple(Fraction(float(v)/total).limit_denominator(max_denom) for v in a)
        if sum(w_frac) != 1:
            w_frac = make_frac(a, max_denom)

    return w_frac, dyad_completion(w_frac)
Example #38
0
def _sum(data, start=0):
    """_sum(data [, start]) -> value

    Return a high-precision sum of the given numeric data. If optional
    argument ``start`` is given, it is added to the total. If ``data`` is
    empty, ``start`` (defaulting to 0) is returned.


    Examples
    --------

    >>> _sum([3, 2.25, 4.5, -0.5, 1.0], 0.75)
    11.0

    Some sources of round-off error will be avoided:

    >>> _sum([1e50, 1, -1e50] * 1000)  # Built-in sum returns zero.
    1000.0

    Fractions and Decimals are also supported:

    >>> from fractions import Fraction as F
    >>> _sum([F(2, 3), F(7, 5), F(1, 4), F(5, 6)])
    Fraction(63, 20)

    >>> from decimal import Decimal as D
    >>> data = [D("0.1375"), D("0.2108"), D("0.3061"), D("0.0419")]
    >>> _sum(data)
    Decimal('0.6963')

    Mixed types are currently treated as an error, except that int is
    allowed.
    """
    # We fail as soon as we reach a value that is not an int or the type of
    # the first value which is not an int. E.g. _sum([int, int, float, int])
    # is okay, but sum([int, int, float, Fraction]) is not.
    allowed_types = set([int, type(start)])
    n, d = _exact_ratio(start)
    partials = {d: n}  # map {denominator: sum of numerators}
    # Micro-optimizations.
    exact_ratio = _exact_ratio
    partials_get = partials.get
    # Add numerators for each denominator.
    for x in data:
        _check_type(type(x), allowed_types)
        n, d = exact_ratio(x)
        partials[d] = partials_get(d, 0) + n
    # Find the expected result type. If allowed_types has only one item, it
    # will be int; if it has two, use the one which isn't int.
    assert len(allowed_types) in (1, 2)
    if len(allowed_types) == 1:
        assert allowed_types.pop() is int
        T = int
    else:
        T = (allowed_types - set([int])).pop()
    if None in partials:
        assert issubclass(T, (float, Decimal))
        assert not math.isfinite(partials[None])
        return T(partials[None])
    total = Fraction()
    for d, n in sorted(partials.items()):
        total += Fraction(n, d)
    if issubclass(T, int):
        assert total.denominator == 1
        return T(total.numerator)
    if issubclass(T, Decimal):
        return T(total.numerator)/total.denominator
    return T(total)
Example #39
0
def fraction_continue(f, a, i):
    ai = a[0] if i == 0 else a[1 + (i - 1) % (len(a) - 1)]
    if f == 0:
        return Fraction(ai)
    return ai + 1 / f
Example #40
0
    elif a == 3:
        n1, n2 = max(n1, n2), min(n1, n2)
        result = n1 / n2
    print(n1, fh[a], n2, '=', end='')
    return result


print('自动生成四则运算')
print('输入0000退出')
while True:
    a = random.randint(0, 4)
    if a == 0:
        result = fenshu()
        jg = input()
        if jg == '0000':
            break
        sr = Fraction(jg)
        if sr == result:
            print('正确')
        else:
            print('错误,正确结果是:', result)
    else:
        result = zhengshu()
        jg = input()
        if jg == '0000':
            break
        sr = int(jg)
        if sr == result:
            print('正确')
        else:
            print('错误,正确结果是:', result)
Example #41
0
for line in list_data:
    line.remove(line[0])


#implement the sudocode in here
def bad_sort(arr, start, end, alpha):
    #size of the array
    if end - start == 1 and arr[end] < arr[start]:
        arr[start], arr[end] = arr[end], arr[start]
    elif end - start > 1:
        m = int(math.ceil(alpha * (end - start + 1)))
        #the way I fix it, to avoid infinite loop
        if m == end-start+1 :
            m = m-1
        bad_sort(arr, start, start + m - 1, alpha)
        bad_sort(arr, end - m + 1, end, alpha)
        bad_sort(arr, start, start + m - 1, alpha)


if __name__ == '__main__':

    print("Please enter a fraction or decimal value for alpha < 1: ")
    alpha = float(Fraction(input()))
    for element in list_data:
        length = len(element)
        bad_sort(element, 0, length - 1, alpha)

    with open("bad.out", "w") as output_file:
        for line in list_data:
            output_file.write("%s\n" % line)
Example #42
0
def get_max_denom(tup):
    """ Get the maximum denominator in a sequence of ``Fraction`` and ``int`` objects
    """
    return max(Fraction(f).denominator for f in tup)
Example #43
0

# http://www.libragold.com/blog/2017/03/minimal-distance-to-pi/
P = calc_fraction_continue(a001203, 30) - 3

# find endpoints of Farey intervals
a, b, c, d = 0, 1, 1, 1
farey = [(a, b), (c, d)]

while True:
    f = b + d
    if f > q2 - q1: break

    e = a + c
    farey.append((e, f))
    if P < Fraction(e, f):
        c, d = e, f
    else:
        a, b = e, f

p_min = int(P * q1)

# increase p_min/min by fractions in farey
while q1 <= q2:
    c, d = 0, 0
    for a, b in farey:
        if q1 + b > q2: break
        if abs(Fraction(p_min + a, q1 + b).real -
               P) < abs(Fraction(p_min, q1).real - P):
            c, d = a, b
            break
Example #44
0
def bug_not_using_std_hash_of_rational():
    return hash(2) != hash(Integer(2)) or hash(Fraction(1,2)) != hash(Rational(1,2))
Example #45
0
 def set_phase(self, vertex, phase):
     self._phase[vertex] = Fraction(phase) % 2
Example #46
0
from collections import namedtuple
from fractions import Fraction
from decimal import Decimal as D, localcontext

with localcontext() as ctx:
    ctx.prec = 6
    pie1 = D("3.14159265358979323846264338327950") / D("2.7182818284590452353")

with localcontext() as ctx:
    ctx.prec = 25
    pie2 = D("3.14159265358979323846264338327950") / D("2.7182818284590452353")

Numbers1 = namedtuple("Numbers1", "a b c d e")
data1 = [
    Numbers1(1.23, D(pie1), 1_000_000_000_000, 2, Fraction(22, 7)),
    Numbers1(4.56, D(pie2), -22, 5, Fraction(1, 3)),
    Numbers1(7.89, D("1.0"), 56, 9, Fraction(10, 2))
]

Numbers2 = namedtuple("Numbers2", "a b c d e")
data2 = [
    Numbers1(1.23, D(pie1), 1_000_000_000_000, 2, Fraction(22, 7)),
    Numbers2(4.56, D(pie2), -22, 5, Fraction(1, 3)),
    Numbers1(7.89, D("1.0"), 56, 9, Fraction(10, 2))
]

Numbers3 = namedtuple("Numbers3", "a b c d e")
data3 = [
    Numbers3("$1.23", D(pie1), 1_000_000_000_000, 2, Fraction(22, 7)),
    Numbers3("$4.56", D(pie2), -22, 5, Fraction(1, 3)),
    Numbers3("$7.89", D("1.0"), 56, 9, Fraction(10, 2))
Example #47
0
 def phase(self, vertex):
     return self._phase.get(vertex,Fraction(1))
Example #48
0
def get_numerator(num1, num2):#분자반환
    a = Fraction(num1, num2)
    return a.numerator
Example #49
0
def c2_1(q, ans):
    n1, m1,f1,f2 = c2([], [])
    m1 = eval("".join(str(i) for i in m1))
    n1 = "".join(str(i) for i in n1)
    n1 = n1[:-1]

    fz = random.randint(1, 10)
    fm = random.randint(10, 100)
    n2 = Fraction(fz, fm)

    kuohao = random.randint(2, 4)  ##括号在前面还是在后面
    if kuohao == 2:
        symbol = random.choice(['+', '-', '*', '/'])
        if symbol == '+':
            q.append('(' + n1 + ')' + '+' + str(n2) + '=')
            ans.append(str(Fraction(f1,f2) + n2))
        elif symbol == '-':
            while m1 < n2:
                fz = random.randint(0, 10)
                fm = random.randint(10, 100)
                n2 = Fraction(fz, fm)
            q.append('(' + n1 + ')' + '-' + str(n2) + '=')
            ans.append(str(Fraction(f1,f2)  - n2))
        elif symbol == '*':
            q.append('(' + n1 + ')' + '×' + str(n2) + '=')
            ans.append(str(Fraction(f1,f2)  * n2))
        else:
            q.append('(' + n1 + ')' + '÷' + str(n2) + '=')
            ans.append(str(Fraction(Fraction(f1,f2) ,n2)))

    else:
        symbol = random.choice(['+', '-', '*', '/'])
        if symbol == '+':
            q.append(str(n2) + '+' + '(' + n1 + ')' + '=')
            ans.append(str(n2 + Fraction(f1,f2) ))
        elif symbol == '-':
            while m1 > n2:
                fz = random.randint(0, 1000)
                fm = random.randint(1, 10)
                n2 = Fraction(fz, fm)
            q.append(str(n2) + '-' + '(' + n1 + ')' + '=')
            ans.append(str(n2 - Fraction(f1,f2) ))
        elif symbol == '*':
            q.append(str(n2) + '×' + '(' + n1 + ')' + '=')
            ans.append(str(n2 * Fraction(f1,f2) ))
        elif symbol == '/':
            q.append(str(n2) + '÷' + '(' + n1 + ')' + '=')
            ans.append(str(Fraction(n2,Fraction(f1,f2) )))

    return q, ans
Example #50
0
 def test_lista_fracionarios(self):
   dados = [Fraction(1,5), Fraction(2,5), Fraction(2,5)]
   resultado = soma(dados)
   self.assertEqual(resultado, 1)
 def fracdec(a):
     return Fraction(Decimal(a))
Example #52
0
    def build_train_cln(self,
                        template,
                        consts,
                        max_epoch=4000,
                        non_loop_invariant=None,
                        max_denominator=10,
                        pname=1):
        loss_threshold = 1e-6

        if template.is_static():
            return [template.to_z3()], False

        if self.df_data is None:
            self.df_data = load_trace(self.csv_name)
        df_data = self.df_data
        data = df_data.to_numpy(dtype=np.float)
        data = np.unique(data, axis=0)
        data_n = data_normalize(data)
        self.data = data
        self.data_n = data_n
        var_names = list(df_data.columns)

        cln_model, weights, bs, Bs, epss = build_cln(template, var_names)

        ges, les, eqs = infer_single_var_bounds_consts(df_data, consts)

        input_size = data.shape[1]
        coeff = None

        if input_size > 1:
            converged = False

            # data preparation
            inputs_np = np.array(data_n, copy=True)
            means_input, std_input = np.zeros(
                [input_size], dtype=np.double), np.zeros([input_size],
                                                         dtype=np.double)
            for i in range(input_size):
                means_input[i] = np.mean(data_n[:, i])
                std_input[i] = np.std(data_n[:, i])
                inputs_np[:, i] = (data_n[:, i] - means_input[i])
            inputs_n = torch.tensor(inputs_np, dtype=torch.float)
            inputs = torch.tensor(data, dtype=torch.float)

            b_factor = 0.010

            B_factor, eps_factor = 0.025, 0.025
            B_target = 20.0

            loss_trace = []

            optimizer = torch.optim.Adam(weights + bs + Bs + epss, lr=0.01)
            for epoch in range(max_epoch):
                optimizer.zero_grad()
                cln_out = cln_model(inputs, inputs_n).squeeze()
                primary_loss = 1 - cln_out.mean()

                if primary_loss < loss_threshold:
                    converged = True
                    break

                l_bs, l_Bs, l_eps = 0, 0, 0
                if bs:
                    l_bs = b_factor * torch.norm(torch.cat(bs), p=1)
                    # l_bs = b_factor*torch.norm((torch.cat(bs)*.5)**2, p=1)
                if Bs:
                    l_Bs = torch.clamp(B_factor *
                                       (B_target - torch.cat(Bs).mean()),
                                       min=0)
                if epss:
                    l_eps = eps_factor * torch.norm(torch.cat(epss), p=2)

                loss = primary_loss + l_bs + l_Bs + l_eps

                # loss_trace.append(loss.item())
                # if epoch%10 == 9 and np.std(loss_trace[-9:]) < 1e-5:
                # break

                loss.backward()
                torch.nn.utils.clip_grad_norm_(cln_model.parameters(), 0.01)

                optimizer.step()

            # calculate final coeff
            weight = torch.stack(weights)
            coeff_ = weight.detach().numpy().reshape([input_size])
            scaled_coeff = np.round(coeff_ / np.abs(coeff_).min())
            coeff = []
            denominator = 1
            for i in range(input_size):
                a = Fraction.from_float(float(
                    coeff_[i])).limit_denominator(max_denominator)
                coeff.append(a)
                denominator = denominator * a.denominator // gcd(
                    denominator, a.denominator)
            coeff = np.asarray([[floor(a * denominator) for a in coeff]])

            # extract ineqs
            ineq_constrs = cln_model.get(IneqConstraint)

            ineqs = []
            for ineq_constr in ineq_constrs:
                coeffs = {}
                for w, var in zip(ineq_constr.weight.flatten(), var_names):
                    if w != 0:
                        coeffs[var] = int(round(w.item()))
                ineqs.append((coeffs, int(round(ineq_constr.b.item())),
                              ineq_constr.op_str))

        Is = construct_invariant(var_names, coeff, ges, les, eqs, ineqs, '',
                                 non_loop_invariant)
        if scaled_coeff.max() < 50:  # large coeffs cause z3 timeouts
            scaled_Is = construct_invariant(var_names,
                                            scaled_coeff.reshape(1,
                                                                 -1), ges, les,
                                            eqs, ineqs, '', non_loop_invariant)
            Is.extend(scaled_Is)

        # for I in Is:
        # print(I)
        return Is, True
Example #53
0
#!/usr/bin/env python3

# 3.8 分数运算
import math
# 你进入时间机器,突然发现你正在做小学家庭作业,并涉及到分数计算问题。或者你可能需要写代码去计算在你的木工工厂中的测量值
if __name__ == "__main__":
    # fractions 模块可以被用来执行包含分数的数学运算。
    from fractions import Fraction

    a = Fraction(5, 4)
    b = Fraction(7, 16)
    print("a: ", a)
    print("b: ", b)
    print("a + b: ", a + b)
    print("a * b: ", a * b)

    # Getting numerator/denominator
    c = a * b
    print("c: ", c)
    print("c.numerator: ", c.numerator)
    print("c.denominator: ", c.denominator)

    # Converting to a float
    print("float(c): ", float(c))

    # Limiting the denominator of a value
    print("c.limit_denominator(8): ", c.limit_denominator(8))

    # Converting a float to a fraction
    x = 3.75
    y = Fraction(*x.as_integer_ratio())
Example #54
0
from fractions import Fraction
import numpy as np

a = [Fraction(22 / 7)]

for i in range(8, 1000000):
	frac = Fraction(np.pi).limit_denominator(i)
	if abs(float(a[-1]) - np.pi) > abs(float(frac) - np.pi):
		a.append(frac)

Example #55
0
    epd.init()
    lastVideo = currentVideo
    randomVideo = random.randint(0 , len(videos) - 1)
    currentVideo = os.path.join(viddir, videos[randomVideo])

    if lastVideo != currentVideo:
        # Check how many frames are in the movie
        if currentVideo in videoInfos:
            videoInfo = videoInfos[currentVideo]
        else:
            videoInfo = ffmpeg.probe(currentVideo)
            videoInfos[currentVideo] = videoInfo

        frameCount = int(videoInfo["streams"][0]["nb_frames"])
        framerate = videoInfo["streams"][0]["avg_frame_rate"]
        framerate = float(Fraction(framerate))
        frametime = 1000 / framerate

    # Pick a random frame
    frame = random.randint(0, frameCount)

    # Convert that frame to Timecode
    msTimecode = "%dms" % (frame * frametime)

    # Use ffmpeg to extract a frame from the movie, letterbox/pillarbox, and save it
    generate_frame(currentVideo, "/dev/shm/frame.bmp", msTimecode)

    # Open image in PIL
    pil_im = Image.open("/dev/shm/frame.bmp")

    enhancer = ImageEnhance.Contrast(pil_im)
Example #56
0
def calc_fraction_continue(a, k):
    f = Fraction(0)
    while k > 0:
        k -= 1
        f = fraction_continue(f, a, k)
    return f
Example #57
0
import re
from fractions import Fraction

lv = lambda x: 10**len(str(x)) if x != "0" else 1
lvten = lambda x: 10**len(str(x))

result = re.match(r"^(?P<int>\d+)(?:\.(?P<just>\d+)?(?:\((?P<rep>\d+)\))?)?$",
                  input()).groupdict()
integral = result["int"]
just = result["just"] or ""
rep = result["rep"] or ""

numerator = (int(integral + just + rep) -
             int(integral + just) if rep else int(integral + just))
denominator = int(
    ("9" * len(rep) + "0" * len(just)) or "1") or int("1" + "0" * len(just))

frac = Fraction(numerator, denominator)
print(f"{frac.numerator}/{frac.denominator}")
Example #58
0
from fractions import Fraction


def divided_difference(values):
    """Calculates the divided difference using the given samples."""
    if len(values) == 1:
        return values[0][1]

    if len(values) == 2:
        return (values[0][1] - values[1][1]) / (values[0][0] - values[1][0])

    return (divided_difference(values[1:]) -
            divided_difference(values[0:-1])) / (values[-1][0] - values[0][0])


print('Divided differences for task 1')
tups = [(0, 4), (1, -1), (2, -3), (4, -6), (6, 9), (3, -5)]
for i in range(0, len(tups)):
    print(tups[:i + 1],
          Fraction(divided_difference(tups[:i + 1])).limit_denominator())

print('Divided differences for task 2')
tups = [(1.885, -1.101), (1.074, 0.549), (-0.074, 0.05), (-0.885, 0.496)]
for i in range(0, len(tups)):
    print(tups[:i + 1], divided_difference(tups[:i + 1]))
Example #59
0
def check_fract(num):
    try:
        Fraction(num)
        return True
    except:
        return False
Example #60
0
# The problem: https://projecteuler.net/problem=65
# Very similar to problem 57
# This one is really

from fractions import Fraction

j = 2
coefficients = [1, 2]
for i in range(1, 99):
    if not i % 3:
        coefficients.append(j * 2)
        j += 1
    else:
        coefficients.append(1)

# used to verify that it was working, setting to 100 runs the actual problem
test_num = 100
frac = 0
for i in range(test_num, 1, -1):
    frac = Fraction(1, frac + coefficients[i - 2])
frac = 2 + frac

print(sum(map(int, str(frac.numerator))))