Python math.isfinite() Examples

The following are code examples for showing how to use math.isfinite(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: tartiflette   Author: tartiflette   File: float.py    MIT License 7 votes vote down vote up
def coerce_output(self, value: Any) -> float:
        """
        Coerce the resolved value for output.
        :param value: value to coerce
        :type value: Any
        :return: the coerced value
        :rtype: float
        """
        # pylint: disable=no-self-use
        try:
            result = value
            if value and isinstance(value, str):
                result = float(value)

            if not isfinite(result):
                raise ValueError

            return result if isinstance(result, float) else float(result)
        except Exception:  # pylint: disable=broad-except
            pass

        raise TypeError(
            f"Float cannot represent non numeric value: < {value} >."
        ) 
Example 2
Project: tartiflette   Author: tartiflette   File: float.py    MIT License 7 votes vote down vote up
def coerce_input(self, value: Any) -> float:
        """
        Coerce the user input from variable value.
        :param value: value to coerce
        :type value: Any
        :return: the coerced value
        :rtype: float
        """
        # pylint: disable=no-self-use
        # ¯\_(ツ)_/¯ booleans are int: `assert isinstance(True, int) is True`
        try:
            if not isinstance(value, bool) and isfinite(value):
                return float(value)
        except Exception:  # pylint: disable=broad-except
            pass
        raise TypeError(
            f"Float cannot represent non numeric value: < {value} >."
        ) 
Example 3
Project: backend.ai-agent   Author: lablup   File: kernel.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, kernel_id, *,
                 exec_timeout: float = 0,
                 client_features: FrozenSet[str] = None) -> None:
        self.started_at = time.monotonic()
        self.finished_at = None
        if not math.isfinite(exec_timeout) or exec_timeout < 0:
            raise ValueError('execution timeout must be a zero or finite positive number.')
        self.exec_timeout = exec_timeout
        self.max_record_size = 10 * (2 ** 20)  # 10 MBytes
        self.client_features = client_features or frozenset()
        self.zctx = zmq.asyncio.Context()
        self.input_sock = self.zctx.socket(zmq.PUSH)
        self.output_sock = self.zctx.socket(zmq.PULL)
        self.completion_queue = asyncio.Queue(maxsize=128)
        self.service_queue = asyncio.Queue(maxsize=128)
        self.service_apps_info_queue = asyncio.Queue(maxsize=128)
        self.status_queue = asyncio.Queue(maxsize=128)
        self.output_queue = None
        self.pending_queues = OrderedDict()
        self.current_run_id = None 
Example 4
Project: tartiflette   Author: tartiflette   File: boolean.py    MIT License 6 votes vote down vote up
def coerce_output(self, value: Any) -> bool:
        """
        Coerce the resolved value for output.
        :param value: value to coerce
        :type value: Any
        :return: the coerced value
        :rtype: bool
        """
        # pylint: disable=no-self-use
        if isinstance(value, bool):
            return value

        try:
            if isfinite(value):
                return bool(value)
        except Exception:  # pylint: disable=broad-except
            pass
        raise TypeError(
            f"Boolean cannot represent a non boolean value: < {value} >."
        ) 
Example 5
Project: suomi-core   Author: suomichain   File: poet_settings_view.py    Apache License 2.0 6 votes vote down vote up
def initial_wait_time(self):
        """Return the initial wait time if config setting exists and is valid,
        otherwise return the default.

        The initial wait time is used during the bootstrapping of the block-
        chain to compute the local mean for wait timers until there are at
        least population_estimate_sample_size PoET blocks in the blockchain.
        """
        if self._initial_wait_time is None:
            self._initial_wait_time = \
                self._get_config_setting(
                    name='suomi.poet.initial_wait_time',
                    value_type=float,
                    default_value=PoetSettingsView._INITIAL_WAIT_TIME_,
                    validate_function=lambda value:
                        math.isfinite(value) and value >= 0)

        return self._initial_wait_time 
Example 6
Project: suomi-core   Author: suomichain   File: poet_settings_view.py    Apache License 2.0 6 votes vote down vote up
def target_wait_time(self):
        """Return the target wait time if config setting exists and is valid,
        otherwise return the default.

        The target wait time is the desired average amount of time, across all
        validators in the network, a validator must wait before attempting to
        claim a block.
        """
        if self._target_wait_time is None:
            self._target_wait_time = \
                self._get_config_setting(
                    name='suomi.poet.target_wait_time',
                    value_type=float,
                    default_value=PoetSettingsView._TARGET_WAIT_TIME_,
                    validate_function=lambda value:
                        math.isfinite(value) and value > 0)

        return self._target_wait_time 
Example 7
Project: rule-engine   Author: zeroSteiner   File: ast.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def is_real_number(value):
	"""
	Check whether *value* is a real number (i.e. capable of being represented as
	a floating point value without loss of information as well as being finite).
	Despite being able to be represented as a float, ``NaN`` is not considered a
	real number for the purposes of this function.

	:param value: The value to check. This value is a native Python type.
	:return: Whether or not the value is a natural number.
	:rtype: bool
	"""
	if not is_numeric(value):
		return False
	if not math.isfinite(value):
		return False
	return True 
Example 8
Project: sawtooth-poet   Author: hyperledger   File: poet_settings_view.py    Apache License 2.0 6 votes vote down vote up
def initial_wait_time(self):
        """Return the initial wait time if config setting exists and is valid,
        otherwise return the default.

        The initial wait time is used during the bootstrapping of the block-
        chain to compute the local mean for wait timers until there are at
        least population_estimate_sample_size PoET blocks in the blockchain.
        """
        if self._initial_wait_time is None:
            self._initial_wait_time = \
                self._get_config_setting(
                    name='sawtooth.poet.initial_wait_time',
                    value_type=float,
                    default_value=PoetSettingsView._INITIAL_WAIT_TIME_,
                    validate_function=lambda value:
                        math.isfinite(value) and value >= 0)

        return self._initial_wait_time 
Example 9
Project: sawtooth-poet   Author: hyperledger   File: poet_settings_view.py    Apache License 2.0 6 votes vote down vote up
def target_wait_time(self):
        """Return the target wait time if config setting exists and is valid,
        otherwise return the default.

        The target wait time is the desired average amount of time, across all
        validators in the network, a validator must wait before attempting to
        claim a block.
        """
        if self._target_wait_time is None:
            self._target_wait_time = \
                self._get_config_setting(
                    name='sawtooth.poet.target_wait_time',
                    value_type=float,
                    default_value=PoetSettingsView._TARGET_WAIT_TIME_,
                    validate_function=lambda value:
                        math.isfinite(value) and value > 0)

        return self._target_wait_time 
