我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用numbers.Real()。
def generic_type_name(v): """Return a descriptive type name that isn't Python specific. For example, an int value will return 'integer' rather than 'int'.""" if isinstance(v, numbers.Integral): # Must come before real numbers check since integrals are reals too return 'integer' elif isinstance(v, numbers.Real): return 'float' elif isinstance(v, (tuple, list)): return 'list' elif isinstance(v, six.string_types): return 'string' elif v is None: return 'null' else: return type(v).__name__
def validate(self, val): if not isinstance(val, numbers.Real): raise ValidationError('expected real number, got %s' % generic_type_name(val)) if not isinstance(val, float): # This checks for the case where a number is passed in with a # magnitude larger than supported by float64. try: val = float(val) except OverflowError: raise ValidationError('too large for float') if math.isnan(val) or math.isinf(val): raise ValidationError('%f values are not supported' % val) if self.minimum is not None and val < self.minimum: raise ValidationError('%f is not greater than %f' % (val, self.minimum)) if self.maximum is not None and val > self.maximum: raise ValidationError('%f is not less than %f' % (val, self.maximum)) return val
def __setitem__(self, key, value): # Overridden to make sure dict is normalized. if not isinstance(value, Real) or value < 0 or value > 1: raise ValueError("Value must be a number between 0 and 1, unlike " + str(i)) try: r = (self[key] - value)/(1 - self[key]) # r is the fraction of the remaining probability mass that # we're going to give up (take). for k in filter(key.__ne__, self): dict.__setitem__(self, k, self[k] * (1 + r)) value = value if len(self) != 1 else 1 if value: dict.__setitem__(self, key, value) else: # This is the purging stage! dict.__delitem__(self, key) except ZeroDivisionError: # self[key] = 1, so key has all the probability mass. We'll leave it # as is, since there's no sensible way of reducing it. pass
def handle(self, conf): if type(self).strategy == StartupBot.strategy: yield _StartupBot.handle(self, conf) return import warnings warnings.warn( "Implementing custom startup bot relaunch strategies by implementing " + "strategy() has been deprecated.", DeprecationWarning ) for value in self.strategy(conf): if isinstance(value, numbers.Real): yield idiokit.sleep(value) else: yield self.launch(value)
def fill(self, datum, weight=1.0): self._checkForCrossReferences() if weight > 0.0: q = self.quantity(datum) if not isinstance(q, numbers.Real): raise TypeError("function return value ({0}) must be boolean or number".format(q)) if self.nan(q): self.nanflow.fill(datum, weight) else: b = self.bin(q) if b not in self.bins: self.bins[b] = self.value.copy() self.bins[b].fill(datum, weight) # no possibility of exception from here on out (for rollback) self.entries += weight
def is_float(x): """Determine whether some object ``x`` is a float type (float, np.float, etc). Parameters ---------- x : object The item to assess Returns ------- bool True if ``x`` is a float type """ return isinstance(x, (float, np.float)) or \ (not isinstance(x, (bool, np.bool)) and isinstance(x, numbers.Real))
def make_train_test(Y, ntest, seed = None): if type(Y) not in [sp.sparse.coo.coo_matrix, sp.sparse.csr.csr_matrix, sp.sparse.csc.csc_matrix]: raise ValueError("Unsupported Y type: %s" + type(Y)) if not isinstance(ntest, numbers.Real) or ntest < 0: raise ValueError("ntest has to be a non-negative number (number or ratio of test samples).") Y = Y.tocoo(copy = False) if ntest < 1: ntest = Y.nnz * ntest if seed is not None: np.random.seed(seed) ntest = int(round(ntest)) rperm = np.random.permutation(Y.nnz) train = rperm[ntest:] test = rperm[0:ntest] Ytrain = sp.sparse.coo_matrix( (Y.data[train], (Y.row[train], Y.col[train])), shape=Y.shape ) Ytest = sp.sparse.coo_matrix( (Y.data[test], (Y.row[test], Y.col[test])), shape=Y.shape ) return Ytrain, Ytest
def get_learning_rate_policy_callback(lr_params): if isinstance(lr_params, numbers.Real): # If argument is real number, set policy to fixed and use given value as base_lr lr_params = {'name': 'fixed', 'base_lr': lr_params} # Check if lr_params contains all required parameters for selected policy. if lr_params['name'] not in lrp.lr_policies: raise NotImplementedError("Learning rate policy {lr_name} not supported." "\nSupported policies are: {policies}".format( lr_name=lr_params['name'], policies=lrp.lr_policies.keys()) ) elif all([x in lr_params.keys() for x in lrp.lr_policies[lr_params['name']]['args']]): return lrp.lr_policies[lr_params['name']]['obj'](lr_params) else: raise ValueError("Too few arguments provided to create policy {lr_name}." "\nGiven: {lr_params}" "\nExpected: {lr_args}".format( lr_name=lr_params['name'], lr_params=lr_params.keys(), lr_args=lrp.lr_policies[lr_params['name']]) )
def __init__(self, amount=None, currency=DEFAULT_CURRENCY, amount_raw=None): if not (amount is None) ^ (amount_raw is None): raise ValueError("You must specify an amount or a raw amount") if not isinstance(currency, Currency): raise TypeError("You must specify a valid Currency") if amount is not None: if not isinstance(amount, numbers.Real): raise TypeError("Amount must be an integer or float") amount_raw = int(amount * 10**currency.precision) if not isinstance(amount_raw, numbers.Integral): raise TypeError("Amount must be an integer or float") self.amount_raw = amount_raw self.currency = currency
def test_get_types(self): tc = testClass('mnop') tc2 = testClass2('qrst') tc3 = testClass3() self.assertEqual(get_types(testfunc), (Tuple[int, Real, str], Tuple[int, Real])) self.assertEqual(get_types(testfunc2), (Tuple[int, Real, testClass], Tuple[int, float])) self.assertEqual(get_types(testfunc4), (Any, Any)) self.assertEqual(get_types(tc2.testmeth), (Tuple[int, Real], str)) self.assertEqual(get_types(testClass2.testmeth), (Tuple[int, Real], str)) self.assertEqual(get_types(tc3.testmeth), (Any, Any)) self.assertEqual(get_types(testClass3Base.testmeth), (Tuple[int, Real], Union[str, int])) self.assertEqual(get_types(tc.testmeth2), (Tuple[int, Real], str)) self.assertEqual(get_types(tc.testmeth_class), (Tuple[int, Real], str)) self.assertEqual(get_types(tc.testmeth_class2), (Tuple[int, Real], str)) self.assertEqual(get_types(tc.testmeth_static), (Tuple[int, Real], str)) self.assertEqual(get_types(tc.testmeth_static2), (Tuple[int, Real], str)) self.assertEqual(get_types(testfunc), (Tuple[int, Real, str], Tuple[int, Real]))
def test_get_types_py3(self): tc = py3.testClass('mnop') tc2 = py3.testClass2('qrst') tc3 = py3.testClass3() self.assertEqual(get_types(py3.testfunc), (Tuple[int, Real, str], Tuple[int, Real])) self.assertEqual(get_types(py3.testfunc2), (Tuple[int, Real, py3.testClass], Tuple[int, float])) self.assertEqual(get_types(tc2.testmeth), (Tuple[int, Real], str)) self.assertEqual(get_types(py3.testClass2.testmeth), (Tuple[int, Real], str)) self.assertEqual(get_types(tc3.testmeth), (Any, Any)) self.assertEqual(get_types(py3.testClass3Base.testmeth), (Tuple[int, Real], Union[str, int])) self.assertEqual(get_types(tc.testmeth2), (Tuple[int, Real], str)) self.assertEqual(get_types(tc.testmeth_class), (Tuple[int, Real], str)) self.assertEqual(get_types(tc.testmeth_class2), (Tuple[int, Real], str)) self.assertEqual(get_types(tc.testmeth_static), (Tuple[int, Real], str)) self.assertEqual(get_types(tc.testmeth_static2), (Tuple[int, Real], str)) self.assertEqual(get_types(py3.testfunc), (Tuple[int, Real, str], Tuple[int, Real]))
def __init__(self, min_value=None, max_value=None): """ A more restrictive minimum or maximum value can be specified than the range inherent to the defined type. """ if min_value is not None: assert isinstance(min_value, numbers.Real), \ 'min_value must be a real number' if not isinstance(min_value, float): try: min_value = float(min_value) except OverflowError: raise AssertionError('min_value is too small for a float') if self.minimum is not None and min_value < self.minimum: raise AssertionError('min_value cannot be less than the ' 'minimum value for this type (%f < %f)' % (min_value, self.minimum)) self.minimum = min_value if max_value is not None: assert isinstance(max_value, numbers.Real), \ 'max_value must be a real number' if not isinstance(max_value, float): try: max_value = float(max_value) except OverflowError: raise AssertionError('max_value is too large for a float') if self.maximum is not None and max_value > self.maximum: raise AssertionError('max_value cannot be greater than the ' 'maximum value for this type (%f < %f)' % (max_value, self.maximum)) self.maximum = max_value
def assert_trade_protocol(event): """Assert that an event meets the protocol for datasource TRADE outputs.""" assert_datasource_protocol(event) assert event.type == DATASOURCE_TYPE.TRADE assert isinstance(event.price, numbers.Real) assert isinstance(event.volume, numbers.Integral) assert isinstance(event.dt, datetime)
def _timedelta_to_seconds(td): """Convert a datetime.timedelta object into a seconds interval for rotating file ouput. :param td: datetime.timedelta :return: time in seconds :rtype: int """ if isinstance(td, numbers.Real): td = datetime.timedelta(seconds=td) return td.total_seconds()
def __mul__(self, other): """Multiply a Point with a constant. >>> 2 * Point(1,2) (2.000,4.000) >>> Point(1,2) * Point(1,2) #doctest:+IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TypeError: """ if not isinstance(other, numbers.Real): return NotImplemented return Point(self.x * other, self.y * other)
def __init__(self, arg): if isinstance(arg, numbers.Real): # We precompute sin and cos for rotations self.angle = arg self.cos = math.cos(self.angle) self.sin = math.sin(self.angle) elif isinstance(arg, Point): # Point angle is the trigonometric angle of the vector # [origin, Point] pt = arg try: self.cos = pt.x / pt.length() self.sin = pt.y / pt.length() except ZeroDivisionError: self.cos = 1 self.sin = 0 self.angle = math.acos(self.cos) if self.sin < 0: self.angle = -self.angle else: raise TypeError("Angle is defined by a number or a Point")
def __init__(self, items = None): """Create a dictionary from iters. If items can't be fed to a dictionary, it will be interpreted as a collection of keys, and each value will default to value 1/n. Otherwise, the values are normalized to sum to one. Raises ValueError if some values are not numbers or are negative. Arguments: - `items`: argument with which to make dictionary """ if items is None: return dict.__init__(self) try: # can fail if items is not iterable or not full of size 2 items: dict.__init__(self, items) except TypeError: try: # Let's assume items is a finite iterable full of keys vals = [1/len(items)] * len(items) except TypeError: # Apparently items has no length -- let's take it as the only # key and put all the probability on it. dict.__init__(self, (items, 1)) else: # if items has a length, it can be iterated through with zip dict.__init__(self, zip(items, vals)) else: # we've successfully made dic from key, value pairs in items, now let's # normalize the dictionary, and check the values for v in self.values(): if not isinstance(v, Real): raise TypeError("Values must be nonnegative real numbers so I " + "can properly normalize them. " + str(v) + " is not.") elif v < 0: raise ValueError("Values must be nonnegative, unlike " + str(v)) tot = sum(self.values()) for k, v in self.items(): self[k] = v/tot
def add_timeout(self, deadline, callback, *args, **kwargs): # This method could be simplified (since tornado 4.0) by # overriding call_at instead of add_timeout, but we leave it # for now as a test of backwards-compatibility. if isinstance(deadline, numbers.Real): delay = max(deadline - self.time(), 0) elif isinstance(deadline, datetime.timedelta): delay = timedelta_to_seconds(deadline) else: raise TypeError("Unsupported deadline %r") return self.reactor.callLater( delay, self._run_callback, functools.partial(wrap(callback), *args, **kwargs))
def format_timestamp(ts): """Formats a timestamp in the format used by HTTP. The argument may be a numeric timestamp as returned by `time.time`, a time tuple as returned by `time.gmtime`, or a `datetime.datetime` object. >>> format_timestamp(1359312200) 'Sun, 27 Jan 2013 18:43:20 GMT' """ if isinstance(ts, numbers.Real): pass elif isinstance(ts, (tuple, time.struct_time)): ts = calendar.timegm(ts) elif isinstance(ts, datetime.datetime): ts = calendar.timegm(ts.utctimetuple()) else: raise TypeError("unknown timestamp type: %r" % ts) return email.utils.formatdate(ts, usegmt=True)
def add_timeout(self, deadline, callback, *args, **kwargs): """Runs the ``callback`` at the time ``deadline`` from the I/O loop. Returns an opaque handle that may be passed to `remove_timeout` to cancel. ``deadline`` may be a number denoting a time (on the same scale as `IOLoop.time`, normally `time.time`), or a `datetime.timedelta` object for a deadline relative to the current time. Since Tornado 4.0, `call_later` is a more convenient alternative for the relative case since it does not require a timedelta object. Note that it is not safe to call `add_timeout` from other threads. Instead, you must use `add_callback` to transfer control to the `IOLoop`'s thread, and then call `add_timeout` from there. Subclasses of IOLoop must implement either `add_timeout` or `call_at`; the default implementations of each will call the other. `call_at` is usually easier to implement, but subclasses that wish to maintain compatibility with Tornado versions prior to 4.0 must use `add_timeout` instead. .. versionchanged:: 4.0 Now passes through ``*args`` and ``**kwargs`` to the callback. """ if isinstance(deadline, numbers.Real): return self.call_at(deadline, callback, *args, **kwargs) elif isinstance(deadline, datetime.timedelta): return self.call_at(self.time() + timedelta_to_seconds(deadline), callback, *args, **kwargs) else: raise TypeError("Unsupported deadline %r" % deadline)
def __init__(self, deadline, callback, io_loop): if not isinstance(deadline, numbers.Real): raise TypeError("Unsupported deadline %r" % deadline) self.deadline = deadline self.callback = callback self.tiebreaker = next(io_loop._timeout_counter) # Comparison methods to sort by deadline, with object id as a tiebreaker # to guarantee a consistent ordering. The heapq module uses __le__ # in python2.5, and __lt__ in 2.6+ (sort() and most other comparisons # use __lt__).
def ed(entries, contentType, binsAsDict=None, **bins): """Create a Categorize that is only capable of being added. Parameters: entries (float): the number of entries. contentType (str): the value's sub-aggregator type (must be provided to determine type for the case when `bins` is empty). bins (dict from str to :doc:`Container <histogrammar.defs.Container>`): the non-empty bin categories and their values. """ if not isinstance(entries, numbers.Real) and entries not in ("nan", "inf", "-inf"): raise TypeError("entries ({0}) must be a number".format(entries)) if not isinstance(contentType, basestring): raise TypeError("contentType ({0}) must be a string".format(contentType)) if not all(isinstance(k, basestring) and isinstance(v, Container) for k, v in bins.items()): raise TypeError("bins ({0}) must be a dict from strings to Containers".format(bins)) if entries < 0.0: raise ValueError("entries ({0}) cannot be negative".format(entries)) out = Categorize(None, None) out.entries = float(entries) if binsAsDict is None: out.bins = {} else: out.bins = binsAsDict out.bins.update(bins) out.contentType = contentType return out.specialize()
def fromJsonFragment(json, nameFromParent): if isinstance(json, dict) and hasKeys(json.keys(), ["entries", "bins:type", "bins"], ["name", "bins:name"]): if json["entries"] in ("nan", "inf", "-inf") or isinstance(json["entries"], numbers.Real): entries = float(json["entries"]) else: raise JsonFormatException(json, "Categorize.entries") if isinstance(json.get("name", None), basestring): name = json["name"] elif json.get("name", None) is None: name = None else: raise JsonFormatException(json["name"], "Categorize.name") if isinstance(json["bins:type"], basestring): contentType = json["bins:type"] factory = Factory.registered[contentType] else: raise JsonFormatException(json, "Categorize.bins:type") if isinstance(json.get("bins:name", None), basestring): dataName = json["bins:name"] elif json.get("bins:name", None) is None: dataName = None else: raise JsonFormatException(json["bins:name"], "Categorize.bins:name") if isinstance(json["bins"], dict): bins = dict((k, factory.fromJsonFragment(v, dataName)) for k, v in json["bins"].items()) else: raise JsonFormatException(json, "Categorize.bins") out = Categorize.ed(entries, contentType, **bins) out.quantity.name = nameFromParent if name is None else name return out.specialize() else: raise JsonFormatException(json, "Categorize")
def ed(binWidth, entries, contentType, bins, nanflow, origin): """Create a SparselyBin that is only capable of being added. Parameters: binWidth (float): the width of a bin. entries (float): the number of entries. contentType (str): the value's sub-aggregator type (must be provided to determine type for the case when `bins` is empty). bins (dict from int to :doc:`Container <histogrammar.defs.Container>`): the non-empty bin indexes and their values. nanflow (:doc:`Container <histogrammar.defs.Container>`): the filled nanflow bin. origin (float): the left edge of the bin whose index is zero. """ if not isinstance(binWidth, numbers.Real): raise TypeError("binWidth ({0}) must be a number".format(binWidth)) if not isinstance(entries, numbers.Real) and entries not in ("nan", "inf", "-inf"): raise TypeError("entries ({0}) must be a number".format(entries)) if not isinstance(contentType, basestring): raise TypeError("contentType ({0}) must be a string".format(contentType)) if not isinstance(bins, dict) or not all(isinstance(k, (int, long)) and isinstance(v, Container) for k, v in bins.items()): raise TypeError("bins ({0}) must be a map from 64-bit integers to Containers".format(bins)) if not isinstance(nanflow, Container): raise TypeError("nanflow ({0}) must be a Container".format(nanflow)) if not isinstance(origin, numbers.Real): raise TypeError("origin ({0}) must be a number".format(origin)) if entries < 0.0: raise ValueError("entries ({0}) cannot be negative".format(entries)) if binWidth <= 0.0: raise ValueError("binWidth ({0}) must be greater than zero".format(binWidth)) out = SparselyBin(binWidth, None, None, nanflow, origin) out.entries = float(entries) out.contentType = contentType out.bins = bins return out.specialize()
def __init__(self, binWidth, quantity, value=Count(), nanflow=Count(), origin=0.0): """Create a SparselyBin that is capable of being filled and added. Parameters: binWidth (float): the width of a bin; must be strictly greater than zero. quantity (function returning float): computes the quantity of interest from the data. value (:doc:`Container <histogrammar.defs.Container>`): generates sub-aggregators to put in each bin. nanflow (:doc:`Container <histogrammar.defs.Container>`): a sub-aggregator to use for data whose quantity is NaN. origin (float): the left edge of the bin whose index is 0. Other parameters: entries (float): the number of entries, initially 0.0. bins (dict from int to :doc:`Container <histogrammar.defs.Container>`): the map, probably a hashmap, to fill with values when their `entries` become non-zero. """ if not isinstance(binWidth, numbers.Real): raise TypeError("binWidth ({0}) must be a number".format(binWidth)) if value is not None and not isinstance(value, Container): raise TypeError("value ({0}) must be a Container".format(value)) if not isinstance(nanflow, Container): raise TypeError("nanflow ({0}) must be a Container".format(nanflow)) if not isinstance(origin, numbers.Real): raise TypeError("origin ({0}) must be a number".format(origin)) if binWidth <= 0.0: raise ValueError("binWidth ({0}) must be greater than zero".format(binWidth)) self.binWidth = binWidth self.entries = 0.0 self.quantity = serializable(quantity) self.value = value if value is not None: self.contentType = value.name self.bins = {} self.nanflow = nanflow.copy() self.origin = origin super(SparselyBin, self).__init__() self.specialize()
def test_floats(self): for t in sctypes['float']: assert_(isinstance(t(), numbers.Real), "{0} is not instance of Real".format(t.__name__)) assert_(issubclass(t, numbers.Real), "{0} is not subclass of Real".format(t.__name__)) assert_(not isinstance(t(), numbers.Rational), "{0} is instance of Rational".format(t.__name__)) assert_(not issubclass(t, numbers.Rational), "{0} is subclass of Rational".format(t.__name__))
def test_complex(self): for t in sctypes['complex']: assert_(isinstance(t(), numbers.Complex), "{0} is not instance of Complex".format(t.__name__)) assert_(issubclass(t, numbers.Complex), "{0} is not subclass of Complex".format(t.__name__)) assert_(not isinstance(t(), numbers.Real), "{0} is instance of Real".format(t.__name__)) assert_(not issubclass(t, numbers.Real), "{0} is subclass of Real".format(t.__name__))
def real_check(*args): from numbers import Real func = inspect.stack()[2][3] for var in args: if not isinstance(var, Real): raise RealError('Function %s expected real number, %s got instead.' % (func, type(var).__name__))
def _operator_fallbacks(monomorphic_operator, fallback_operator): def forward(a, b): if isinstance(b, (jsint, Fraction)): return monomorphic_operator(a, b) elif isinstance(b, float): return fallback_operator(float(a), b) elif isinstance(b, complex): return fallback_operator(complex(a), b) else: return NotImplemented forward.__name__ = '__' + fallback_operator.__name__ + '__' forward.__doc__ = monomorphic_operator.__doc__ def reverse(b, a): if isinstance(a, numbers.Rational): # Includes ints. return monomorphic_operator(a, b) elif isinstance(a, numbers.Real): return fallback_operator(float(a), float(b)) elif isinstance(a, numbers.Complex): return fallback_operator(complex(a), complex(b)) else: return NotImplemented reverse.__name__ = '__r' + fallback_operator.__name__ + '__' reverse.__doc__ = monomorphic_operator.__doc__ return forward, reverse
def test_timer(self): with timer() as t: j = 1 for i in range(1000): j *= i self.assertTrue( isinstance( t, timer ) ) self.assertTrue( isinstance( t.start_time, numbers.Real ) ) self.assertTrue( isinstance( t.end_time, numbers.Real ) ) self.assertEqual( t.time_taken, t.end_time - t.start_time )
def sqrt(x: Real) -> Real: """ Return the square root of a positive number. """ return _math.sqrt(x)
def exp(x: Real) -> Real: """ Return the exponential of a number. """ return _math.exp(x)
def log(x: Real) -> Real: """ Return the natural logarithm of x. Aliases: log | ln """ return _math.log(x)
def log10(x: Real) -> Real: """ Return the logarithm of x in base 10. """ return _math.log10(x)
def log2(x: Real) -> Real: """ Return the logarithm of x in base 2. """ return _math.log2(x)