Python fractions 模块,Fraction() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用fractions.Fraction()

项目:code    作者:ActiveState    | 项目源码 | 文件源码
def spread(count, start, end=None, step=None, mode=1):
    if end is step is None:
        raise TypeError('one of end or step must be given')
    if not isinstance(mode, int):
        raise TypeError('mode must be an int')
    if count != int(count):
        raise ValueError('count must be an integer')
    elif count <= 0:
        raise ValueError('count must be positive')
    if mode & 1:
        yield start
    if end is None:
        step = Fraction(step)
        end = start + count*step
    else:
        step = Fraction(end-start)/count
    start = Fraction(start)
    for i in range(1, count):
        yield float(start + i*step)
    if mode & 2:
        yield float(end)
项目:FPTuner    作者:soarlab    | 项目源码 | 文件源码
def __init__ (self, val): 
        assert((type(val) is int) or (isinstance(val, Fraction)) or (type(val) is float))
        if (type(val) is float): 
            val = Fraction(val)

        if (sys.version_info.major == 2): 
            sys.exit("Error: FPTuner is currently based on Python3 only...") 
            super(ConstantExpr, self).__init__(False) 
        elif (sys.version_info.major == 3):
            super().__init__(False) 
        else:
            sys.exit("ERROR: not supported python version: " + str(sys.version_info)) 

        self.operands.append(val)
        self.lower_bound = val 
        self.upper_bound = val 
        self.gid        = -1
项目:FPTuner    作者:soarlab    | 项目源码 | 文件源码
def concEval (self, vmap = {}): 
        retv = self.opd().concEval(vmap)
        assert((type(retv) is int) or (type(retv) is float) or (isinstance(retv, Fraction))) 
        if (self.operator.label == "abs"): 
            return abs(retv) 
        elif (self.operator.label == "sqrt"): 
            return math.sqrt(retv) 
        elif (self.operator.label == "-"): 
            if (type(retv) is int): 
                return (-1 * retv)
            elif ((type(retv) is float) or (isinstance(retv, Fraction))): 
                return (-1.0 * retv) 
            else: 
                assert(False) 
        else: 
            sys.exit("ERROR: unknwon operator found in function \"concEval\" of a UnaryExpr")
项目:FPTuner    作者:soarlab    | 项目源码 | 文件源码
def concEval (self, vmap = {}): 
        retv_lhs = self.lhs().concEval(vmap) 
        assert((type(retv_lhs) is int) or (type(retv_lhs) is float) or (isinstance(retv_lhs, Fraction))) 
        retv_rhs = self.rhs().concEval(vmap) 
        assert((type(retv_rhs) is int) or (type(retv_rhs) is float) or (isinstance(retv_rhs, Fraction))) 

        if (self.operator.label == "+"): 
            return (retv_lhs + retv_rhs) 
        elif (self.operator.label == "-"): 
            return (retv_lhs - retv_rhs)
        elif (self.operator.label == "*"): 
            return (retv_lhs * retv_rhs) 
        elif (self.operator.label == "/"): 
            return (retv_lhs / retv_rhs) 
        elif (self.operator.label == "^"): 
            assert(type(retv_rhs) is int) 
            return math.pow(retv_lhs, retv_rhs) 
        else: 
            sys.exit("ERROR: unknown operator found in function \"similar\" of a BinaryExpr")
项目:FPTuner    作者:soarlab    | 项目源码 | 文件源码
def addVar (self, ve):
        assert(isinstance(ve, tft_expr.VariableExpr))

        vlabel = ve.label()
        vtype  = ve.type()
        lb     = None
        if (ve.hasLB()):
            lb = ve.lb().value()
        ub     = None
        if (ve.hasUB()):
            ub = ve.ub().value() 
        assert(vtype in [int, float, Fraction])

        if (vlabel not in self.variables.keys()):
            self.variables[vlabel] = [vtype, lb, ub]
        else:
            assert(vtype is self.variables[vlabel][0])
            assert(lb is self.variables[vlabel][1])
            assert(ub is self.variables[vlabel][2])
项目:FPTuner    作者:soarlab    | 项目源码 | 文件源码
def FConst (fpn): 
    global CONST_ID 

    assert((type(fpn) is float) or (isinstance(fpn, Fraction))) 
    # return tft_expr.ConstantExpr(fpn)

    const_value = tft_expr.ConstantExpr( fpn ) 
    const_name  = tft_expr.PRESERVED_CONST_VPREFIX + "_" + str(CONST_ID) 
    CONST_ID    = CONST_ID + 1 

    return DeclareBoundedVar(const_name, 
                             Fraction, 
                             tft_expr.PRESERVED_CONST_GID, 
                             const_value, const_value, 
                             True)                              


# NOTE: Please don't call this function internally...
项目:mugen    作者:scherroman    | 项目源码 | 文件源码
def speed_multiply(self, speed: Union[float, Fraction],
                       offset: Opt[int] = None):
        """
        Speeds up or slows down events by grouping them together or splitting them up.
        For slowdowns, event type group boundaries and isolated events are preserved.

        Parameters
        ----------
        speed
            Factor to speedup or slowdown by. 
            Must be of the form x (speedup) or 1/x (slowdown), where x is a natural number.
            Otherwise, 0 to remove all events.

        offset
            Offsets the grouping of events for slowdowns.
            Takes a max offset of x - 1 for a slowdown of 1/x, where x is a natural number
        """
        if speed == 0:
            self.clear()
        elif speed > 1:
            self._split(speed.numerator)
        elif speed < 1:
            self._merge(speed.denominator, offset)