Example 10
Project: bfx-hf-indicators-py   Author: bitfinexcom   File: chaikin_oscillator.py    Apache License 2.0 6 votes vote down vote up
def update(self, candle):
    self._adl.update(candle)
    adl = self._adl.v()

    if not isfinite(adl):
      return
    
    self._shortEMA.update(adl)
    self._longEMA.update(adl)

    short = self._shortEMA.v()
    long = self._longEMA.v()

    if (isfinite(short) and isfinite(long)):
      super().update(short - long)

    return self.v() 
Example 11
Project: bfx-hf-indicators-py   Author: bitfinexcom   File: chaikin_oscillator.py    Apache License 2.0 6 votes vote down vote up
def add(self, candle):
    self._adl.add(candle)
    adl = self._adl.v()

    if not isfinite(adl):
      return
    
    self._shortEMA.add(adl)
    self._longEMA.add(adl)

    short = self._shortEMA.v()
    long = self._longEMA.v()

    if (isfinite(short) and isfinite(long)):
      super().add(short - long)

    return self.v() 
Example 12
Project: bfx-hf-indicators-py   Author: bitfinexcom   File: acceleration.py    Apache License 2.0 6 votes vote down vote up
def add(self, v):
    self._roc.add(v)
    roc = self._roc.v()

    if not isfinite(roc):
      return

    if len(self._buffer) == self._p:
      super().add(roc - self._buffer[0])

    self._buffer.append(roc)

    if len(self._buffer) > self._p:
      del self._buffer[0]

    return self.v() 
Example 13
Project: bfx-hf-indicators-py   Author: bitfinexcom   File: macd.py    Apache License 2.0 6 votes vote down vote up
def add(self, v):
    slowEMA = self._slowEMA.add(v)
    fastEMA = self._fastEMA.add(v)

    if not isfinite(slowEMA) or not isfinite(fastEMA):
      return

    macd = fastEMA - slowEMA
    signalEMA = self._signalEMA.add(macd)

    if not isfinite(signalEMA):
      return

    histogram = macd - signalEMA

    super().add({
      'macd': macd,
      'signal': signalEMA,
      'histogram': histogram
    })

    return self.v() 
Example 14
Project: bfx-hf-indicators-py   Author: bitfinexcom   File: relative_volatility_index.py    Apache License 2.0 6 votes vote down vote up
def update(self, v):
    if self._prevInputValue == None:
      return self.v()

    self._stddev.update(v)
    stddev = self._stddev.v()

    if not isfinite(stddev):
      return self.v()
    
    [u, d] = RVI.ud(v, self._prevInputValue, stddev)

    self._uEMA.update(u)
    self._dEMA.update(d)

    uSum = self._uEMA.v()
    dSum = self._dEMA.v()

    if uSum == dSum:
      return super().update(0)
    else:
      return super().update(100 * (uSum / (uSum + dSum))) 
Example 15
Project: Neuraxle   Author: Neuraxio   File: distributions.py    Apache License 2.0 6 votes vote down vote up
def rvs(self) -> float:
        """
        Will return a float value in the specified range as specified at creation.

        :return: a float.
        """
        if self.hard_clip_min is None and self.hard_clip_max is None:
            result = float(np.random.normal(self.mean, self.std))
        else:
            a = -np.inf
            b = np.inf

            if self.hard_clip_min is not None:
                a = (self.hard_clip_min - self.mean) / self.std

            if self.hard_clip_max is not None:
                b = (self.hard_clip_max - self.mean) / self.std

            result = truncnorm.rvs(a=a, b=b, loc=self.mean, scale=self.std)

        if not math.isfinite(result):
            return self.rvs()
        return float(result) 
Example 16
Project: Neuraxle   Author: Neuraxio   File: distributions.py    Apache License 2.0 6 votes vote down vote up
def rvs(self) -> float:
        """
        Will return a float value in the specified range as specified at creation.
        Note: the range at creation was in log space. The return value is after taking an exponent.

        :return: a float.
        """
        if self.hard_clip_min is None and self.hard_clip_max is None:
            result = 2 ** float(np.random.normal(self.log2_space_mean, self.log2_space_std))
        else:
            a = -np.inf
            b = np.inf

            if self.hard_clip_min is not None:
                a = (math.log2(self.hard_clip_min) - self.log2_space_mean) / self.log2_space_std

            if self.hard_clip_max is not None:
                b = (math.log2(self.hard_clip_max) - self.log2_space_mean) / self.log2_space_std

            result = 2 ** float(truncnorm.rvs(a=a, b=b, loc=self.log2_space_mean, scale=self.log2_space_std))

        if not math.isfinite(result):
            return self.rvs()

        return float(result) 
Example 17
Project: online-judge-tools   Author: kmyk   File: test.py    MIT License 6 votes vote down vote up
def compare_as_floats(xs_: str, ys_: str, error: float) -> bool:
    def f(x):
        try:
            y = float(x)
            if not math.isfinite(y):
                log.warning('not an real number found: %f', y)
            return y
        except ValueError:
            return x

    xs = list(map(f, xs_.split()))
    ys = list(map(f, ys_.split()))
    if len(xs) != len(ys):
        return False
    for x, y in zip(xs, ys):
        if isinstance(x, float) and isinstance(y, float):
            if not math.isclose(x, y, rel_tol=error, abs_tol=error):
                return False
        else:
            if x != y:
                return False
    return True 
Example 18
Project: InsightAgent   Author: insightfinder   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def _exact_ratio(x):
    u"""Convert Real number x exactly to (numerator, denominator) pair.

    >>> _exact_ratio(0.25)
    (1, 4)

    x is expected to be an int, Fraction, Decimal or float.
    """
    try:
        try:
            # int, Fraction
            return (x.numerator, x.denominator)
        except AttributeError:
            # float
            try:
                return x.as_integer_ratio()
            except AttributeError:
                # Decimal
                try:
                    return _decimal_to_ratio(x)
                except AttributeError:
                    msg = u"can't convert type '{}' to numerator/denominator"
                    raise TypeError(msg.format(type(x).__name__))
    except (OverflowError, ValueError):
        # INF or NAN
        if __debug__:
            # Decimal signalling NANs cannot be converted to float :-(
            if isinstance(x, Decimal):
                assert not x.is_finite()
            else:
                assert not math.isfinite(x)
        return (x, None)


