当前位置: 首页>>代码示例>>Python>>正文


Python numbers.Real方法代码示例

本文整理汇总了Python中numbers.Real方法的典型用法代码示例。如果您正苦于以下问题:Python numbers.Real方法的具体用法?Python numbers.Real怎么用?Python numbers.Real使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在numbers的用法示例。


在下文中一共展示了numbers.Real方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: set_dimension

# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Real [as 别名]
def set_dimension(self, vector_dim):
        """Sets the dimension `vector_dim` of the domain of the mechanism.

        This dimension relates to the size of the input vector of the function being considered by the mechanism.  This
        corresponds to the size of the random vector produced by the mechanism.

        Parameters
        ----------
        vector_dim : int
            Function input dimension.

        Returns
        -------
        self : class

        """
        if not isinstance(vector_dim, Real) or not np.isclose(vector_dim, int(vector_dim)):
            raise TypeError("d must be integer-valued")
        if not vector_dim >= 1:
            raise ValueError("d must be strictly positive")

        self._vector_dim = int(vector_dim)
        return self 
开发者ID:IBM,项目名称:differential-privacy-library,代码行数:25,代码来源:vector.py

示例2: check_inputs

# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Real [as 别名]
def check_inputs(self, value):
        super().check_inputs(value)

        if self._delta is None:
            raise ValueError("Delta must be set")

        if self._sensitivity is None:
            raise ValueError("Sensitivity must be set")

        if self._scale is None:
            self._scale = np.sqrt(2 * np.log(1.25 / self._delta)) * self._sensitivity / self._epsilon

        if not isinstance(value, Real):
            raise TypeError("Value to be randomised must be a number")

        return True 
开发者ID:IBM,项目名称:differential-privacy-library,代码行数:18,代码来源:gaussian.py

示例3: set_sensitivity

# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Real [as 别名]
def set_sensitivity(self, sensitivity):
        """Sets the sensitivity of the mechanism.

        Parameters
        ----------
        sensitivity : float
            The sensitivity of the mechanism.  Must satisfy `sensitivity` > 0.

        Returns
        -------
        self : class

        """
        if not isinstance(sensitivity, Real):
            raise TypeError("Sensitivity must be numeric")

        if sensitivity < 0:
            raise ValueError("Sensitivity must be non-negative")

        self._sensitivity = float(sensitivity)
        return self 
开发者ID:IBM,项目名称:differential-privacy-library,代码行数:23,代码来源:laplace.py

示例4: toNumpy

# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Real [as 别名]
def toNumpy(self):
            """Changes this field into a Numpy representation *in-place* (destructively replaces the old representation)."""

            if self.tpe == numbers.Real:
                self.data = numpy.array(self.data, dtype=numpy.dtype(float))
            elif self.tpe == basestring:
                unique = sorted(set(self.data))
                intToStr = dict(enumerate(unique))
                strToInt = dict((x, i) for i, x in enumerate(unique))
                converted = numpy.empty(len(self.data), dtype=numpy.dtype(int))
                for i, x in enumerate(self.data):
                    converted[i] = strToInt[x]
                self.intToStr = intToStr
                self.strToInt = strToInt
                self.data = converted
            return self 
开发者ID:modelop,项目名称:hadrian,代码行数:18,代码来源:cart.py

示例5: format_timestamp

# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Real [as 别名]
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) 
开发者ID:tao12345666333,项目名称:tornado-zh,代码行数:21,代码来源:httputil.py

示例6: _decimalize

# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Real [as 别名]
def _decimalize(v, q = None):
    # If already a decimal, just return itself
    if type(v) == Decimal:
        return v

    # If tuple/list passed, bulk-convert
    elif isinstance(v, (tuple, list)):
        return type(v)(decimalize(x, q) for x in v)

    # Convert int-like
    elif isinstance(v, numbers.Integral):
        return Decimal(int(v))

    # Convert float-like
    elif isinstance(v, numbers.Real):
        if q != None:
            return Decimal(repr(v)).quantize(Decimal(repr(q)),
                rounding=ROUND_HALF_UP)
        else:
            return Decimal(repr(v))
    else:
        raise ValueError("Cannot convert {0} to Decimal.".format(v)) 
开发者ID:jsvine,项目名称:pdfplumber,代码行数:24,代码来源:utils.py

示例7: ldexp

# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Real [as 别名]
def ldexp(cls, fraction, exponent):
        """Make an IBMFloat from fraction and exponent.

        The is the inverse function of IBMFloat.frexp()

        Args:
            fraction: A Real in the range -1.0 to 1.0.
            exponent: An integer in the range -256 to 255 inclusive.
        """
        if not (-1.0 <= fraction <= 1.0):
            raise ValueError("ldexp fraction {!r} out of range -1.0 to +1.0")

        if not (-256 <= exponent < 256):
            raise ValueError("ldexp exponent {!r} out of range -256 to 256")

        ieee = fraction * 2**exponent
        return IBMFloat.from_float(ieee) 