项目:esys-pbi    作者:fsxfreak    | 项目源码 | 文件源码
def __init__(self, file_loc,fps=30):
        super().__init__()
        # the approximate capture rate.
        self.fps = int(fps)
        self.time_base = Fraction(1000,self.fps*1000)
        file_loc = str(file_loc) #force str over unicode.
        try:
            file_path,ext = file_loc.rsplit('.', 1)
        except:
            logger.error("'{}' is not a valid media file name.".format(file_loc))
            raise Exception("Error")

        if ext not in ('mp4'):
            logger.warning("media file container should be mp4. Using a different container is risky.")

        self.file_loc = file_loc
        self.container = av.open(self.file_loc,'w')
        logger.debug("Opened '{}' for writing.".format(self.file_loc))

        self.video_stream = self.container.add_stream('mjpeg',1/self.time_base)
        self.video_stream.pix_fmt = "yuvj422p"
        self.configured = False
        self.frame_count = 0

        self.write_video_frame_compressed = self.write_video_frame
项目:keras-text    作者:raghakot    | 项目源码 | 文件源码
def multi_label_train_test_split(y, test_size=0.2):
    """Creates a test split with roughly the same multi-label distribution in `y`.

    Args:
        y: The multi-label outputs.
        test_size: The test size in [0, 1]

    Returns:
        The train and test indices.
    """
    if test_size <= 0 or test_size >= 1:
        raise ValueError("`test_size` should be between 0 and 1")

    # Find the smallest rational number.
    frac = Fraction(test_size).limit_denominator()
    test_folds, total_folds = frac.numerator, frac.denominator
    logger.warn('Inferring test_size as {}/{}. Generating {} folds. The algorithm might fail if denominator is large.'
                .format(test_folds, total_folds, total_folds))

    folds = equal_distribution_folds(y, folds=total_folds)
    test_indices = np.concatenate(folds[:test_folds])
    train_indices = np.concatenate(folds[test_folds:])
    return train_indices, test_indices
项目:Graphene    作者:ashivni    | 项目源码 | 文件源码
def lowStrainApproximation(l1,l2,ep_max=0.0001,d_start=1,d_fac=2):
    """
    Find r1, r2 such that abs(0.5*(l1*r1 - l2*r2)/min(l2*r2,l1*r1)) < ep_max
    """

    ep = 1.0    # strain
    d = d_start
    while abs(ep) > ep_max:
        r1 = Fraction(l2/l1).limit_denominator(d).numerator
        r2 = Fraction(l2/l1).limit_denominator(d).denominator
        if r1 > d:
            r2 = Fraction(l1/l2).limit_denominator(d).numerator
            r1 = Fraction(l1/l2).limit_denominator(d).denominator
        if r1 > d:
            print (l1, l2)
            raise Exception('Cannot find good approximation')
        if r2 == 0 or r1 == 0:
            d *= d_fac
        else:
            ep = 0.5*(l1*r1 - l2*r2)/min(l2*r2,l1*r1)
            if abs(ep) > ep_max:
                d *= d_fac

    return r1, r2
项目:jsntlib    作者:JarryShaw    | 项目源码 | 文件源码
def continuedFraction(numerator, denominator=None):
    if denominator is None:     denominator = 1

    real_check(numerator, denominator); notneg_check(numerator, denominator)

    x = fractions.Fraction(numerator, denominator)
    a = jsfloor(x)
    x -= a
    cf_ = [a]

    while x != 0:
        x = 1 / x
        a = jsfloor(x)
        x -= a
        cf_.append(a)

    if cf_[-1] == 2:    cf_[-1:] = [1, 1]
    return cf_
项目:blocksver    作者:ndrchvzz    | 项目源码 | 文件源码
def main():
    cachePath = os.path.join(tempfile.gettempdir(), CACHEFILE)
    cache = loadCache(cachePath, BASE64)
    chainInfo = rpcRetrieve('getblockchaininfo')
    bestHash = chainInfo['bestblockhash']
    height = int(chainInfo['blocks'])
    bip9forks = chainInfo['bip9_softforks']
    print(formatWelcome(cache, WINDOW, bestHash, height,
                        F(chainInfo['difficulty']), bip9forks, THRESHOLD))
    if cache.height == 0:
        print('Please wait while retrieving latest block versions and caching them...\n')
    if len(cache.hashes) < 1 or cache.hashes[0] != bestHash:
        retrieveBlock = lambda h: rpcRetrieve('getblock', h)
        cache = updateCache(cache, WINDOW, HASHES_SIZE, bestHash, height, retrieveBlock)
        saveCache(cache, cachePath, BASE64)
    print(formatAllData(cache, bip9forks, THRESHOLD, WINDOW))