# FIXME This is faster than Fraction.from_decimal, but still too slow. 
Example 19
Project: TGC-Designer-Tools   Author: chadrockey   File: GeoPointCloud.py    Apache License 2.0 5 votes vote down vote up
def addFromImage(self, image, image_scale, latlon_origin, proj):
        # Insert points
        X = []
        Y = []
        Z = []
        I = []
        C = []

        for row in range(0, image.shape[0]):
            for column in range(0, image.shape[1]):
                z = image[row, column]
                if math.isfinite(z):
                    x, y = self.cv2ToENU(row, column, image_scale)
                    X.append(x)
                    Y.append(y)
                    Z.append(z)
                    I.append(0.0)
                    C.append(0.0)

        self.addDataSet(X, Y, Z, I, C)

        # Need to store the lowest coordinates in case we cropped the image by not inserting invalid pixels
        # These will become zero when removeBias() is called and helps center large or offset courses to fit
        # Within the 2k square
        west_most_point = numpy.min(self.point_matrix[:,0]) # Offset from 0.0 left edge to west most point
        south_most_point = numpy.min(self.point_matrix[:,1]) # Offset from 0.0 bottom edge to south most point

        # Calculate the origin of these points
        self._proj = proj
        uncropped_origin = self.latlonToProj(latlon_origin[0], latlon_origin[1])
        # Move the original origin up to the new left/bottom point
        self._origin = (uncropped_origin[0] + west_most_point, uncropped_origin[1] + south_most_point)

        # Clear properties
        self.removeBias()
        self.resetProperties() 
Example 20
Project: RouteOptimization   Author: andre-le   File: compat.py    MIT License 5 votes vote down vote up
def isfinite(x):
        return not isinf(x) and not isnan(x) 
Example 21
Project: NiujiaoDebugger   Author: MrSrc   File: statistics.py    GNU General Public License v3.0 5 votes vote down vote up
def _isfinite(x):
    try:
        return x.is_finite()  # Likely a Decimal.
    except AttributeError:
        return math.isfinite(x)  # Coerces to float first. 
Example 22
Project: NiujiaoDebugger   Author: MrSrc   File: test_math.py    GNU General Public License v3.0 5 votes vote down vote up
def testIsfinite(self):
        self.assertTrue(math.isfinite(0.0))
        self.assertTrue(math.isfinite(-0.0))
        self.assertTrue(math.isfinite(1.0))
        self.assertTrue(math.isfinite(-1.0))
        self.assertFalse(math.isfinite(float("nan")))
        self.assertFalse(math.isfinite(float("inf")))
        self.assertFalse(math.isfinite(float("-inf"))) 
Example 23
Project: NiujiaoDebugger   Author: MrSrc   File: test_cmath.py    GNU General Public License v3.0 5 votes vote down vote up
def test_isfinite(self):
        real_vals = [float('-inf'), -2.3, -0.0,
                     0.0, 2.3, float('inf'), float('nan')]
        for x in real_vals:
            for y in real_vals:
                z = complex(x, y)
                self.assertEqual(cmath.isfinite(z),
                                  math.isfinite(x) and math.isfinite(y)) 
Example 24
Project: MetroloPy   Author: nrc-cnrc   File: nummy.py    GNU General Public License v3.0 5 votes vote down vote up
def _set_correlation_matrix(gummys, matrix):
        super(nummy,nummy)._set_correlation_matrix(gummys,matrix)
        cov = nummy.covariance_matrix(gummys)
        mean = [g.x for g in gummys]
        if isfinite(gummys[0].dof) and all([g.dof==gummys[0].dof for g in gummys]):
            mvdist = MultiTDist(mean,cov,gummys[0].dof)
        else:
            mvdist = MultiNormalDist(mean,cov)
        for i,g in enumerate(gummys):
            g._dist = mvdist[i] 
Example 25
Project: MetroloPy   Author: nrc-cnrc   File: nummy.py    GNU General Public License v3.0 5 votes vote down vote up
def _set_covariance_matrix(gummys, matrix):
        super(nummy,nummy)._set_covariance_matrix(gummys,matrix)
        mean = [g.x for g in gummys]
        if isfinite(gummys[0].dof) and all([g.dof==gummys[0].dof for g in gummys]):
            mvdist = MultiTDist(mean,matrix,gummys[0].dof)
        else:
            mvdist = MultiNormalDist(mean,matrix)
        for i,g in enumerate(gummys):
            g._dist = mvdist[i] 
Example 26
Project: hypothesis-couchdb   Author: kxepal   File: json.py    Apache License 2.0 5 votes vote down vote up
def numbers(min_value=None, max_value=None):
    """Generates instances of ``int`` and ``float`` types, except special
    values like ``inf`` and `NaN`.

    `min_value` and `max_value` arguments are applied to both
    ``hypothesis.strategies.integers`` and ``hypothesis.strategies.floats``
     strategies which are used under hood.
    """
    min_value_int = int(min_value) if min_value is not None else None
    max_value_int = int(max_value) if max_value is not None else None
    integers = st.integers(min_value=min_value_int, max_value=max_value_int)
    floats = st.floats(min_value=min_value, max_value=max_value)
    return integers | floats.filter(math.isfinite) 
Example 27
Project: python-pytest-cases   Author: smarie   File: example_code.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def isfinite(x):
        """
        isfinite(x) -> bool

        Return True if x is neither an infinity nor a NaN, and False otherwise.
        """
        return not (isinf(x) or isnan(x)) 
Example 28
Project: python-pytest-cases   Author: smarie   File: example_code.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def super_function_i_want_to_test(a, b):
    """
    An example function to be tested
    :param a:
    :param b:
    :return:
    """
    if not isfinite(a):
        raise InfiniteInput('a')
    if not isfinite(b):
        raise InfiniteInput('b')

    return a + 1, b + 1 
Example 29
Project: python-pytest-cases   Author: smarie   File: example_code.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def super_function_i_want_to_test2(a, b):
    """
    An example function to be tested
    :param a:
    :param b:
    :return:
    """
    if not isfinite(a):
        raise InfiniteInput('a')
    if not isfinite(b):
        raise InfiniteInput('b')

    return a + 1, b + 1 
Example 30
Project: banruo   Author: yingshang   File: fields.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def validate(self, value):
        super().validate(value)
        if value in self.empty_values:
            return
        if not math.isfinite(value):
            raise ValidationError(self.error_messages['invalid'], code='invalid') 
