def from_decimal(cls, dec): from decimal import Decimal if isinstance(dec, numbers.Integral): dec = Decimal(int(dec)) elif not isinstance(dec, Decimal): raise TypeError( "%s.from_decimal() only takes Decimals, not %r (%s)" % (cls.__name__, dec, type(dec).__name__)) return cls(*dec.as_integer_ratio())
def from_decimal(cls, dec): """Converts a finite Decimal instance to a rational number, exactly.""" from decimal import Decimal if isinstance(dec, numbers.Integral): dec = Decimal(int(dec)) elif not isinstance(dec, Decimal): raise TypeError( "%s.from_decimal() only takes Decimals, not %r (%s)" % (cls.__name__, dec, type(dec).__name__)) return cls(*dec.as_integer_ratio())
class Note: decimal_two = Decimal(2) def __init__(self, note_num=60, note_len=Decimal(0.25), is_rest=False): self.midi_num = note_num self.note_len = Decimal(note_len) self.is_rest = is_rest # checks if the note has a valid length # returns true if the note is a multiple of a nonpositive power of two def is_valid_length(self): numer, denom = map(Decimal, self.note_len.as_integer_ratio()) log = denom.log10() / self.decimal_two.log10() return math.ceil(log) == math.floor(log) and numer <= denom def __str__(self): return "(Note number = {}, length = {}, is_rest = {})".format(self.midi_num,self.note_len, self.is_rest)
adjusted() return the adjusted exponent as_integer_ratio() return a pair (n, d) of integers that represent the given Decimal instance as a fraction as_tuple() return a named tuple DecimalTuple(sign, digits, exponent) copy_abs() return the absolute value of the argument copy_sign(other) return a copy of the first operand with the sign set to be the same as other exp() return the value of the (natural) exponential function e**x at the given number quantize(exp, rounding=None) round a number to a fixed exponent Rounding modes decimal.ROUND_CEILING round towards Infinity decimal.ROUND_FLOOR round towards -Infinity decimal.ROUND_UP round away from zero decimal.ROUND_DOWN round towards zero decimal.ROUND_HALF_UP round to nearest with ties going away from zero. decimal.ROUND_HALF_DOWN round to nearest with ties going towards zero decimal.ROUND_HALF_EVEN round to nearest with ties going to nearest even integer """ import decimal from decimal import Decimal a = Decimal(-139) + Decimal('-2e-5') + Decimal('1.53') print(a) print(a.adjusted()) # the position of the most significant digit with respect to the decimal point print(a.as_integer_ratio()) print(a.as_tuple()) # sign 0 for positive or 1 for negative print(a.copy_abs(), a.quantize(Decimal('1.000'), rounding=decimal.ROUND_UP)) b = Decimal(15) print(a, b, a + b, a - b, a * b, a / b)
from decimal import Decimal, getcontext # incorrect getcontext().prec = 100 t = 0 for i in range(2, 100): s = Decimal(i).sqrt() if s.as_integer_ratio()[1] != 1: for i in str(s)[2:]: t += int(i) print(t) print(t)
def lecture_graphe(path): f = open(path) # Parse du nombre de sommets try: nb_sommets = Decimal(f.readline()) if nb_sommets.as_integer_ratio()[1] != 1: raise Exception nb_sommets = int(nb_sommets) if nb_sommets <= 0: raise Exception except: print('SyntaxError:', 'Erreur à la ligne 1, le nombre de sommets doit être un nombre entier positif non nul') f.close() return None # Parse du nombre d'arcs try: nb_arcs = Decimal(f.readline()) if nb_arcs.as_integer_ratio()[1] != 1: raise Exception nb_arcs = int(nb_arcs) if nb_arcs < 0: raise Exception except: print('SyntaxError:', 'Erreur à la ligne 2, le nombre de d\'arcs doit être un nombre entier') f.close() return None arcs = [] i = 2 # Déclaration des arcs for line in f.readlines(): i += 1 line = line.strip().split(' ') # Nombre d'arguments dans la lignes if len(line) != 3: print('SyntaxError:', f'Erreur à la ligne {i}, l\'arc ne contient pas le bon nombre de valeurs') f.close() return None # Parse de l'argument 1 try: line[0] = Decimal(line[0]) if line[0].as_integer_ratio()[1] != 1: raise Exception line[0] = int(line[0]) if not 0 <= line[0] < nb_sommets: raise Exception except: print('SyntaxError:', f'Erreur à la ligne {i}, le sommet de départ n\'existe pas') f.close() return None # Parse de l'argument 2 try: line[1] = Decimal(line[1]) if line[1].as_integer_ratio()[1] != 1: raise Exception line[1] = int(line[1]) if not 0 <= line[1] < nb_sommets: raise Exception except: print('SyntaxError:', f'Erreur à la ligne {i}, le sommet d\'arrivée n\'existe pas') f.close() return None # Parse de l'argument 3 try: line[2] = Decimal(line[2]) except: print('SyntaxError:', f'Erreur à la ligne {i}, la pondération de l\'arc doit être un nombre') f.close() return None # Ajout de l'arc à la liste arcs.append(line) # Vérification du nombre d'arcs difference_arcs = len(arcs) - nb_arcs if (difference_arcs != 0): accord_pluriel = "s" if abs(difference_arcs) > 1 else "" print('SyntaxError:', f'{abs(difference_arcs)} arc{accord_pluriel} {"manquant" if difference_arcs < 0 else "supplémentaire"}{accord_pluriel} dans la déclaration du graphe') f.close() return None f.close() return nb_sommets, nb_arcs, arcs