项目:jsonplus    作者:randomir    | 项目源码 | 文件源码
def _json_default_exact(obj):
    """Serialization handlers for types unsupported by `simplejson` 
    that try to preserve the exact data types.
    """
    classname = type(obj).__name__
    handlers = {
        'datetime': methodcaller('isoformat'),
        'date': methodcaller('isoformat'),
        'time': methodcaller('isoformat'),
        'timedelta': partial(getattrs, attrs=['days', 'seconds', 'microseconds']),
        'tuple': list,
        'set': list,
        'frozenset': list,
        'complex': partial(getattrs, attrs=['real', 'imag']),
        'Decimal': str,
        'Fraction': partial(getattrs, attrs=['numerator', 'denominator']),
        'UUID': partial(getattrs, attrs=['hex']),
    }
    if classname in handlers:
        return {"__class__": classname,
                "__value__": handlers[classname](obj)}
    elif isinstance(obj, tuple) and classname != 'tuple':
        return {"__class__": "namedtuple",
                "__value__": _dump_namedtuple(classname, obj)}
    raise TypeError(repr(obj) + " is not JSON serializable")
项目:jsonplus    作者:randomir    | 项目源码 | 文件源码
def _json_default_compat(obj):
    classname = type(obj).__name__
    handlers = {
        'datetime': methodcaller('isoformat'),
        'date': methodcaller('isoformat'),
        'time': methodcaller('isoformat'),
        'timedelta': _timedelta_total_seconds,
        'set': list,
        'frozenset': list,
        'complex': partial(getattrs, attrs=['real', 'imag']),
        'Fraction': partial(getattrs, attrs=['numerator', 'denominator']),
        'UUID': str
    }
    if classname in handlers:
        return handlers[classname](obj)
    raise TypeError(repr(obj) + " is not JSON serializable")
项目:jsonplus    作者:randomir    | 项目源码 | 文件源码
def _json_object_hook(dict):
    """Deserialization handlers for types unsupported by `simplejson`.
    """
    classname = dict.get('__class__')
    handlers = {
        'datetime': parse_datetime,
        'date': lambda v: parse_datetime(v).date(),
        'time': lambda v: parse_datetime(v).timetz(),
        'timedelta': kwargified(timedelta),
        'tuple': tuple,
        'set': set,
        'frozenset': frozenset,
        'complex': kwargified(complex),
        'Decimal': Decimal,
        'Fraction': kwargified(Fraction),
        'namedtuple': _load_namedtuple,
        'UUID': kwargified(uuid.UUID)
    }
    if classname:
        constructor = handlers.get(classname)
        value = dict.get('__value__')
        if constructor:
            return constructor(value)
        raise TypeError("Unknown class: '%s'" % classname)
    return dict