Example 31
Project: suomi-core   Author: suomichain   File: poet_settings_view.py    Apache License 2.0 5 votes vote down vote up
def ztest_maximum_win_deviation(self):
        """Return the zTest maximum win deviation if config setting exists and
        is valid, otherwise return the default.

        The zTest maximum win deviation specifies the maximum allowed
        deviation from the expected win frequency for a particular validator
        before the zTest will fail and the claimed block will be rejected.
        The deviation corresponds to a confidence interval (i.e., how
        confident we are that we have truly detected a validator winning at
        a frequency we consider too frequent):

        3.075 ==> 99.9%
        2.575 ==> 99.5%
        2.321 ==> 99%
        1.645 ==> 95%
        """
        if self._ztest_maximum_win_deviation is None:
            self._ztest_maximum_win_deviation = \
                self._get_config_setting(
                    name='suomi.poet.ztest_maximum_win_deviation',
                    value_type=float,
                    default_value=PoetSettingsView.
                    _ZTEST_MAXIMUM_WIN_DEVIATION_,
                    validate_function=lambda value:
                        math.isfinite(value) and value > 0)

        return self._ztest_maximum_win_deviation 
Example 32
Project: Blockly-rduino-communication   Author: technologiescollege   File: statistics.py    GNU General Public License v3.0 5 votes vote down vote up
def _isfinite(x):
    try:
        return x.is_finite()  # Likely a Decimal.
    except AttributeError:
        return math.isfinite(x)  # Coerces to float first. 
Example 33
Project: Blockly-rduino-communication   Author: technologiescollege   File: statistics.py    GNU General Public License v3.0 5 votes vote down vote up
def _exact_ratio(x):
    """Return Real number x to exact (numerator, denominator) pair.

    >>> _exact_ratio(0.25)
    (1, 4)

    x is expected to be an int, Fraction, Decimal or float.
    """
    try:
        # Optimise the common case of floats. We expect that the most often
        # used numeric type will be builtin floats, so try to make this as
        # fast as possible.
        if type(x) is float:
            return x.as_integer_ratio()
        try:
            # x may be an int, Fraction, or Integral ABC.
            return (x.numerator, x.denominator)
        except AttributeError:
            try:
                # x may be a float subclass.
                return x.as_integer_ratio()
            except AttributeError:
                try:
                    # x may be a Decimal.
                    return _decimal_to_ratio(x)
                except AttributeError:
                    # Just give up?
                    pass
    except (OverflowError, ValueError):
        # float NAN or INF.
        assert not math.isfinite(x)
        return (x, None)
    msg = "can't convert type '{}' to numerator/denominator"
    raise TypeError(msg.format(type(x).__name__))


# FIXME This is faster than Fraction.from_decimal, but still too slow. 
Example 34
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_math.py    GNU General Public License v3.0 5 votes vote down vote up
def testIsfinite(self):
        self.assertTrue(math.isfinite(0.0))
        self.assertTrue(math.isfinite(-0.0))
        self.assertTrue(math.isfinite(1.0))
        self.assertTrue(math.isfinite(-1.0))
        self.assertFalse(math.isfinite(float("nan")))
        self.assertFalse(math.isfinite(float("inf")))
        self.assertFalse(math.isfinite(float("-inf"))) 
Example 35
Project: py-metric-temporal-logic   Author: mvcisback   File: utils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _interval_discretizable(itvl, dt):
    l, u = itvl.lower / dt, itvl.upper / dt
    if not (isfinite(l) and isfinite(u)):
        return False
    return max(abs(l - round(l)), abs(u - round(u))) < 1e-3 
Example 36
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: statistics.py    GNU General Public License v2.0 5 votes vote down vote up
def _isfinite(x):
    try:
        return x.is_finite()  # Likely a Decimal.
    except AttributeError:
        return math.isfinite(x)  # Coerces to float first. 
Example 37
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_math.py    GNU General Public License v2.0 5 votes vote down vote up
def testIsfinite(self):
        self.assertTrue(math.isfinite(0.0))
        self.assertTrue(math.isfinite(-0.0))
        self.assertTrue(math.isfinite(1.0))
        self.assertTrue(math.isfinite(-1.0))
        self.assertFalse(math.isfinite(float("nan")))
        self.assertFalse(math.isfinite(float("inf")))
        self.assertFalse(math.isfinite(float("-inf"))) 
Example 38
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_cmath.py    GNU General Public License v2.0 5 votes vote down vote up
def test_isfinite(self):
        real_vals = [float('-inf'), -2.3, -0.0,
                     0.0, 2.3, float('inf'), float('nan')]
        for x in real_vals:
            for y in real_vals:
                z = complex(x, y)
                self.assertEqual(cmath.isfinite(z),
                                  math.isfinite(x) and math.isfinite(y)) 
Example 39
Project: aws-lambda-runtime-pypy   Author: uscheller   File: statistics.py    Apache License 2.0 5 votes vote down vote up
def _isfinite(x):
    try:
        return x.is_finite()  # Likely a Decimal.
    except AttributeError:
        return math.isfinite(x)  # Coerces to float first. 
Example 40
Project: aws-lambda-runtime-pypy   Author: uscheller   File: statistics.py    Apache License 2.0 5 votes vote down vote up
def _exact_ratio(x):
    """Return Real number x to exact (numerator, denominator) pair.

    >>> _exact_ratio(0.25)
    (1, 4)

    x is expected to be an int, Fraction, Decimal or float.
    """
    try:
        # Optimise the common case of floats. We expect that the most often
        # used numeric type will be builtin floats, so try to make this as
        # fast as possible.
        if type(x) is float:
            return x.as_integer_ratio()
        try:
            # x may be an int, Fraction, or Integral ABC.
            return (x.numerator, x.denominator)
        except AttributeError:
            try:
                # x may be a float subclass.
                return x.as_integer_ratio()
            except AttributeError:
                try:
                    # x may be a Decimal.
                    return _decimal_to_ratio(x)
                except AttributeError:
                    # Just give up?
                    pass
    except (OverflowError, ValueError):
        # float NAN or INF.
        assert not math.isfinite(x)
        return (x, None)
    msg = "can't convert type '{}' to numerator/denominator"
    raise TypeError(msg.format(type(x).__name__))


# FIXME This is faster than Fraction.from_decimal, but still too slow. 
Example 41
Project: python-driver   Author: bblfsh   File: astimprove.py    GNU General Public License v3.0 5 votes vote down vote up
def visit_Num(self, node: Node) -> Node:
        # complex objects are not json-serializable
        if isinstance(node["n"], complex):
            node.update({"n": {"real": node["n"].real,
                               "imag": node["n"].imag}})
        # infinity and nan are not json-serializable
        elif not math.isfinite(node["n"]):
            node.update({"n": str(node["n"])})
        return node 