开发者ID:sixty-north,项目名称:segpy,代码行数:19,代码来源:ibm_float.py

示例8: is_float

# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Real [as 别名]
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)) 
开发者ID:tgsmith61591,项目名称:skutil,代码行数:21,代码来源:util.py

示例9: as_str_any

# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Real [as 别名]
def as_str_any(value):
  """Converts to `str` as `str(value)`, but use `as_str` for `bytes`.

  Args:
    value: A object that can be converted to `str`.

  Returns:
    A `str` object.
  """
  if isinstance(value, bytes):
    return as_str(value)
  else:
    return str(value)


# Numpy 1.8 scalars don't inherit from numbers.Integral in Python 3, so we
# need to check them specifically.  The same goes from Real and Complex. 
开发者ID:ryfeus,项目名称:lambda-packs,代码行数:19,代码来源:compat.py

示例10: __init__

# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Real [as 别名]
def __init__(
        self, deadline: float, callback: Callable[[], None], io_loop: IOLoop
    ) -> None:
        if not isinstance(deadline, numbers.Real):
            raise TypeError("Unsupported deadline %r" % deadline)
        self.deadline = deadline
        self.callback = callback
        self.tdeadline = (
            deadline,
            next(io_loop._timeout_counter),
        )  # type: Tuple[float, int]

    # 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__). 
开发者ID:opendevops-cn,项目名称:opendevops,代码行数:18,代码来源:ioloop.py

示例11: test_type_validation

# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Real [as 别名]
def test_type_validation(task):
    """Test type validating an entry.

    """
    validator = validators.Feval(types=numbers.Real)

    task.feval = '2*{Loop_val}'
    val, res, msg = validator.check(task, 'feval')
    assert val == 2
    assert res
    assert not msg

    task.feval = '2j*{Loop_val}'
    val, res, msg = validator.check(task, 'feval')
    assert val is None
    assert not res
    assert msg 
开发者ID:Exopy,项目名称:exopy,代码行数:19,代码来源:test_validators.py

示例12: get_learning_rate_policy_callback

# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Real [as 别名]
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']])
                         ) 
开发者ID:NervanaSystems,项目名称:ngraph-python,代码行数:24,代码来源:optimizer.py

示例13: set_gamma

# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Real [as 别名]
def set_gamma(self, gamma):
        r"""Sets the tuning parameter :math:`\gamma` for the mechanism.

        Must satisfy 0 <= `gamma` <= 1.  If not set, gamma defaults to minimise the expectation of the amplitude of
        noise,
        .. math:: \gamma = \frac{1}{1 + e^{\epsilon / 2}}

        Parameters
        ----------
        gamma : float
            Value of the tuning parameter gamma for the mechanism.

        Returns
        -------
        self : class

        Raises
        ------
        TypeError
            If `gamma` is not a float.

        ValueError
            If `gamma` is does not satisfy 0 <= `gamma` <= 1.

        """
        if not isinstance(gamma, Real):
            raise TypeError("Gamma must be numeric")
        if not 0.0 <= gamma <= 1.0:
            raise ValueError("Gamma must be in [0,1]")

        self._gamma = float(gamma)
        return self 
开发者ID:IBM,项目名称:differential-privacy-library,代码行数:34,代码来源:staircase.py

示例14: set_bounds

# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Real [as 别名]
def set_bounds(self, lower, upper):
        """Sets the lower and upper bounds of the mechanism.

        Must have lower <= upper.

        Parameters
        ----------
        lower : float
            The lower bound of the mechanism.

        upper : float
            The upper bound of the mechanism.

        Returns
        -------
        self : class

        """
        if not isinstance(lower, Real) or not isinstance(upper, Real):
            raise TypeError("Bounds must be numeric")

        if lower > upper:
            raise ValueError("Lower bound must not be greater than upper bound")

        self._lower_bound = float(lower)
        self._upper_bound = float(upper)

        return self 
开发者ID:IBM,项目名称:differential-privacy-library,代码行数:30,代码来源:base.py

示例15: set_sensitivity

# 需要导入模块: import numbers [as 别名]
# 或者: from numbers import Real [as 别名]
def set_sensitivity(self, sensitivity):
        if not isinstance(sensitivity, Real):
            raise TypeError("Sensitivity must be numeric")

        if sensitivity < 0:
            raise ValueError("Sensitivity must be non-negative")

        self._sensitivity = float(sensitivity)
        return self 
开发者ID:IBM,项目名称:differential-privacy-library,代码行数:11,代码来源:uniform.py


注:本文中的numbers.Real方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。