项目:uci-statnlp    作者:sameersingh    | 项目源码 | 文件源码
def modified_precision(references, hypothesis, n):
    # Extracts all ngrams in hypothesis
    # Set an empty Counter if hypothesis is empty.
    counts = Counter(ngrams(hypothesis, n)) if len(hypothesis) >= n else Counter()
    # Extract a union of references' counts.
    ## max_counts = reduce(or_, [Counter(ngrams(ref, n)) for ref in references])
    max_counts = {}
    for reference in references:
        reference_counts = Counter(ngrams(reference, n)) if len(reference) >= n else Counter()
        for ngram in counts:
            max_counts[ngram] = max(max_counts.get(ngram, 0),
                                    reference_counts[ngram])

    # Assigns the intersection between hypothesis and references' counts.
    clipped_counts = {ngram: min(count, max_counts[ngram])
                      for ngram, count in counts.items()}

    numerator = sum(clipped_counts.values())
    # Ensures that denominator is minimum 1 to avoid ZeroDivisionError.
    # Usually this happens when the ngram order is > len(reference).
    denominator = max(1, sum(counts.values()))

    return Fraction(numerator, denominator)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def testInit(self):
        self.assertEqual((0, 1), _components(F()))
        self.assertEqual((7, 1), _components(F(7)))
        self.assertEqual((7, 3), _components(F(F(7, 3))))

        self.assertEqual((-1, 1), _components(F(-1, 1)))
        self.assertEqual((-1, 1), _components(F(1, -1)))
        self.assertEqual((1, 1), _components(F(-2, -2)))
        self.assertEqual((1, 2), _components(F(5, 10)))
        self.assertEqual((7, 15), _components(F(7, 15)))
        self.assertEqual((10**23, 1), _components(F(10**23)))

        self.assertEqual((3, 77), _components(F(F(3, 7), 11)))
        self.assertEqual((-9, 5), _components(F(2, F(-10, 9))))
        self.assertEqual((2486, 2485), _components(F(F(22, 7), F(355, 113))))

        self.assertRaisesMessage(ZeroDivisionError, "Fraction(12, 0)",
                                 F, 12, 0)
        self.assertRaises(TypeError, F, 1.5 + 3j)

        self.assertRaises(TypeError, F, "3/2", 3)
        self.assertRaises(TypeError, F, 3, 0j)
        self.assertRaises(TypeError, F, 3, 1j)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def testFromDecimal(self):
        self.assertRaises(TypeError, F.from_decimal, 3+4j)
        self.assertEqual(F(10, 1), F.from_decimal(10))
        self.assertEqual(F(0), F.from_decimal(Decimal("-0")))
        self.assertEqual(F(5, 10), F.from_decimal(Decimal("0.5")))
        self.assertEqual(F(5, 1000), F.from_decimal(Decimal("5e-3")))
        self.assertEqual(F(5000), F.from_decimal(Decimal("5e3")))
        self.assertEqual(1 - F(1, 10**30),
                         F.from_decimal(Decimal("0." + "9" * 30)))

        self.assertRaisesMessage(
            TypeError, "Cannot convert Infinity to Fraction.",
            F.from_decimal, Decimal("inf"))
        self.assertRaisesMessage(
            TypeError, "Cannot convert -Infinity to Fraction.",
            F.from_decimal, Decimal("-inf"))
        self.assertRaisesMessage(
            TypeError, "Cannot convert NaN to Fraction.",
            F.from_decimal, Decimal("nan"))
        self.assertRaisesMessage(
            TypeError, "Cannot convert sNaN to Fraction.",
            F.from_decimal, Decimal("snan"))
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_accumulate(self):
        self.assertEqual(list(accumulate(range(10))),               # one positional arg
                          [0, 1, 3, 6, 10, 15, 21, 28, 36, 45])
        self.assertEqual(list(accumulate(iterable=range(10))),      # kw arg
                          [0, 1, 3, 6, 10, 15, 21, 28, 36, 45])
        for typ in int, complex, Decimal, Fraction:                 # multiple types
            self.assertEqual(
                list(accumulate(map(typ, range(10)))),
                list(map(typ, [0, 1, 3, 6, 10, 15, 21, 28, 36, 45])))
        self.assertEqual(list(accumulate('abc')), ['a', 'ab', 'abc'])   # works with non-numeric
        self.assertEqual(list(accumulate([])), [])                  # empty iterable
        self.assertEqual(list(accumulate([7])), [7])                # iterable of length one
        self.assertRaises(TypeError, accumulate, range(10), 5)      # too many args
        self.assertRaises(TypeError, accumulate)                    # too few args
        self.assertRaises(TypeError, accumulate, x=range(10))       # unexpected kwd arg
        self.assertRaises(TypeError, list, accumulate([1, []]))     # args that don't add
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def testInit(self):
        self.assertEqual((0, 1), _components(F()))
        self.assertEqual((7, 1), _components(F(7)))
        self.assertEqual((7, 3), _components(F(F(7, 3))))

        self.assertEqual((-1, 1), _components(F(-1, 1)))
        self.assertEqual((-1, 1), _components(F(1, -1)))
        self.assertEqual((1, 1), _components(F(-2, -2)))
        self.assertEqual((1, 2), _components(F(5, 10)))
        self.assertEqual((7, 15), _components(F(7, 15)))
        self.assertEqual((10**23, 1), _components(F(10**23)))

        self.assertEqual((3, 77), _components(F(F(3, 7), 11)))
        self.assertEqual((-9, 5), _components(F(2, F(-10, 9))))
        self.assertEqual((2486, 2485), _components(F(F(22, 7), F(355, 113))))

        self.assertRaisesMessage(ZeroDivisionError, "Fraction(12, 0)",
                                 F, 12, 0)
        self.assertRaises(TypeError, F, 1.5 + 3j)

        self.assertRaises(TypeError, F, "3/2", 3)
        self.assertRaises(TypeError, F, 3, 0j)
        self.assertRaises(TypeError, F, 3, 1j)
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def testInit(self):
        self.assertEqual((0, 1), _components(F()))
        self.assertEqual((7, 1), _components(F(7)))
        self.assertEqual((7, 3), _components(F(F(7, 3))))

        self.assertEqual((-1, 1), _components(F(-1, 1)))
        self.assertEqual((-1, 1), _components(F(1, -1)))
        self.assertEqual((1, 1), _components(F(-2, -2)))
        self.assertEqual((1, 2), _components(F(5, 10)))
        self.assertEqual((7, 15), _components(F(7, 15)))
        self.assertEqual((10**23, 1), _components(F(10**23)))

        self.assertEqual((3, 77), _components(F(F(3, 7), 11)))
        self.assertEqual((-9, 5), _components(F(2, F(-10, 9))))
        self.assertEqual((2486, 2485), _components(F(F(22, 7), F(355, 113))))

        self.assertRaisesMessage(ZeroDivisionError, "Fraction(12, 0)",
                                 F, 12, 0)
        self.assertRaises(TypeError, F, 1.5 + 3j)

        self.assertRaises(TypeError, F, "3/2", 3)
        self.assertRaises(TypeError, F, 3, 0j)
        self.assertRaises(TypeError, F, 3, 1j)
项目:ml-utils    作者:LinxiFan    | 项目源码 | 文件源码
def ast_decorator_factory(ast_transformer, **kwargs):
    """
    https://greentreesnakes.readthedocs.io/en/latest/examples.html

    Args:
        ast_transformer: a class or object that extends DecoratorAST

    Returns:
        a decorator that performs magic on a function
    """
    @meta_wrap
    def _decorator(func, *, debug=0):
        return apply_ast_transform(func, ast_transformer, debug=debug, **kwargs)
    return _decorator


# ---------------- Fraction interpreter -----------------
项目:GeneticAlgorithmsWithPython    作者:handcraftsman    | 项目源码 | 文件源码
def test_3_unknowns(self):
        geneRange = [i for i in range(-5, 5) if i != 0]
        geneset = [i for i in set(
            Fraction(d, e)
            for d in geneRange
            for e in geneRange if e != 0)]

        def fnGenesToInputs(genes):
            return genes

        def e1(genes):
            x, y, z = genes
            return 6 * x - 2 * y + 8 * z - 20

        def e2(genes):
            x, y, z = genes
            return y + 8 * x * z + 1

        def e3(genes):
            x, y, z = genes
            return 2 * z * Fraction(6, x) \
                   + 3 * Fraction(y, 2) - 6

        equations = [e1, e2, e3]
        self.solve_unknowns(3, geneset, equations, fnGenesToInputs)