Example 42
Project: news_proj   Author: TheoElia   File: fields.py    MIT License 5 votes vote down vote up
def validate(self, value):
        super().validate(value)
        if value in self.empty_values:
            return
        if not math.isfinite(value):
            raise ValidationError(self.error_messages['invalid'], code='invalid') 
Example 43
Project: yolact   Author: dbolya   File: functions.py    MIT License 5 votes vote down vote up
def add(self, elem):
        """ Adds an element to the window, removing the earliest element if necessary. """
        if not math.isfinite(elem):
            print('Warning: Moving average ignored a value of %f' % elem)
            return
        
        self.window.append(elem)
        self.sum += elem

        if len(self.window) > self.max_window_size:
            self.sum -= self.window.popleft() 
Example 44
Project: setup   Author: mindbender-studio   File: statistics.py    MIT License 5 votes vote down vote up
def _isfinite(x):
    try:
        return x.is_finite()  # Likely a Decimal.
    except AttributeError:
        return math.isfinite(x)  # Coerces to float first. 
Example 45
Project: vue-django-element-django   Author: jonathanmusto   File: fields.py    MIT License 5 votes vote down vote up
def validate(self, value):
        super().validate(value)
        if value in self.empty_values:
            return
        if not math.isfinite(value):
            raise ValidationError(self.error_messages['invalid'], code='invalid') 
Example 46
Project: vue-django-element-django   Author: jonathanmusto   File: fields.py    MIT License 5 votes vote down vote up
def validate(self, value):
        super().validate(value)
        if value in self.empty_values:
            return
        if not math.isfinite(value):
            raise ValidationError(self.error_messages['invalid'], code='invalid') 
Example 47
Project: GeoMop   Author: GeoMop   File: data_types_tree.py    GNU General Public License v3.0 5 votes vote down vote up
def _get_settings_script(self):
        """return python script, that create instance of this class"""
        if self.__float is None:
            return ["Float()"]
        s = str(self.__float)
        if not math.isfinite(self.__float):
            s = "'{}'".format(s)
        return ["Float({0})".format(s)] 
Example 48
Project: eperpus   Author: HilmiZul   File: fields.py    MIT License 5 votes vote down vote up
def validate(self, value):
        super().validate(value)
        if value in self.empty_values:
            return
        if not math.isfinite(value):
            raise ValidationError(self.error_messages['invalid'], code='invalid') 
Example 49
Project: graphql-core-next   Author: graphql-python   File: is_finite.py    MIT License 5 votes vote down vote up
def is_finite(value: Any) -> bool:
    """Return true if a value is a finite number."""
    return (isinstance(value, int) and not isinstance(value, bool)) or (
        isinstance(value, float) and isfinite(value)
    ) 
Example 50
Project: graphql-core-next   Author: graphql-python   File: is_integer.py    MIT License 5 votes vote down vote up
def is_integer(value: Any) -> bool:
    """Return true if a value is an integer number."""
    return (isinstance(value, int) and not isinstance(value, bool)) or (
        isinstance(value, float) and isfinite(value) and int(value) == value
    ) 
Example 51
Project: graphql-core-next   Author: graphql-python   File: scalars.py    MIT License 5 votes vote down vote up
def serialize_float(value: Any) -> float:
    if isinstance(value, bool):
        return 1 if value else 0
    try:
        if not value and isinstance(value, str):
            value = ""
            raise ValueError
        num = value if isinstance(value, float) else float(value)
        if not isfinite(num):
            raise ValueError
    except (ValueError, TypeError):
        raise GraphQLError(
            f"Float cannot represent non numeric value: {inspect(value)}"
        )
    return num 
Example 52
Project: quilt   Author: Richienb   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def isrealnum(variable):
    """
    Check if the variable resembles a rational number.

    :type variable: integer
    :type param: The variable to check.
    """
    return bool(math.isfinite(variable)) 
Example 53
Project: hotxlfp   Author: aidhound   File: statistics.py    MIT License 5 votes vote down vote up
def _isfinite(x):
    try:
        return x.is_finite()  # Likely a Decimal.
    except AttributeError:
        return math.isfinite(x)  # Coerces to float first. 
Example 54
Project: json-syntax   Author: UnitedIncome   File: action_v1.py    MIT License 5 votes vote down vote up
def convert_float(value):
    value = float(value)
    if math.isfinite(value):
        return value
    elif math.isnan(value):
        return "NaN"
    elif value < 0.0:
        return "-Infinity"
    else:
        return "Infinity" 
Example 55
Project: json-syntax   Author: UnitedIncome   File: dynamodb.py    MIT License 5 votes vote down vote up
def _encode_number(value):
    if not isfinite(value):
        # We could employ a string type here, but this could put us in a corner if we
        # try to use number sets...
        raise ValueError("Can't encode non-finite values in Dynamodb")
    if isinstance(value, (int, float, Decimal)):
        return str(value)
    else:
        # This is all the Real interface guarantees us. It's a stretch using Fraction in Dynamo.
        return str(float(value)) 
Example 56
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: fields.py    MIT License 5 votes vote down vote up
def validate(self, value):
        super().validate(value)
        if value in self.empty_values:
            return
        if not math.isfinite(value):
            raise ValidationError(self.error_messages['invalid'], code='invalid') 
Example 57
Project: sawtooth-poet   Author: hyperledger   File: poet_settings_view.py    Apache License 2.0 5 votes vote down vote up
def ztest_maximum_win_deviation(self):
        """Return the zTest maximum win deviation if config setting exists and
        is valid, otherwise return the default.

        The zTest maximum win deviation specifies the maximum allowed
        deviation from the expected win frequency for a particular validator
        before the zTest will fail and the claimed block will be rejected.
        The deviation corresponds to a confidence interval (i.e., how
        confident we are that we have truly detected a validator winning at
        a frequency we consider too frequent):

        3.075 ==> 99.9%
        2.575 ==> 99.5%
        2.321 ==> 99%
        1.645 ==> 95%
        """
        if self._ztest_maximum_win_deviation is None:
            self._ztest_maximum_win_deviation = \
                self._get_config_setting(
                    name='sawtooth.poet.ztest_maximum_win_deviation',
                    value_type=float,
                    default_value=PoetSettingsView.
                    _ZTEST_MAXIMUM_WIN_DEVIATION_,
                    validate_function=lambda value:
                        math.isfinite(value) and value > 0)

        return self._ztest_maximum_win_deviation 
