コード例 #1
0
def test_minimal_fractions_3():
    assert minimal(
        lists(fractions()), lambda s: len(s) >= 20) == [Fraction(0)] * 20
コード例 #2
0
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='')
コード例 #3
0
ファイル: power_tools.py プロジェクト: whoiszyc/cvxpy
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
コード例 #4
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)
コード例 #5
0
ファイル: helpers.py プロジェクト: Scotti18/Recipes
def check_fract(num):
    try:
        Fraction(num)
        return True
    except:
        return False
コード例 #6
0
def calc_fraction_continue(a, k):
    f = Fraction(0)
    while k > 0:
        k -= 1
        f = fraction_continue(f, a, k)
    return f
コード例 #7
0
ファイル: badSort.py プロジェクト: Liuyih/algorithm
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)
コード例 #8
0
 def phase(self, vertex):
     return self._phase.get(vertex,Fraction(1))
コード例 #9
0
 def set_phase(self, vertex, phase):
     self._phase[vertex] = Fraction(phase) % 2
コード例 #10
0
ファイル: CHAPTER1.py プロジェクト: uuuugi/study_python_algo
def get_numerator(num1, num2):#분자반환
    a = Fraction(num1, num2)
    return a.numerator
コード例 #11
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())
コード例 #12
0
ファイル: CHAPTER1.py プロジェクト: uuuugi/study_python_algo
def get_denominator(num1, num2):#분모반환
    a = Fraction(num1, num2)
    return a.denominator
コード例 #13
0
ファイル: CHAPTER1.py プロジェクト: uuuugi/study_python_algo
def float_to_fractions(num): #분수로반환
    return Fraction(*num.as_integer_ratio())
コード例 #14
0
def test_minimal_fractions_4():
    x = minimal(
        lists(fractions(), min_size=20),
        lambda s: len([t for t in s if t >= 1]) >= 20
    )
    assert x == [Fraction(1)] * 20
コード例 #15
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
コード例 #16
0
 def add_to_phase(self, vertex, phase):
     self._phase[vertex] = (self._phase.get(vertex,Fraction(1)) + Fraction(phase)) % 2
コード例 #17
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
コード例 #18
0
ファイル: line_constructor.py プロジェクト: dpazel/music_rep
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)
コード例 #19
0
 def test_lista_fracionarios(self):
   dados = [Fraction(1,5), Fraction(2,5), Fraction(2,5)]
   resultado = soma(dados)
   self.assertEqual(resultado, 1)
コード例 #20
0
ファイル: _5_2_decimal.py プロジェクト: mutiantong/python
#!/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)
コード例 #21
0
ファイル: sympy_bugs.py プロジェクト: edt-yxz-zzd/python3_src
def bug_not_using_std_hash_of_rational():
    return hash(2) != hash(Integer(2)) or hash(Fraction(1,2)) != hash(Rational(1,2))
コード例 #22
0
ファイル: problem_65.py プロジェクト: cgiven25/project_euler
# 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))))
コード例 #23
0
ファイル: sizeyunsuan1.py プロジェクト: Wallrving/Wallhub
    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)
コード例 #24
0
 def fracdec(a):
     return Fraction(Decimal(a))
コード例 #25
0
ファイル: statistics.py プロジェクト: 2139272/cmark-gfm
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)
コード例 #26
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))
コード例 #27
0
ファイル: power_tools.py プロジェクト: whoiszyc/cvxpy
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)
コード例 #28
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
コード例 #29
0
ファイル: power_tools.py プロジェクト: whoiszyc/cvxpy
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)
コード例 #30
0
def test_minimal_fractions_2():
    assert minimal(fractions(), lambda x: x >= 1) == Fraction(1)