项目:GeneticAlgorithmsWithPython    作者:handcraftsman    | 项目源码 | 文件源码
def test_3_desconocidos(self):
        valores = [i for i in range(-5, 5) if i != 0]
        geneSet = [i for i in set(
            Fraction(d, e)
            for d in valores
            for e in valores if e != 0)]

        def fnGenesAEntradas(genes):
            return genes

        def e1(genes):
            x, y, z = genes
            return 6 * x - 2 * y + 8 * z - 20

        def e2(genes):
            x, y, z = genes
            return y + 8 * x * z + 1

        def e3(genes):
            x, y, z = genes
            return 2 * z * Fraction(6, x) \
                   + 3 * Fraction(y, 2) - 6

        ecuaciones = [e1, e2, e3]
        self.resolver_desconocidos(3, geneSet, ecuaciones, fnGenesAEntradas)
项目:performance    作者:python    | 项目源码 | 文件源码
def _applyActionSide1(state, act):
    me, them, extra = state

    if act == 'Super Potion':
        me = applyHPChange(me, 50)
        return {(me, them, extra): Fraction(1)}

    mdata = attack_data[act]
    aind = 3 if mdata.isspec else 0
    dind = 3 if mdata.isspec else 1
    pdiv = 64 if mdata.crit else 512
    dmg_dist = getCritDist(me.fixed.lvl, Fraction(me.fixed.basespeed, pdiv),
                           me.stats[aind], me.fixed.stats[aind], them.stats[
                               dind], them.fixed.stats[dind],
                           mdata.power, mdata.stab, mdata.te)

    dist = defaultdict(Fraction)
    for dmg, p in dmg_dist.items():
        them2 = applyHPChange(them, -dmg)
        dist[me, them2, extra] += p
    return dist
项目:performance    作者:python    | 项目源码 | 文件源码
def _getSuccessorsB(self, statep):
        st, state, action = statep
        dist = defaultdict(Fraction)
        for eact, p in [('Water Gun', Fraction(64, 130)),
                        ('Bubblebeam', Fraction(66, 130))]:
            priority1 = state[0].stats.speed + \
                10000 * (action == 'Super Potion')
            priority2 = state[1].stats.speed + 10000 * (action == 'X Defend')

            if priority1 > priority2:
                self._applyActionPair(state, 0, action, 1, eact, dist, p)
            elif priority1 < priority2:
                self._applyActionPair(state, 1, eact, 0, action, dist, p)
            else:
                self._applyActionPair(state, 0, action, 1, eact, dist, p / 2)
                self._applyActionPair(state, 1, eact, 0, action, dist, p / 2)

        return {k: float(p) for k, p in dist.items() if p > 0}
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def testInit(self):
        self.assertEqual((0, 1), _components(F()))
        self.assertEqual((7, 1), _components(F(7)))
        self.assertEqual((7, 3), _components(F(F(7, 3))))

        self.assertEqual((-1, 1), _components(F(-1, 1)))
        self.assertEqual((-1, 1), _components(F(1, -1)))
        self.assertEqual((1, 1), _components(F(-2, -2)))
        self.assertEqual((1, 2), _components(F(5, 10)))
        self.assertEqual((7, 15), _components(F(7, 15)))
        self.assertEqual((10**23, 1), _components(F(10**23)))

        self.assertEqual((3, 77), _components(F(F(3, 7), 11)))
        self.assertEqual((-9, 5), _components(F(2, F(-10, 9))))
        self.assertEqual((2486, 2485), _components(F(F(22, 7), F(355, 113))))

        self.assertRaisesMessage(ZeroDivisionError, "Fraction(12, 0)",
                                 F, 12, 0)
        self.assertRaises(TypeError, F, 1.5 + 3j)

        self.assertRaises(TypeError, F, "3/2", 3)
        self.assertRaises(TypeError, F, 3, 0j)
        self.assertRaises(TypeError, F, 3, 1j)
项目:NEAT_PyGenetics    作者:strangedev    | 项目源码 | 文件源码
def test_copyConstruct(self):
        s1 = StorageGenome()
        s1.inputs['uiae'] = 1
        s1.inputs['eaiu'] = 2
        s1.outputs['nrtd'] = 3
        s1.outputs['dtrn'] = 4
        s1.genes[2] = (True, float(Fraction(15, 11)))
        s1.genes[5] = (True, float(Fraction(135, 9)))
        s1.genes[12] = (True, float(Fraction(17, 81)))
        s1.analysis_result.topologically_sorted_nodes = [1, 5, 7, 2, 3, 8]
        s1.analysis_result.topologically_sorted_cycle_nodes = [3, 2, 8, 1]
        s1.analysis_result.gene_closes_cycle_map[5] = True
        s2 = StorageGenome(s1)

        self.assertNotEqual(s1, s2)
        self.assertNotEqual(s1._id, s2._id)
        self.assertDictEqual(s1.inputs, s2.inputs)
        self.assertDictEqual(s1.outputs, s2.outputs)
        self.assertDictEqual(s1.genes, s2.genes)
        self.assertEqual(s1.cluster, s2.cluster)
        self.assertEqual(s1.analysis_result, s2.analysis_result)
        self.assertNotEqual(s1.__repr__(), s2.__repr__())