Example 58
Project: Django_To_Do   Author: IEEE-VIT   File: fields.py    MIT License 5 votes vote down vote up
def validate(self, value):
        super().validate(value)
        if value in self.empty_values:
            return
        if not math.isfinite(value):
            raise ValidationError(self.error_messages['invalid'], code='invalid') 
Example 59
Project: bfx-hf-indicators-py   Author: bitfinexcom   File: envelope.py    Apache License 2.0 5 votes vote down vote up
def update(self, v):
    self._sma.update(v)
    basis = self._sma.v()

    if not isfinite(basis):
      return
    
    delta = basis * self._p
    super().update({
      'upper': basis + delta,
      'basis': basis,
      'lower': basis - delta
    })

    return self.v() 
Example 60
Project: bfx-hf-indicators-py   Author: bitfinexcom   File: envelope.py    Apache License 2.0 5 votes vote down vote up
def add(self, v):
    self._sma.add(v)
    basis = self._sma.v()

    if not isfinite(basis):
      return
    
    delta = basis * self._p
    super().add({
      'upper': basis + delta,
      'basis': basis,
      'lower': basis - delta
    })

    return self.v() 
Example 61
Project: bfx-hf-indicators-py   Author: bitfinexcom   File: rsi.py    Apache License 2.0 5 votes vote down vote up
def _rs (self):
    uAvg = self._uEMA.v()
    dAvg = self._dEMA.v()

    if not isfinite(uAvg) or not isfinite(dAvg) or dAvg == 0:
      return None
    else:
      return uAvg / dAvg 
Example 62
Project: bfx-hf-indicators-py   Author: bitfinexcom   File: ema_vol.py    Apache License 2.0 5 votes vote down vote up
def update(self, candle):
    self._ema.update(candle['vol'])
    ema = self._ema.v()

    if isfinite(ema):
      super().update(ema)

    return self.v() 
Example 63
Project: bfx-hf-indicators-py   Author: bitfinexcom   File: ema_vol.py    Apache License 2.0 5 votes vote down vote up
def add(self, candle):
    self._ema.add(candle['vol'])
    ema = self._ema.v()

    if isfinite(ema):
      super().add(ema)

    return self.v() 
Example 64
Project: bfx-hf-indicators-py   Author: bitfinexcom   File: stochastic_rsi.py    Apache License 2.0 5 votes vote down vote up
def add(self, v):
    self._rsi.add(v)
    rsi = self._rsi.v()

    if not isfinite(rsi):
      return self.v()

    self._buffer.append(rsi)
    
    if len(self._buffer) > self._l:
      del self._buffer[0]
    elif len(self._buffer) < self._l:
      return self.v()
    
    low = min(self._buffer)
    high = max(self._buffer)
    stoch = 1 if high == low else ((rsi - low) / (high - low))

    self._smaStoch.add(stoch * 100)
    smaStoch = self._smaStoch.v()

    if not isfinite(smaStoch):
      return self.v()

    self._smaSignal.add(smaStoch)
    smaSignal = self._smaSignal.v()
  
    if isfinite(smaSignal):
      super().add({
        'v': smaStoch,
        'signal': smaSignal
      })

    return self.v() 
Example 65
Project: bfx-hf-indicators-py   Author: bitfinexcom   File: trix.py    Apache License 2.0 5 votes vote down vote up
def update(self, v):
    self._emaFirst.update(v)
    self._emaSecond.update(self._emaFirst.v())
    self._emaThird.update(self._emaSecond.v())

    curr = self._emaThird.v()

    if not isfinite(curr) or self._emaThird.l() < 2:
      return self.v()

    prev = self._emaThird.prev()
   
    return super().update(((curr / prev) - 1) * 10000) 
Example 66
Project: bfx-hf-indicators-py   Author: bitfinexcom   File: trix.py    Apache License 2.0 5 votes vote down vote up
def add(self, v):
    self._emaFirst.add(v)
    self._emaSecond.add(self._emaFirst.v())
    self._emaThird.add(self._emaSecond.v())

    curr = self._emaThird.v()

    if not isfinite(curr) or self._emaThird.l() < 2:
      return self.v()

    prev = self._emaThird.prev()
   
    return super().add(((curr / prev) - 1) * 10000) 
Example 67
Project: bfx-hf-indicators-py   Author: bitfinexcom   File: ease_of_movement.py    Apache License 2.0 5 votes vote down vote up
def update(self, candle):
    if self._lastCandle == None:
      return
    
    eom = EOM.calcEOM(candle, self._lastCandle, self._d)
    self._sma.update(eom)

    v = self._sma.v()

    if isfinite(v):
      super().update(v)
    return self.v() 
Example 68
Project: bfx-hf-indicators-py   Author: bitfinexcom   File: ease_of_movement.py    Apache License 2.0 5 votes vote down vote up
def add(self, candle):
    if self._lastCandle == None:
      self._lastCandle = candle
      return
    
    eom = EOM.calcEOM(candle, self._lastCandle, self._d)
    self._sma.add(eom)

    v = self._sma.v()

    if isfinite(v):
      super().add(v)
    
    self._lastCandle = candle
    return self.v() 
Example 69
Project: bfx-hf-indicators-py   Author: bitfinexcom   File: accumulation_distribution.py    Apache License 2.0 5 votes vote down vote up
def update(self, candle):
    moneyFlowVol = AccumulationDistribution.moneyFlowVol(candle)
    prev = self.prev()

    if isfinite(prev):
      super().update(prev + moneyFlowVol)
    else:
      super().update(moneyFlowVol)

    return self.v() 
Example 70
Project: bfx-hf-indicators-py   Author: bitfinexcom   File: accumulation_distribution.py    Apache License 2.0 5 votes vote down vote up
def add(self, candle):
    moneyFlowVol = AccumulationDistribution.moneyFlowVol(candle)
    prev = self.v()

    if isfinite(prev):
      super().add(prev + moneyFlowVol)
    else:
      super().add(moneyFlowVol)

    return self.v() 
Example 71
Project: bfx-hf-indicators-py   Author: bitfinexcom   File: coppock_curve.py    Apache License 2.0 5 votes vote down vote up
def update(self, v):
    self._shortROC.update(v)
    self._longROC.update(v)

    short = self._shortROC.v()
    long = self._longROC.v()

    if not isfinite(short) or not isfinite(long):
      return
    
    self._wma.update(short + long)
    super().update(self._wma.v())
    return self.v() 
Example 72
Project: bfx-hf-indicators-py   Author: bitfinexcom   File: coppock_curve.py    Apache License 2.0 5 votes vote down vote up
def add(self, v):
    self._shortROC.add(v)
    self._longROC.add(v)

    short = self._shortROC.v()
    long = self._longROC.v()

    if not isfinite(short) or not isfinite(long):
      return
    
    self._wma.add(short + long)
    super().add(self._wma.v())
    return self.v() 
Example 73
Project: bfx-hf-indicators-py   Author: bitfinexcom   File: relative_volatility_index.py    Apache License 2.0 5 votes vote down vote up
def add(self, v):
    if self._prevInputValue == None:
      self._prevInputValue = v
      return self.v()

    self._stddev.add(v)
    stddev = self._stddev.v()

    if not isfinite(stddev):
      return self.v()
    
    [u, d] = RVI.ud(v, self._prevInputValue, stddev)

    self._uEMA.add(u)
    self._dEMA.add(d)

    uSum = self._uEMA.v()
    dSum = self._dEMA.v()

    if uSum == dSum:
      super().add(0)
    else:
      super().add(100 * (uSum / (uSum + dSum)))
    
    self._prevInputValue = v

    return self.v() 
Example 74
Project: AyurGenomics-Viz-ML   Author: rintukutum   File: fields.py    MIT License 5 votes vote down vote up
def validate(self, value):
        super().validate(value)
        if value in self.empty_values:
            return
        if not math.isfinite(value):
            raise ValidationError(self.error_messages['invalid'], code='invalid') 
Example 75
Project: data_algebra   Author: WinVector   File: SQLite.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def prepare_connection(self, conn):
        # https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.create_function
        conn.create_function("is_bad", 1, _check_scalar_bad)
        # math fns
        conn.create_function("acos", 1, math.acos)
        conn.create_function("acosh", 1, math.acosh)
        conn.create_function("asin", 1, math.asin)
        conn.create_function("asinh", 1, math.asinh)
        conn.create_function("atan", 1, math.atan)
        conn.create_function("atanh", 1, math.atanh)
        conn.create_function("ceil", 1, math.ceil)
        conn.create_function("cos", 1, math.cos)
        conn.create_function("cosh", 1, math.cosh)
        conn.create_function("degrees", 1, math.degrees)
        conn.create_function("erf", 1, math.erf)
        conn.create_function("erfc", 1, math.erfc)
        conn.create_function("exp", 1, math.exp)
        conn.create_function("expm1", 1, math.expm1)
        conn.create_function("fabs", 1, math.fabs)
        conn.create_function("factorial", 1, math.factorial)
        conn.create_function("floor", 1, math.floor)
        conn.create_function("frexp", 1, math.frexp)
        conn.create_function("gamma", 1, math.gamma)
        conn.create_function("isfinite", 1, math.isfinite)
        conn.create_function("isinf", 1, math.isinf)
        conn.create_function("isnan", 1, math.isnan)
        conn.create_function("lgamma", 1, math.lgamma)
        conn.create_function("log", 1, math.log)
        conn.create_function("log10", 1, math.log10)
        conn.create_function("log1p", 1, math.log1p)
        conn.create_function("log2", 1, math.log2)
        conn.create_function("modf", 1, math.modf)
        conn.create_function("radians", 1, math.radians)
        conn.create_function("sin", 1, math.sin)
        conn.create_function("sinh", 1, math.sinh)
        conn.create_function("sqrt", 1, math.sqrt)
        conn.create_function("tan", 1, math.tan)
        conn.create_function("tanh", 1, math.tanh)
        conn.create_function("trunc", 1, math.trunc)
        conn.create_function("atan2", 2, math.atan2)
        conn.create_function("copysign", 2, math.copysign)
        conn.create_function("fmod", 2, math.fmod)
        conn.create_function("gcd", 2, math.gcd)
        conn.create_function("hypot", 2, math.hypot)
        conn.create_function("isclose", 2, math.isclose)
        conn.create_function("ldexp", 2, math.ldexp)
        conn.create_function("pow", 2, math.pow) 
Example 76
Project: data_algebra   Author: WinVector   File: SQLite.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def prepare_connection(self, conn):
        # https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.create_function
        conn.create_function("is_bad", 1, _check_scalar_bad)
        # math fns
        conn.create_function("acos", 1, math.acos)
        conn.create_function("acosh", 1, math.acosh)
        conn.create_function("asin", 1, math.asin)
        conn.create_function("asinh", 1, math.asinh)
        conn.create_function("atan", 1, math.atan)
        conn.create_function("atanh", 1, math.atanh)
        conn.create_function("ceil", 1, math.ceil)
        conn.create_function("cos", 1, math.cos)
        conn.create_function("cosh", 1, math.cosh)
        conn.create_function("degrees", 1, math.degrees)
        conn.create_function("erf", 1, math.erf)
        conn.create_function("erfc", 1, math.erfc)
        conn.create_function("exp", 1, math.exp)
        conn.create_function("expm1", 1, math.expm1)
        conn.create_function("fabs", 1, math.fabs)
        conn.create_function("factorial", 1, math.factorial)
        conn.create_function("floor", 1, math.floor)
        conn.create_function("frexp", 1, math.frexp)
        conn.create_function("gamma", 1, math.gamma)
        conn.create_function("isfinite", 1, math.isfinite)
        conn.create_function("isinf", 1, math.isinf)
        conn.create_function("isnan", 1, math.isnan)
        conn.create_function("lgamma", 1, math.lgamma)
        conn.create_function("log", 1, math.log)
        conn.create_function("log10", 1, math.log10)
        conn.create_function("log1p", 1, math.log1p)
        conn.create_function("log2", 1, math.log2)
        conn.create_function("modf", 1, math.modf)
        conn.create_function("radians", 1, math.radians)
        conn.create_function("sin", 1, math.sin)
        conn.create_function("sinh", 1, math.sinh)
        conn.create_function("sqrt", 1, math.sqrt)
        conn.create_function("tan", 1, math.tan)
        conn.create_function("tanh", 1, math.tanh)
        conn.create_function("trunc", 1, math.trunc)
        conn.create_function("atan2", 2, math.atan2)
        conn.create_function("copysign", 2, math.copysign)
        conn.create_function("fmod", 2, math.fmod)
        conn.create_function("gcd", 2, math.gcd)
        conn.create_function("hypot", 2, math.hypot)
        conn.create_function("isclose", 2, math.isclose)
        conn.create_function("ldexp", 2, math.ldexp)
        conn.create_function("pow", 2, math.pow) 