项目:litesdcard    作者:lambdaconcept    | 项目源码 | 文件源码
def __init__(self, platform, clk_freq):
        self.clock_domains.cd_sys = ClockDomain()

        f0 = 32*1000000
        clk32 = platform.request("clk32")
        clk32a = Signal()
        self.specials += Instance("IBUFG", i_I=clk32, o_O=clk32a)
        clk32b = Signal()
        self.specials += Instance("BUFIO2", p_DIVIDE=1,
                                  p_DIVIDE_BYPASS="TRUE", p_I_INVERT="FALSE",
                                  i_I=clk32a, o_DIVCLK=clk32b)
        f = Fraction(int(clk_freq), int(f0))
        n, m, p = f.denominator, f.numerator, 16
        assert f0/n*m == clk_freq
        pll_lckd = Signal()
        pll_fb = Signal()
        pll = Signal(6)
        self.specials.pll = Instance("PLL_ADV", p_SIM_DEVICE="SPARTAN6",
                                     p_BANDWIDTH="OPTIMIZED", p_COMPENSATION="INTERNAL",
                                     p_REF_JITTER=.01, p_CLK_FEEDBACK="CLKFBOUT",
                                     i_DADDR=0, i_DCLK=0, i_DEN=0, i_DI=0, i_DWE=0, i_RST=0, i_REL=0,
                                     p_DIVCLK_DIVIDE=1, p_CLKFBOUT_MULT=m*p//n, p_CLKFBOUT_PHASE=0.,
                                     i_CLKIN1=clk32b, i_CLKIN2=0, i_CLKINSEL=1,
                                     p_CLKIN1_PERIOD=1000000000/f0, p_CLKIN2_PERIOD=0.,
                                     i_CLKFBIN=pll_fb, o_CLKFBOUT=pll_fb, o_LOCKED=pll_lckd,
                                     o_CLKOUT0=pll[0], p_CLKOUT0_DUTY_CYCLE=.5,
                                     o_CLKOUT1=pll[1], p_CLKOUT1_DUTY_CYCLE=.5,
                                     o_CLKOUT2=pll[2], p_CLKOUT2_DUTY_CYCLE=.5,
                                     o_CLKOUT3=pll[3], p_CLKOUT3_DUTY_CYCLE=.5,
                                     o_CLKOUT4=pll[4], p_CLKOUT4_DUTY_CYCLE=.5,
                                     o_CLKOUT5=pll[5], p_CLKOUT5_DUTY_CYCLE=.5,
                                     p_CLKOUT0_PHASE=0., p_CLKOUT0_DIVIDE=p//1, # sys
                                     p_CLKOUT1_PHASE=0., p_CLKOUT1_DIVIDE=p//1,
                                     p_CLKOUT2_PHASE=0., p_CLKOUT2_DIVIDE=p//1,
                                     p_CLKOUT3_PHASE=0., p_CLKOUT3_DIVIDE=p//1,
                                     p_CLKOUT4_PHASE=0., p_CLKOUT4_DIVIDE=p//1,
                                     p_CLKOUT5_PHASE=0., p_CLKOUT5_DIVIDE=p//1,
        )
        self.specials += Instance("BUFG", i_I=pll[0], o_O=self.cd_sys.clk)
        self.specials += AsyncResetSynchronizer(self.cd_sys, ~pll_lckd)
项目:py-openmath    作者:OpenMath    | 项目源码 | 文件源码
def test_rational(self):
        def to_om_rat(obj):
            return om.OMApplication(om.OMSymbol('rational', cd='nums1'),
                                    map(to_openmath, [obj.numerator, obj.denominator]))
        def to_py_rat(obj):
            return Fraction(to_python(obj.arguments[0]), to_python(obj.arguments[1]))
        register(Fraction, to_om_rat, 'nums1', 'rational', to_py_rat)

        a = Fraction(10, 12)
        self.assertEqual(a, to_python(to_openmath(a)))
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def __init__(self, value, denominator=1):
        """
        :param value: either an integer numerator, a
        float/rational/other number, or an IFDRational
        :param denominator: Optional integer denominator
        """
        self._denominator = denominator
        self._numerator = value
        self._val = float(1)

        if isinstance(value, Fraction):
            self._numerator = value.numerator
            self._denominator = value.denominator
            self._val = value

        if isinstance(value, IFDRational):
            self._denominator = value.denominator
            self._numerator = value.numerator
            self._val = value._val
            return

        if denominator == 0:
            self._val = float('nan')
            return

        elif denominator == 1:
            self._val = Fraction(value)
        else:
            self._val = Fraction(value, denominator)
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def fraction(self, terms=None):
        "Convert to a Fraction."

        if terms is None or terms >= len(self):
            terms = len(self) - 1

        frac = Fraction(1, self[terms])
        for t in reversed(self[1:terms]):
            frac = 1 / (frac + t)

        frac += self[0]
        return frac