Example 77
Project: jenkspy   Author: mthh   File: core.py    MIT License 4 votes vote down vote up
def jenks_breaks(values, nb_class):
    """
    Compute jenks natural breaks on a sequence of `values`, given `nb_class`,
    the number of desired class.

    Parameters
    ----------
    values : array-like
        The Iterable sequence of numbers (integer/float) to be used.
    nb_class : int
        The desired number of class (as some other functions requests
        a `k` value, `nb_class` is like `k` + 1). Have to be lesser than
        the length of `values` and greater than 2.

    Returns
    -------
    breaks : tuple of floats
        The computed break values, including minimum and maximum, in order
        to have all the bounds for building `nb_class` class,
        so the returned tuple has a length of `nb_class` + 1.


    Examples
    --------
    Using nb_class = 3, expecting 4 break values , including min and max :

    >>> jenks_breaks(
            [1.3, 7.1, 7.3, 2.3, 3.9, 4.1, 7.8, 1.2, 4.3, 7.3, 5.0, 4.3],
            nb_class = 3)  # Should output (1.2, 2.3, 5.0, 7.8)

    """

    if not isinstance(values, Iterable) or isinstance(values, (str, bytes)):
        raise TypeError("A sequence of numbers is expected")
    if isinstance(nb_class, float) and int(nb_class) == nb_class:
        nb_class = int(nb_class)
    if not isinstance(nb_class, int):
        raise TypeError(
            "Number of class have to be a positive integer: "
            "expected an instance of 'int' but found {}"
            .format(type(nb_class)))

    nb_values = len(values)
    if np and isinstance(values, np.ndarray):
        values = values[np.argwhere(np.isfinite(values)).reshape(-1)]
    else:
        values = [i for i in values if isfinite(i)]
        
    if len(values) != nb_values:
        warnings.warn('Invalid values encountered (NaN or Inf) were ignored')
        nb_values = len(values)
    
    if nb_class >= nb_values or nb_class < 2:
        raise ValueError("Number of class have to be an integer "
                         "greater than 2 and "
                         "smaller than the number of values to use")

    return jenks._jenks_breaks(values, nb_class) 
Example 78
Project: kaggle-kuzushiji-2019   Author: lopuhin   File: engine.py    MIT License 4 votes vote down vote up
def train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq):
    model.train()
    metric_logger = utils.MetricLogger(delimiter='  ')
    metric_logger.add_meter(
        'lr', utils.SmoothedValue(window_size=1, fmt='{value:.6f}'))
    header = 'Epoch: [{}]'.format(epoch)

    lr_scheduler = None
    if epoch == 0:
        warmup_factor = 1. / 1000
        warmup_iters = min(1000, len(data_loader) - 1)

        lr_scheduler = utils.warmup_lr_scheduler(
            optimizer, warmup_iters, warmup_factor)

    for images, targets in metric_logger.log_every(
            data_loader, print_freq, header):
        images = list(image.to(device) for image in images)
        targets = [{k: v.to(device) for k, v in t.items()} for t in targets]

        loss_dict = model(images, targets)

        losses = sum(loss for loss in loss_dict.values())

        # reduce losses over all GPUs for logging purposes
        loss_dict_reduced = utils.reduce_dict(loss_dict)
        losses_reduced = sum(loss for loss in loss_dict_reduced.values())

        loss_value = losses_reduced.item()

        if not math.isfinite(loss_value):
            print('Loss is {}, stopping training'.format(loss_value))
            print(loss_dict_reduced)
            sys.exit(1)

        optimizer.zero_grad()
        losses.backward()
        optimizer.step()

        if lr_scheduler is not None:
            lr_scheduler.step()

        metric_logger.update(loss=losses_reduced, **loss_dict_reduced)
        metric_logger.update(lr=optimizer.param_groups[0]['lr'])

    return {k: m.global_avg for k, m in metric_logger.meters.items()} 
Example 79
Project: doctor   Author: upsight   File: types.py    MIT License 4 votes vote down vote up
def __new__(cls, *args, **kwargs):
        if cls.nullable and args[0] is None:
            return None

        try:
            value = cls.native_type.__new__(cls, *args, **kwargs)
        except (TypeError, ValueError):
            raise TypeSystemError(cls=cls, code='type') from None

        if not math.isfinite(value):
            raise TypeSystemError(cls=cls, code='finite')

        if cls.minimum is not None:
            if cls.exclusive_minimum:
                if value <= cls.minimum:
                    raise TypeSystemError(cls=cls, code='exclusive_minimum')
            else:
                if value < cls.minimum:
                    raise TypeSystemError(cls=cls, code='minimum')

        if cls.maximum is not None:
            if cls.exclusive_maximum:
                if value >= cls.maximum:
                    raise TypeSystemError(cls=cls, code='exclusive_maximum')
            else:
                if value > cls.maximum:
                    raise TypeSystemError(cls=cls, code='maximum')

        if cls.multiple_of is not None:
            if isinstance(cls.multiple_of, float):
                failed = not (value * (1 / cls.multiple_of)).is_integer()
            else:
                failed = value % cls.multiple_of
            if failed:
                raise TypeSystemError(cls=cls, code='multiple_of')

        # Coerce value to the native type.  We only do this if the value
        # is an instance of the class.
        if isinstance(value, cls):
            value = cls.native_type(value)

        cls.validate(value)
        return value 
Example 80
Project: campy   Author: sredmond   File: gmath.py    MIT License 4 votes vote down vote up
def count_digits(n, base=10):
    """Count the number of digits in a number in some base.

    Any non-integral part of the number is discarded: ``count_digits(3.1415)``
    is the same as ``count_digits(3)``.

    The provided n must be finite and the provided base must be a positive
    integer, otherwise an error is raised.

    Usage::

        count_digits(4)  # => 1
        count_digits(41)  # => 2
        count_digits(413)  # => 3

        count_digits(9.9)  # => 1
        count_digits(10.1)  # => 2

        count_digits(-15)  # => 2
        count_digits(-314.15)  # => 3

        count_digits(3, base=2)  # => 2
        count_digits(4, base=2)  # => 3
        count_digits(8, base=3)  # => 2
        count_digits(41, base=5)  # => 3

    Invalid Usage::

        count_digits(float('inf'))  # raises error
        count_digits(5, base=-3)  # raises error
        count_digits(5, base=2.2)  # raises error

    :param n: number whose digits to count
    :param base: base system to use
    :returns: the number of digits of n when written in the given base.
    """
    if not math.isfinite(n):
        error("n must be finite")
    if base <= 0 or not float.is_integer(base):
        error("base must be a positive integer")
    n = int(abs(n))
    base = int(base)

    count = 0
    while n > 0:
        count += 1
        n //= count
    return count


# TODO(sredmond): Consider adding an isclose method.