项目:FPTuner    作者:soarlab    | 项目源码 | 文件源码
def addVar (self, ve): 
        assert(isinstance(ve, tft_expr.VariableExpr)) 
        if (ve.label().startswith(tft_expr.GROUP_ERR_VAR_PREFIX) or ve.label().startswith(tft_expr.ERR_VAR_PREFIX)): 
            assert(ve.type() == int) 
        if (ve in self.var_expr_2_gurobi_var.keys()): 
            return 

        # add variable 
        var = ""
        if (ve.type() == int): 
            var = self.solver.addVar(vtype=GRB.INTEGER, name=ve.label()) 
        elif (ve.type() == Fraction): 
            var = self.solver.addVar(name=ve.label())
        else: 
            sys.exit("ERROR: invalid type of VariableExpr found when asking gurobi for OptimizeExpr")             
        self.var_expr_2_gurobi_var[ve] = var 

        self.solver.update() 

        # write range 
        if (ve.hasBounds()): 
            # check lower bound 
            if (ve.lb().value() < Fraction(0, 1)): 
                sys.exit("ERROR: variable's (" + ve.label() +") lower bound must be greater than 0") 
            # add constraint 
            self.addConstraint("linear", "<=", ve.lb(), ve)
            self.addConstraint("linear", "<=", ve, ve.ub())
项目:FPTuner    作者:soarlab    | 项目源码 | 文件源码
def Eps2CtypeString (eps): 
    assert(isinstance(eps, Fraction)) 

    if (eps == tft_alloc.EPSILON_32): 
        return "float" 

    elif (eps == tft_alloc.EPSILON_64): 
        return "double" 

    elif (eps == tft_alloc.EPSILON_128): 
        return "__float128" 

    else: 
        sys.exit("Error: invalid bit-width: " + str(bw))
项目:FPTuner    作者:soarlab    | 项目源码 | 文件源码
def refVar (self): 
        return tft_expr.VariableExpr(self.refVarName(), Fraction, -1, False)
项目:FPTuner    作者:soarlab    | 项目源码 | 文件源码
def absexpr (self):
        if (self.stored_absexpr is not None): 
            return self.stored_absexpr 

        if (self.expr.hasLB() and self.expr.lb().value() >= Fraction(0, 1)): 
            self.stored_absexpr = self.expr 

        elif (isinstance(self.expr, tft_expr.UnaryExpr) and (self.expr.operator.label == "abs")): 
            self.stored_absexpr = self.expr 

        else: 
            self.stored_absexpr = IR.MakeUnaryExpr("abs", -1, self.expr, True)

        return self.stored_absexpr
项目:FPTuner    作者:soarlab    | 项目源码 | 文件源码
def scalingUpFactor (self):         
        if   (IR.PREC_CANDIDATES == ["e32", "e64"]): 
            return tft_expr.ConstantExpr(math.pow(2, 21))
        elif (IR.PREC_CANDIDATES == ["e64", "e128"]):
            return tft_expr.ConstantExpr(math.pow(2, 50))
        elif (IR.PREC_CANDIDATES == ["e32", "e64", "e128"]):
            return tft_expr.ConstantExpr(math.pow(2, 48))
        else: 
            sys.exit("Error: invalid setting of IR.PREC_CANDIDATES: " + str(IR.PREC_CANDIDATES))

        # scaling_eps = Fraction(0.0) 
        scaling_eps = Fraction(1.0) 

        for gid,epss in self.gid2epsilons.items(): 
            for eps in epss: 
                assert(eps.value() >= 0.0) 

                if (eps.value() == 0.0): 
                    continue 

#                if (scaling_eps < eps.value()): 
                if (scaling_eps > eps.value()): 
                    scaling_eps = eps.value() 

        up_fac = Fraction(scaling_eps.denominator, scaling_eps.numerator) 
        # return tft_expr.ConstantExpr(up_fac) 
        # return tft_expr.ConstantExpr(up_fac * 512.0) 
        return tft_expr.ConstantExpr(up_fac / 8.0 ) # It is just a heuristic to divide by 8.0
项目:FPTuner    作者:soarlab    | 项目源码 | 文件源码
def FreshErrorSumVar (): 
    global ID_ERROR_SUM 

    var_es = tft_expr.VariableExpr(tft_expr.ERR_SUM_PREFIX+str(ID_ERROR_SUM), Fraction, -1, False)
    ID_ERROR_SUM = ID_ERROR_SUM + 1 

    return var_es
项目:FPTuner    作者:soarlab    | 项目源码 | 文件源码
def rational_value (self): 
        if (self.type() == int): 
            return Fraction(self.value(), 1) 
        elif (self.type() == Fraction): 
            return self.value() 
        else: 
            sys.exit("ERROR: invalid value type for ConstantExpr")
项目:FPTuner    作者:soarlab    | 项目源码 | 文件源码
def __str__ (self): 
        if (self.type() == int): 
            return "([Const:int] " + str(self.value()) + ")"
        elif (self.type() == Fraction): 
            return "([Const:Fraction] " + str(float(self.value())) + ")"
        else: 
            sys.exit("ERROR: invalid type of ConstantExpr found in __str__")
项目:FPTuner    作者:soarlab    | 项目源码 | 文件源码
def __eq__ (self, rhs): 
        if (not isinstance(rhs, ConstantExpr)): 
            return False 
        if (self.type() == rhs.type()): 
            return (self.value() == rhs.value()) 
        elif (self.type() == int and rhs.type() == Fraction): 
            return (Fraction(self.value(), 1) == rhs.value())
        elif (self.type() == Fraction and rhs.type() == int): 
            return (self.value() == Fraction(rhs.value(), 1))
        else:
            sys.exit("ERROR: invlaid __eq__ scenario of ConstExpr")
项目:FPTuner    作者:soarlab    | 项目源码 | 文件源码
def __gt__ (self, rhs): 
        if (not isinstance(rhs, ConstantExpr)): 
            return False 
        if (self.type() == rhs.type()): 
            return (self.value() > rhs.value()) 
        elif (self.type() == int and rhs.type() == Fraction): 
            return (Fraction(self.value(), 1) > rhs.value())
        elif (self.type() == Fraction and rhs.type() == int): 
            return (self.value() > Fraction(rhs.value(), 1))
        else:
            sys.exit("ERROR: invlaid __gt__ scenario of ConstExpr")
项目:FPTuner    作者:soarlab    | 项目源码 | 文件源码
def __lt__ (self, rhs):
        if (not isinstance(rhs, ConstantExpr)): 
            return False 
        if (self.type() == rhs.type()): 
            return (self.value() < rhs.value()) 
        elif (self.type() == int and rhs.type() == Fraction): 
            return (Fraction(self.value(), 1) < rhs.value())
        elif (self.type() == Fraction and rhs.type() == int): 
            return (self.value() < Fraction(rhs.value(), 1))
        else:
            sys.exit("ERROR: invlaid __lt__ scenario of ConstExpr")
项目:FPTuner    作者:soarlab    | 项目源码 | 文件源码
def concEval (self, vmap = {}): 
        retv = self.value() 
        assert((type(retv) is int) or (type(retv) is float) or (isinstance(retv, Fraction))) 
        return retv
项目:FPTuner    作者:soarlab    | 项目源码 | 文件源码
def __init__ (self, label, vtype, gid, check_prefix=True): 
        assert(isinstance(label, str))
        assert(vtype == int or vtype == Fraction)
        assert(type(gid) is int) 

        if (sys.version_info.major == 2): 
            sys.exit("Error: FPTuner is currently based on Python3 only...") 
            super(VariableExpr, self).__init__() 
        elif (sys.version_info.major == 3):
            super().__init__() 
        else:
            sys.exit("ERROR: not supported python version: " + str(sys.version_info)) 

        if (gid == PRESERVED_CONST_GID): 
            assert(label.startswith(PRESERVED_CONST_VPREFIX)) 

        self.vtype       = vtype 
        self.operands.append(label) 
        self.gid         = gid 

        if (check_prefix): 
            if (self.isPreservedVar()): 
                print("ERROR: the given label \"" + label + "\" has a preserved prefix...")
                assert(False) 

        RegisterVariableExpr(self)
项目:FPTuner    作者:soarlab    | 项目源码 | 文件源码
def concEval (self, vmap = {}): 
        assert(self in vmap.keys()) 
        retv = vmap[self] 
        assert((type(retv) is int) or (type(retv) is float) or (isinstance(retv, Fraction))) 
        return retv
项目:FPTuner    作者:soarlab    | 项目源码 | 文件源码
def setLB (self, lb): 
        assert(isinstance(lb, ConstantExpr)) 
        if (self.operator.label in ["abs", "sqrt"]): 
            assert(lb.value() >= Fraction(0, 1))             
        self.lower_bound = lb
项目:FPTuner    作者:soarlab    | 项目源码 | 文件源码
def setUB (self, ub): 
        assert(isinstance(ub, ConstantExpr)) 
        if (self.operator.label in ["abs", "sqrt"]): 
            assert(ub.value() >= Fraction(0, 1)) 
        self.upper_bound = ub
项目:FPTuner    作者:soarlab    | 项目源码 | 文件源码
def EPS2HDLValue (eps): 
    assert(isinstance(eps, Fraction)) 
    try: 
        i = tft_alloc.EpsValues().index(eps) 
        return i 

    except ValueError: 
        sys.exit("ERROR: not supporting argument for EPS2FID: " + str(eps))
项目:FPTuner    作者:soarlab    | 项目源码 | 文件源码
def computeConstBinaryExpr (op, opd0, opd1): 
    assert(isinstance(op, EXPR.BinaryOp)) 
    assert(isinstance(opd0, EXPR.ConstantExpr)) 
    assert(isinstance(opd1, EXPR.ConstantExpr))

    v0 = opd0.value() 
    v1 = opd1.value() 

    assert((type(v0) is int) or (type(v0) is float) or isinstance(v0, Fraction)) 
    assert((type(v1) is int) or (type(v1) is float) or isinstance(v1, Fraction)) 

    if   (op.label == "+"): 
        return EXPR.ConstantExpr(v0 + v1) 
    elif (op.label == "-"): 
        return EXPR.ConstantExpr(v0 - v1) 
    elif (op.label == "*"): 
        return EXPR.ConstantExpr(v0 * v1) 
    elif (op.label == "/"):
        return EXPR.ConstantExpr(v0 / v1) 
    elif (op.label == "^"): 
        return EXPR.ConstantExpr(v0 ** v1) 
    else: 
        assert(False) 


# ========
# string to operator 
# ========