Python math.isinf() Examples

The following are code examples for showing how to use math.isinf(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: DropboxConnect   Author: raguay   File: stone_validators.py    (MIT License) View Source Project 6 votes vote down vote up
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 
Example 2
Project: kinect-2-libras   Author: inessadl   File: fractions.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def __eq__(a, b):
        """a == b"""
        if isinstance(b, Rational):
            return (a._numerator == b.numerator and
                    a._denominator == b.denominator)
        if isinstance(b, numbers.Complex) and b.imag == 0:
            b = b.real
        if isinstance(b, float):
            if math.isnan(b) or math.isinf(b):
                # comparisons with an infinity or nan should behave in
                # the same way for any finite a, so treat a as zero.
                return 0.0 == b
            else:
                return a == a.from_float(b)
        else:
            # Since a doesn't know how to compare with b, let's give b
            # a chance to compare itself with a.
            return NotImplemented 
Example 3
Project: kinect-2-libras   Author: inessadl   File: fractions.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def _richcmp(self, other, op):
        """Helper for comparison operators, for internal use only.

        Implement comparison between a Rational instance `self`, and
        either another Rational instance or a float `other`.  If
        `other` is not a Rational instance or a float, return
        NotImplemented. `op` should be one of the six standard
        comparison operators.

        """
        # convert other to a Rational instance where reasonable.
        if isinstance(other, Rational):
            return op(self._numerator * other.denominator,
                      self._denominator * other.numerator)
        # comparisons with complex should raise a TypeError, for consistency
        # with int<->complex, float<->complex, and complex<->complex comparisons.
        if isinstance(other, complex):
            raise TypeError("no ordering relation is defined for complex numbers")
        if isinstance(other, float):
            if math.isnan(other) or math.isinf(other):
                return op(0.0, other)
            else:
                return op(self, self.from_float(other))
        else:
            return NotImplemented 
Example 4
Project: Projects   Author: it2school   File: stone_validators.py    (license) View Source Project 6 votes vote down vote up
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 
Example 5
Project: girder_worker   Author: girder   File: table_test.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def test_nan(self):
        output = convert(
            'table',
            {
                'format': 'csv',
                'url': 'file://' + os.path.join('data', 'RadiomicsData.csv')
            },
            {'format': 'rows.json'}
        )
        data = json.loads(output['data'])
        self.assertEqual(len(data['fields']), 454)
        self.assertEqual(data['fields'][:3], [
            'GLCM_autocorr', 'GLCM_clusProm', 'GLCM_clusShade'
        ])
        self.assertEqual(len(data['rows']), 99)
        for row in data['rows']:
            for field in row:
                if isinstance(row[field], float):
                    self.assertFalse(math.isnan(row[field]))
                    self.assertFalse(math.isinf(row[field])) 
Example 6
Project: girder_worker   Author: girder   File: __init__.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def csv_to_rows(input):
    reader = get_csv_reader(input)
    rows = [d for d in reader]
    fields = reader.fieldnames

    output = {'fields': fields, 'rows': rows}

    # Attempt numeric conversion
    for row in output['rows']:
        for col in row:
            try:
                row[col] = int(row[col])
            except Exception:
                try:
                    orig = row[col]
                    row[col] = float(row[col])

                    # Disallow NaN, Inf, -Inf since this does not
                    # pass through JSON converters cleanly
                    if math.isnan(row[col]) or math.isinf(row[col]):
                        row[col] = orig
                except Exception:
                    pass

    return output 
Example 7
Project: hostapd-mana   Author: adde88   File: python.py    (license) View Source Project 6 votes vote down vote up
def __repr__(self):
        # Infinities aren't compared using tolerances, so don't show a
        # tolerance.
        if math.isinf(self.expected):
            return str(self.expected)

        # If a sensible tolerance can't be calculated, self.tolerance will
        # raise a ValueError.  In this case, display '???'.
        try:
            vetted_tolerance = '{:.1e}'.format(self.tolerance)
        except ValueError:
            vetted_tolerance = '???'

        plus_minus = u'{0} \u00b1 {1}'.format(self.expected, vetted_tolerance)

        # In python2, __repr__() must return a string (i.e. not a unicode
        # object).  In python3, __repr__() must return a unicode object
        # (although now strings are unicode objects and bytes are what
        # strings were).
        if sys.version_info[0] == 2:
            return plus_minus.encode('utf-8')
        else:
            return plus_minus 
Example 8
Project: hostapd-mana   Author: adde88   File: python.py    (license) View Source Project 6 votes vote down vote up
def __eq__(self, actual):
        # Short-circuit exact equality.
        if actual == self.expected:
            return True

        # Infinity shouldn't be approximately equal to anything but itself, but
        # if there's a relative tolerance, it will be infinite and infinity
        # will seem approximately equal to everything.  The equal-to-itself
        # case would have been short circuited above, so here we can just
        # return false if the expected value is infinite.  The abs() call is
        # for compatibility with complex numbers.
        if math.isinf(abs(self.expected)):
            return False

        # Return true if the two numbers are within the tolerance.
        return abs(self.expected - actual) <= self.tolerance 
Example 9
Project: hostapd-mana   Author: adde88   File: fractions.py    (license) View Source Project 6 votes vote down vote up
def __eq__(a, b):
        """a == b"""
        if isinstance(b, Rational):
            return (a._numerator == b.numerator and
                    a._denominator == b.denominator)
        if isinstance(b, numbers.Complex) and b.imag == 0:
            b = b.real
        if isinstance(b, float):
            if math.isnan(b) or math.isinf(b):
                # comparisons with an infinity or nan should behave in
                # the same way for any finite a, so treat a as zero.
                return 0.0 == b
            else:
                return a == a.from_float(b)
        else:
            # Since a doesn't know how to compare with b, let's give b
            # a chance to compare itself with a.
            return NotImplemented 
Example 10
Project: probabilistic-matrix-factorization   Author: aki-nishimura   File: matrix_factorization.py    (license) View Source Project 6 votes vote down vote up
def update_weight_param(self, mu0, r, u, c, v):
        # Returns the weight parameters in an 1-D array in the row major order
        # and also the mean estimate of matrix factorization as a by-product.

        mu = self.compute_model_mean(self.y_coo.row, self.y_coo.col, mu0, r, u, c, v)

        if math.isinf(self.prior_param['obs_df']):
            phi = self.prior_param['weight']
        else:
            prior_shape = self.prior_param['obs_df'] / 2
            prior_rate = self.prior_param['obs_df'] / 2 / self.prior_param['weight']
            sq_error = (self.y_coo.data - mu) ** 2
            post_shape = prior_shape + 1 / 2
            post_rate = prior_rate + sq_error / 2
            phi = np.random.gamma(post_shape, 1 / post_rate)

        return phi, mu 
Example 11
Project: python   Author: micronicstraining   File: div_all_conditions_sol.py    (license) View Source Project 6 votes vote down vote up
def main(args):
    num, den = args
    try:
        num, den = float(num), float(den)
    except ValueError as e:
        logging.error('Invalid input')
        return INVALID_INPUT

    if den == 0:
        # this is a run-time error but not a type error
        # can be considered a warning or an error based on use case
        # written here as mere warning.
        logging.warn('Invalid denominator input!')
        return DIV_BY_ZERO_EXIT

    if math.isnan(num) or math.isnan(den):
        return INVALID_INPUT_NAN

    if math.isinf(num) or math.isinf(den):
        return INVALID_INPUT_INF

    print('Answer: ' + str(num / den))
    return 0 
Example 12
Project: dd-trace-py   Author: DataDog   File: span.py    (license) View Source Project 6 votes vote down vote up
def set_metric(self, key, value):
        # This method sets a numeric tag value for the given key. It acts
        # like `set_meta()` and it simply add a tag without further processing.

        # FIXME[matt] we could push this check to serialization time as well.
        # only permit types that are commonly serializable (don't use
        # isinstance so that we convert unserializable types like numpy
        # numbers)
        if type(value) not in numeric_types:
            try:
                value = float(value)
            except (ValueError, TypeError):
                log.debug("ignoring not number metric %s:%s", key, value)
                return

        # don't allow nan or inf
        if math.isnan(value) or math.isinf(value):
            log.debug("ignoring not real metric %s:%s", key, value)
            return

        self.metrics[key] = value 
Example 13
Project: discontinuous-hmc   Author: aki-nishimura   File: nuts_sampler.py    (license) View Source Project 6 votes vote down vote up
def HMC(f, epsilon, n_step, theta0, logp0, grad0):

    p = random_momentum(len(theta0))
    joint0 = - compute_hamiltonian(logp0, p)

    nfevals_total = 0
    theta, p, grad, logp, nfevals = integrator(f, epsilon, theta0, p, grad0)
    nfevals_total += nfevals
    for i in range(1, n_step):
        theta, p, grad, logp, nfevals = integrator(f, epsilon, theta, p, grad)
        nfevals_total += nfevals

    joint = - compute_hamiltonian(logp, p)
    if math.isinf(logp):
        acceptprob = 0
    else:
        acceptprob = min(1, np.exp(joint - joint0))

    if acceptprob < np.random.rand():
        theta = theta0
        logp = logp0
        grad = grad0

    return theta, logp, grad, acceptprob, nfevals_total 
Example 14
Project: datatest   Author: shawnbrown   File: decimal.py    (license) View Source Project 6 votes vote down vote up
def _from_float(cls, f):
        if isinstance(f, int):                # handle integer inputs
            return cls(f)
        if not isinstance(f, float):
            raise TypeError("argument must be int or float.")
        if _math.isinf(f) or _math.isnan(f):
            return cls(repr(f))
        if _math.copysign(1.0, f) == 1.0:
            sign = 0
        else:
            sign = 1
        n, d = abs(f).as_integer_ratio()
        #k = d.bit_length() - 1
        k = _bit_length(d) - 1
        result = _dec_from_triple(sign, str(n*5**k), -k)
        if cls is Decimal:
            return result
        else:
            return cls(result) 
Example 15
Project: zippy   Author: securesystemslab   File: test_math.py    (license) View Source Project 6 votes vote down vote up
def acc_check(expected, got, rel_err=2e-15, abs_err = 5e-323):
    """Determine whether non-NaN floats a and b are equal to within a
    (small) rounding error.  The default values for rel_err and
    abs_err are chosen to be suitable for platforms where a float is
    represented by an IEEE 754 double.  They allow an error of between
    9 and 19 ulps."""

    # need to special case infinities, since inf - inf gives nan
    if math.isinf(expected) and got == expected:
        return None

    error = got - expected

    permitted_error = max(abs_err, rel_err * abs(expected))
    if abs(error) < permitted_error:
        return None
    return "error = {}; permitted error = {}".format(error,
                                                     permitted_error) 
Example 16
Project: zippy   Author: securesystemslab   File: fractions.py    (license) View Source Project 6 votes vote down vote up
def __eq__(a, b):
        """a == b"""
        if isinstance(b, numbers.Rational):
            return (a._numerator == b.numerator and
                    a._denominator == b.denominator)
        if isinstance(b, numbers.Complex) and b.imag == 0:
            b = b.real
        if isinstance(b, float):
            if math.isnan(b) or math.isinf(b):
                # comparisons with an infinity or nan should behave in
                # the same way for any finite a, so treat a as zero.
                return 0.0 == b
            else:
                return a == a.from_float(b)
        else:
            # Since a doesn't know how to compare with b, let's give b
            # a chance to compare itself with a.
            return NotImplemented 
Example 17
Project: zippy   Author: securesystemslab   File: fractions.py    (license) View Source Project 6 votes vote down vote up
def _richcmp(self, other, op):
        """Helper for comparison operators, for internal use only.

        Implement comparison between a Rational instance `self`, and
        either another Rational instance or a float `other`.  If
        `other` is not a Rational instance or a float, return
        NotImplemented. `op` should be one of the six standard
        comparison operators.

        """
        # convert other to a Rational instance where reasonable.
        if isinstance(other, numbers.Rational):
            return op(self._numerator * other.denominator,
                      self._denominator * other.numerator)
        if isinstance(other, float):
            if math.isnan(other) or math.isinf(other):
                return op(0.0, other)
            else:
                return op(self, self.from_float(other))
        else:
            return NotImplemented 
Example 18
Project: oil   Author: oilshell   File: test_math.py    (license) View Source Project 6 votes vote down vote up
def acc_check(expected, got, rel_err=2e-15, abs_err = 5e-323):
    """Determine whether non-NaN floats a and b are equal to within a
    (small) rounding error.  The default values for rel_err and
    abs_err are chosen to be suitable for platforms where a float is
    represented by an IEEE 754 double.  They allow an error of between
    9 and 19 ulps."""

    # need to special case infinities, since inf - inf gives nan
    if math.isinf(expected) and got == expected:
        return None

    error = got - expected

    permitted_error = max(abs_err, rel_err * abs(expected))
    if abs(error) < permitted_error:
        return None
    return "error = {}; permitted error = {}".format(error,
                                                     permitted_error) 
Example 19
Project: oil   Author: oilshell   File: fractions.py    (license) View Source Project 6 votes vote down vote up
def __eq__(a, b):
        """a == b"""
        if isinstance(b, Rational):
            return (a._numerator == b.numerator and
                    a._denominator == b.denominator)
        if isinstance(b, numbers.Complex) and b.imag == 0:
            b = b.real
        if isinstance(b, float):
            if math.isnan(b) or math.isinf(b):
                # comparisons with an infinity or nan should behave in
                # the same way for any finite a, so treat a as zero.
                return 0.0 == b
            else:
                return a == a.from_float(b)
        else:
            # Since a doesn't know how to compare with b, let's give b
            # a chance to compare itself with a.
            return NotImplemented 
Example 20
Project: oil   Author: oilshell   File: fractions.py    (license) View Source Project 6 votes vote down vote up
def _richcmp(self, other, op):
        """Helper for comparison operators, for internal use only.

        Implement comparison between a Rational instance `self`, and
        either another Rational instance or a float `other`.  If
        `other` is not a Rational instance or a float, return
        NotImplemented. `op` should be one of the six standard
        comparison operators.

        """
        # convert other to a Rational instance where reasonable.
        if isinstance(other, Rational):
            return op(self._numerator * other.denominator,
                      self._denominator * other.numerator)
        # comparisons with complex should raise a TypeError, for consistency
        # with int<->complex, float<->complex, and complex<->complex comparisons.
        if isinstance(other, complex):
            raise TypeError("no ordering relation is defined for complex numbers")
        if isinstance(other, float):
            if math.isnan(other) or math.isinf(other):
                return op(0.0, other)
            else:
                return op(self, self.from_float(other))
        else:
            return NotImplemented 
Example 21
Project: python2-tracer   Author: extremecoders-re   File: test_math.py    (license) View Source Project 6 votes vote down vote up
def acc_check(expected, got, rel_err=2e-15, abs_err = 5e-323):
    """Determine whether non-NaN floats a and b are equal to within a
    (small) rounding error.  The default values for rel_err and
    abs_err are chosen to be suitable for platforms where a float is
    represented by an IEEE 754 double.  They allow an error of between
    9 and 19 ulps."""

    # need to special case infinities, since inf - inf gives nan
    if math.isinf(expected) and got == expected:
        return None

    error = got - expected

    permitted_error = max(abs_err, rel_err * abs(expected))
    if abs(error) < permitted_error:
        return None
    return "error = {}; permitted error = {}".format(error,
                                                     permitted_error) 
Example 22
Project: python2-tracer   Author: extremecoders-re   File: fractions.py    (license) View Source Project 6 votes vote down vote up
def __eq__(a, b):
        """a == b"""
        if isinstance(b, Rational):
            return (a._numerator == b.numerator and
                    a._denominator == b.denominator)
        if isinstance(b, numbers.Complex) and b.imag == 0:
            b = b.real
        if isinstance(b, float):
            if math.isnan(b) or math.isinf(b):
                # comparisons with an infinity or nan should behave in
                # the same way for any finite a, so treat a as zero.
                return 0.0 == b
            else:
                return a == a.from_float(b)
        else:
            # Since a doesn't know how to compare with b, let's give b
            # a chance to compare itself with a.
            return NotImplemented 
Example 23
Project: python2-tracer   Author: extremecoders-re   File: fractions.py    (license) View Source Project 6 votes vote down vote up
def _richcmp(self, other, op):
        """Helper for comparison operators, for internal use only.

        Implement comparison between a Rational instance `self`, and
        either another Rational instance or a float `other`.  If
        `other` is not a Rational instance or a float, return
        NotImplemented. `op` should be one of the six standard
        comparison operators.

        """
        # convert other to a Rational instance where reasonable.
        if isinstance(other, Rational):
            return op(self._numerator * other.denominator,
                      self._denominator * other.numerator)
        # comparisons with complex should raise a TypeError, for consistency
        # with int<->complex, float<->complex, and complex<->complex comparisons.
        if isinstance(other, complex):
            raise TypeError("no ordering relation is defined for complex numbers")
        if isinstance(other, float):
            if math.isnan(other) or math.isinf(other):
                return op(0.0, other)
            else:
                return op(self, self.from_float(other))
        else:
            return NotImplemented 
Example 24
Project: nmt   Author: tensorflow   File: train.py    (license) View Source Project 6 votes vote down vote up
def check_stats(stats, global_step, steps_per_stats, hparams, log_f):
  """Print statistics and also check for overflow."""
  # Print statistics for the previous epoch.
  avg_step_time = stats["step_time"] / steps_per_stats
  avg_grad_norm = stats["grad_norm"] / steps_per_stats
  train_ppl = utils.safe_exp(
      stats["loss"] / stats["predict_count"])
  speed = stats["total_count"] / (1000 * stats["step_time"])
  utils.print_out(
      "  global step %d lr %g "
      "step-time %.2fs wps %.2fK ppl %.2f gN %.2f %s" %
      (global_step, stats["learning_rate"],
       avg_step_time, speed, train_ppl, avg_grad_norm,
       _get_best_results(hparams)),
      log_f)

  # Check for overflow
  is_overflow = False
  if math.isnan(train_ppl) or math.isinf(train_ppl) or train_ppl > 1e20:
    utils.print_out("  step %d overflow, stop early" % global_step, log_f)
    is_overflow = True

  return is_overflow 
Example 25
Project: sslstrip-hsts-openwrt   Author: adde88   File: python.py    (license) View Source Project 6 votes vote down vote up
def __repr__(self):
        # Infinities aren't compared using tolerances, so don't show a
        # tolerance.
        if math.isinf(self.expected):
            return str(self.expected)

        # If a sensible tolerance can't be calculated, self.tolerance will
        # raise a ValueError.  In this case, display '???'.
        try:
            vetted_tolerance = '{:.1e}'.format(self.tolerance)
        except ValueError:
            vetted_tolerance = '???'

        plus_minus = u'{0} \u00b1 {1}'.format(self.expected, vetted_tolerance)

        # In python2, __repr__() must return a string (i.e. not a unicode
        # object).  In python3, __repr__() must return a unicode object
        # (although now strings are unicode objects and bytes are what
        # strings were).
        if sys.version_info[0] == 2:
            return plus_minus.encode('utf-8')
        else:
            return plus_minus 
Example 26
Project: sslstrip-hsts-openwrt   Author: adde88   File: python.py    (license) View Source Project 6 votes vote down vote up
def __eq__(self, actual):
        # Short-circuit exact equality.
        if actual == self.expected:
            return True

        # Infinity shouldn't be approximately equal to anything but itself, but
        # if there's a relative tolerance, it will be infinite and infinity
        # will seem approximately equal to everything.  The equal-to-itself
        # case would have been short circuited above, so here we can just
        # return false if the expected value is infinite.  The abs() call is
        # for compatibility with complex numbers.
        if math.isinf(abs(self.expected)):
            return False

        # Return true if the two numbers are within the tolerance.
        return abs(self.expected - actual) <= self.tolerance 
Example 27
Project: sslstrip-hsts-openwrt   Author: adde88   File: fractions.py    (license) View Source Project 6 votes vote down vote up
def __eq__(a, b):
        """a == b"""
        if isinstance(b, Rational):
            return (a._numerator == b.numerator and
                    a._denominator == b.denominator)
        if isinstance(b, numbers.Complex) and b.imag == 0:
            b = b.real
        if isinstance(b, float):
            if math.isnan(b) or math.isinf(b):
                # comparisons with an infinity or nan should behave in
                # the same way for any finite a, so treat a as zero.
                return 0.0 == b
            else:
                return a == a.from_float(b)
        else:
            # Since a doesn't know how to compare with b, let's give b
            # a chance to compare itself with a.
            return NotImplemented 
Example 28
Project: web_ctp   Author: molebot   File: test_math.py    (license) View Source Project 6 votes vote down vote up
def acc_check(expected, got, rel_err=2e-15, abs_err = 5e-323):
    """Determine whether non-NaN floats a and b are equal to within a
    (small) rounding error.  The default values for rel_err and
    abs_err are chosen to be suitable for platforms where a float is
    represented by an IEEE 754 double.  They allow an error of between
    9 and 19 ulps."""

    # need to special case infinities, since inf - inf gives nan
    if math.isinf(expected) and got == expected:
        return None

    error = got - expected

    permitted_error = max(abs_err, rel_err * abs(expected))
    if abs(error) < permitted_error:
        return None
    return "error = {}; permitted error = {}".format(error,
                                                     permitted_error) 
Example 29
Project: web_ctp   Author: molebot   File: fractions.py    (license) View Source Project 6 votes vote down vote up
def from_float(cls, f):
        """Converts a finite float to a rational number, exactly.

        Beware that Fraction.from_float(0.3) != Fraction(3, 10).

        """
        if isinstance(f, numbers.Integral):
            return cls(f)
        elif not isinstance(f, float):
            raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
                            (cls.__name__, f, type(f).__name__))
        if math.isnan(f):
            raise ValueError("Cannot convert %r to %s." % (f, cls.__name__))
        if math.isinf(f):
            raise OverflowError("Cannot convert %r to %s." % (f, cls.__name__))
        return cls(*f.as_integer_ratio()) 
Example 30
Project: web_ctp   Author: molebot   File: fractions.py    (license) View Source Project 6 votes vote down vote up
def __eq__(a, b):
        """a == b"""
        if isinstance(b, numbers.Rational):
            return (a._numerator == b.numerator and
                    a._denominator == b.denominator)
        if isinstance(b, numbers.Complex) and b.imag == 0:
            b = b.real
        if isinstance(b, float):
            if math.isnan(b) or math.isinf(b):
                # comparisons with an infinity or nan should behave in
                # the same way for any finite a, so treat a as zero.
                return 0.0 == b
            else:
                return a == a.from_float(b)
        else:
            # Since a doesn't know how to compare with b, let's give b
            # a chance to compare itself with a.
            return NotImplemented 
Example 31
Project: web_ctp   Author: molebot   File: fractions.py    (license) View Source Project 6 votes vote down vote up
def _richcmp(self, other, op):
        """Helper for comparison operators, for internal use only.

        Implement comparison between a Rational instance `self`, and
        either another Rational instance or a float `other`.  If
        `other` is not a Rational instance or a float, return
        NotImplemented. `op` should be one of the six standard
        comparison operators.

        """
        # convert other to a Rational instance where reasonable.
        if isinstance(other, numbers.Rational):
            return op(self._numerator * other.denominator,
                      self._denominator * other.numerator)
        if isinstance(other, float):
            if math.isnan(other) or math.isinf(other):
                return op(0.0, other)
            else:
                return op(self, self.from_float(other))
        else:
            return NotImplemented 
Example 32
Project: cgpm   Author: probcomp   File: importance.py    (license) View Source Project 6 votes vote down vote up
def logpdf(self, rowid, targets, constraints=None, inputs=None):
        if constraints is None:
            constraints = {}
        if inputs is None:
            inputs = {}
        # Compute joint probability.
        samples_joint, weights_joint = zip(*[
            self.weighted_sample(
                rowid, [], gu.merged(targets, constraints), inputs)
            for _i in xrange(self.accuracy)
        ])
        logp_joint = gu.logmeanexp(weights_joint)
        # Compute marginal probability.
        samples_marginal, weights_marginal = zip(*[
            self.weighted_sample(rowid, [], constraints, inputs)
            for _i in xrange(self.accuracy)
        ]) if constraints else ({}, [0.])
        if all(isinf(l) for l in weights_marginal):
            raise ValueError('Zero density constraints: %s' % (constraints,))
        logp_constraints = gu.logmeanexp(weights_marginal)
        # Return log ratio.
        return logp_joint - logp_constraints 
Example 33
Project: cgpm   Author: probcomp   File: general.py    (license) View Source Project 6 votes vote down vote up
def logsumexp(array):
    # https://github.com/probcomp/bayeslite/blob/master/src/math_util.py
    if len(array) == 0:
        return float('-inf')
    m = max(array)

    # m = +inf means addends are all +inf, hence so are sum and log.
    # m = -inf means addends are all zero, hence so is sum, and log is
    # -inf.  But if +inf and -inf are among the inputs, or if input is
    # NaN, let the usual computation yield a NaN.
    if math.isinf(m) and min(array) != -m and \
       all(not math.isnan(a) for a in array):
        return m

    # Since m = max{a_0, a_1, ...}, it follows that a <= m for all a,
    # so a - m <= 0; hence exp(a - m) is guaranteed not to overflow.
    return m + math.log(sum(math.exp(a - m) for a in array)) 
Example 34
Project: godot-python   Author: touilleMan   File: python.py    (license) View Source Project 6 votes vote down vote up
def __repr__(self):
        if isinstance(self.expected, complex):
            return str(self.expected)

        # Infinities aren't compared using tolerances, so don't show a
        # tolerance.
        if math.isinf(self.expected):
            return str(self.expected)

        # If a sensible tolerance can't be calculated, self.tolerance will
        # raise a ValueError.  In this case, display '???'.
        try:
            vetted_tolerance = '{:.1e}'.format(self.tolerance)
        except ValueError:
            vetted_tolerance = '???'

        if sys.version_info[0] == 2:
            return '{0} +- {1}'.format(self.expected, vetted_tolerance)
        else:
            return u'{0} \u00b1 {1}'.format(self.expected, vetted_tolerance) 
Example 35
Project: godot-python   Author: touilleMan   File: python.py    (license) View Source Project 6 votes vote down vote up
def __eq__(self, actual):
        # Short-circuit exact equality.
        if actual == self.expected:
            return True

        # Infinity shouldn't be approximately equal to anything but itself, but
        # if there's a relative tolerance, it will be infinite and infinity
        # will seem approximately equal to everything.  The equal-to-itself
        # case would have been short circuited above, so here we can just
        # return false if the expected value is infinite.  The abs() call is
        # for compatibility with complex numbers.
        if math.isinf(abs(self.expected)):
            return False

        # Return true if the two numbers are within the tolerance.
        return abs(self.expected - actual) <= self.tolerance 
Example 36
Project: godot-python   Author: touilleMan   File: python.py    (license) View Source Project 6 votes vote down vote up
def __repr__(self):
        if isinstance(self.expected, complex):
            return str(self.expected)

        # Infinities aren't compared using tolerances, so don't show a
        # tolerance.
        if math.isinf(self.expected):
            return str(self.expected)

        # If a sensible tolerance can't be calculated, self.tolerance will
        # raise a ValueError.  In this case, display '???'.
        try:
            vetted_tolerance = '{:.1e}'.format(self.tolerance)
        except ValueError:
            vetted_tolerance = '???'

        if sys.version_info[0] == 2:
            return '{0} +- {1}'.format(self.expected, vetted_tolerance)
        else:
            return u'{0} \u00b1 {1}'.format(self.expected, vetted_tolerance) 
Example 37
Project: godot-python   Author: touilleMan   File: python.py    (license) View Source Project 6 votes vote down vote up
def __eq__(self, actual):
        # Short-circuit exact equality.
        if actual == self.expected:
            return True

        # Infinity shouldn't be approximately equal to anything but itself, but
        # if there's a relative tolerance, it will be infinite and infinity
        # will seem approximately equal to everything.  The equal-to-itself
        # case would have been short circuited above, so here we can just
        # return false if the expected value is infinite.  The abs() call is
        # for compatibility with complex numbers.
        if math.isinf(abs(self.expected)):
            return False

        # Return true if the two numbers are within the tolerance.
        return abs(self.expected - actual) <= self.tolerance 
Example 38
Project: drupebox   Author: duncanhawthorne   File: stone_validators.py    (license) View Source Project 6 votes vote down vote up
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 
Example 39
Project: pefile.pypy   Author: cloudtracer   File: test_math.py    (license) View Source Project 6 votes vote down vote up
def acc_check(expected, got, rel_err=2e-15, abs_err = 5e-323):
    """Determine whether non-NaN floats a and b are equal to within a
    (small) rounding error.  The default values for rel_err and
    abs_err are chosen to be suitable for platforms where a float is
    represented by an IEEE 754 double.  They allow an error of between
    9 and 19 ulps."""

    # need to special case infinities, since inf - inf gives nan
    if math.isinf(expected) and got == expected:
        return None

    error = got - expected

    permitted_error = max(abs_err, rel_err * abs(expected))
    if abs(error) < permitted_error:
        return None
    return "error = {}; permitted error = {}".format(error,
                                                     permitted_error) 
Example 40
Project: pefile.pypy   Author: cloudtracer   File: fractions.py    (license) View Source Project 6 votes vote down vote up
def __eq__(a, b):
        """a == b"""
        if isinstance(b, Rational):
            return (a._numerator == b.numerator and
                    a._denominator == b.denominator)
        if isinstance(b, numbers.Complex) and b.imag == 0:
            b = b.real
        if isinstance(b, float):
            if math.isnan(b) or math.isinf(b):
                # comparisons with an infinity or nan should behave in
                # the same way for any finite a, so treat a as zero.
                return 0.0 == b
            else:
                return a == a.from_float(b)
        else:
            # Since a doesn't know how to compare with b, let's give b
            # a chance to compare itself with a.
            return NotImplemented 
Example 41
Project: pefile.pypy   Author: cloudtracer   File: fractions.py    (license) View Source Project 6 votes vote down vote up
def _richcmp(self, other, op):
        """Helper for comparison operators, for internal use only.

        Implement comparison between a Rational instance `self`, and
        either another Rational instance or a float `other`.  If
        `other` is not a Rational instance or a float, return
        NotImplemented. `op` should be one of the six standard
        comparison operators.

        """
        # convert other to a Rational instance where reasonable.
        if isinstance(other, Rational):
            return op(self._numerator * other.denominator,
                      self._denominator * other.numerator)
        # comparisons with complex should raise a TypeError, for consistency
        # with int<->complex, float<->complex, and complex<->complex comparisons.
        if isinstance(other, complex):
            raise TypeError("no ordering relation is defined for complex numbers")
        if isinstance(other, float):
            if math.isnan(other) or math.isinf(other):
                return op(0.0, other)
            else:
                return op(self, self.from_float(other))
        else:
            return NotImplemented 
Example 42
Project: ouroboros   Author: pybee   File: cmath.py    (license) View Source Project 6 votes vote down vote up
def rect(r, phi):
    _rect_special = [
        [inf+nanj, None, -inf, complex(-float("inf"), -0.0), None, inf+nanj, inf+nanj],
        [nan+nanj, None, None, None, None, nan+nanj, nan+nanj],
        [0, None, complex(-0.0, 0.0), complex(-0.0, -0.0), None, 0, 0],
        [0, None, complex(0.0, -0.0), 0, None, 0, 0],
        [nan+nanj, None, None, None, None, nan+nanj, nan+nanj],
        [inf+nanj, None, complex(float("inf"), -0.0), inf, None, inf+nanj, inf+nanj],
        [nan+nanj, nan+nanj, nan, nan, nan+nanj, nan+nanj, nan+nanj]
    ]

    if not math.isfinite(r) or not math.isfinite(phi):
        if math.isinf(phi) and not math.isnan(r) and r != 0:
            raise ValueError
        if math.isinf(r) and math.isfinite(phi) and phi != 0:
            if r > 0:
                return complex(math.copysign(inf, math.cos(phi)),
                               math.copysign(inf, math.sin(phi)))
            return complex(-math.copysign(inf, math.cos(phi)),
                           -math.copysign(inf, math.sin(phi)))
        return _rect_special[_special_type(r)][_special_type(phi)]
    return complex(r*math.cos(phi), r*math.sin(phi)) 
Example 43
Project: ouroboros   Author: pybee   File: cmath.py    (license) View Source Project 6 votes vote down vote up
def isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0):
    a = _make_complex(a)
    b = _make_complex(b)
    rel_tol = float(rel_tol)
    abs_tol = float(abs_tol)
    if rel_tol < 0 or abs_tol < 0:
        raise ValueError("tolerances must be non-negative")
    if a.real == b.real and a.imag == b.imag:
        return True
    if math.isinf(a.real) or math.isinf(a.imag) or math.isinf(b.real) \
            or math.isinf(b.imag):
        return False
    # if isnan(a) or isnan(b):
    #     return False
    diff = abs(a-b)
    return diff <= rel_tol * abs(a) or diff <= rel_tol * abs(b) or diff <= abs_tol 
Example 44
Project: ouroboros   Author: pybee   File: test_math.py    (license) View Source Project 6 votes vote down vote up
def acc_check(expected, got, rel_err=2e-15, abs_err = 5e-323):
    """Determine whether non-NaN floats a and b are equal to within a
    (small) rounding error.  The default values for rel_err and
    abs_err are chosen to be suitable for platforms where a float is
    represented by an IEEE 754 double.  They allow an error of between
    9 and 19 ulps."""

    # need to special case infinities, since inf - inf gives nan
    if math.isinf(expected) and got == expected:
        return None

    error = got - expected

    permitted_error = max(abs_err, rel_err * abs(expected))
    if abs(error) < permitted_error:
        return None
    return "error = {}; permitted error = {}".format(error,
                                                     permitted_error) 
Example 45
Project: ouroboros   Author: pybee   File: fractions.py    (license) View Source Project 6 votes vote down vote up
def from_float(cls, f):
        """Converts a finite float to a rational number, exactly.

        Beware that Fraction.from_float(0.3) != Fraction(3, 10).

        """
        if isinstance(f, numbers.Integral):
            return cls(f)
        elif not isinstance(f, float):
            raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
                            (cls.__name__, f, type(f).__name__))
        if math.isnan(f):
            raise ValueError("Cannot convert %r to %s." % (f, cls.__name__))
        if math.isinf(f):
            raise OverflowError("Cannot convert %r to %s." % (f, cls.__name__))
        return cls(*f.as_integer_ratio()) 
Example 46
Project: ouroboros   Author: pybee   File: fractions.py    (license) View Source Project 6 votes vote down vote up
def __eq__(a, b):
        """a == b"""
        if isinstance(b, numbers.Rational):
            return (a._numerator == b.numerator and
                    a._denominator == b.denominator)
        if isinstance(b, numbers.Complex) and b.imag == 0:
            b = b.real
        if isinstance(b, float):
            if math.isnan(b) or math.isinf(b):
                # comparisons with an infinity or nan should behave in
                # the same way for any finite a, so treat a as zero.
                return 0.0 == b
            else:
                return a == a.from_float(b)
        else:
            # Since a doesn't know how to compare with b, let's give b
            # a chance to compare itself with a.
            return NotImplemented 
Example 47
Project: ouroboros   Author: pybee   File: fractions.py    (license) View Source Project 6 votes vote down vote up
def _richcmp(self, other, op):
        """Helper for comparison operators, for internal use only.

        Implement comparison between a Rational instance `self`, and
        either another Rational instance or a float `other`.  If
        `other` is not a Rational instance or a float, return
        NotImplemented. `op` should be one of the six standard
        comparison operators.

        """
        # convert other to a Rational instance where reasonable.
        if isinstance(other, numbers.Rational):
            return op(self._numerator * other.denominator,
                      self._denominator * other.numerator)
        if isinstance(other, float):
            if math.isnan(other) or math.isinf(other):
                return op(0.0, other)
            else:
                return op(self, self.from_float(other))
        else:
            return NotImplemented 
Example 48
Project: ndk-python   Author: gittor   File: test_math.py    (license) View Source Project 6 votes vote down vote up
def acc_check(expected, got, rel_err=2e-15, abs_err = 5e-323):
    """Determine whether non-NaN floats a and b are equal to within a
    (small) rounding error.  The default values for rel_err and
    abs_err are chosen to be suitable for platforms where a float is
    represented by an IEEE 754 double.  They allow an error of between
    9 and 19 ulps."""

    # need to special case infinities, since inf - inf gives nan
    if math.isinf(expected) and got == expected:
        return None

    error = got - expected

    permitted_error = max(abs_err, rel_err * abs(expected))
    if abs(error) < permitted_error:
        return None
    return "error = {}; permitted error = {}".format(error,
                                                     permitted_error) 
Example 49
Project: ndk-python   Author: gittor   File: fractions.py    (license) View Source Project 6 votes vote down vote up
def __eq__(a, b):
        """a == b"""
        if isinstance(b, Rational):
            return (a._numerator == b.numerator and
                    a._denominator == b.denominator)
        if isinstance(b, numbers.Complex) and b.imag == 0:
            b = b.real
        if isinstance(b, float):
            if math.isnan(b) or math.isinf(b):
                # comparisons with an infinity or nan should behave in
                # the same way for any finite a, so treat a as zero.
                return 0.0 == b
            else:
                return a == a.from_float(b)
        else:
            # Since a doesn't know how to compare with b, let's give b
            # a chance to compare itself with a.
            return NotImplemented 
Example 50
Project: ndk-python   Author: gittor   File: fractions.py    (license) View Source Project 6 votes vote down vote up
def _richcmp(self, other, op):
        """Helper for comparison operators, for internal use only.

        Implement comparison between a Rational instance `self`, and
        either another Rational instance or a float `other`.  If
        `other` is not a Rational instance or a float, return
        NotImplemented. `op` should be one of the six standard
        comparison operators.

        """
        # convert other to a Rational instance where reasonable.
        if isinstance(other, Rational):
            return op(self._numerator * other.denominator,
                      self._denominator * other.numerator)
        # comparisons with complex should raise a TypeError, for consistency
        # with int<->complex, float<->complex, and complex<->complex comparisons.
        if isinstance(other, complex):
            raise TypeError("no ordering relation is defined for complex numbers")
        if isinstance(other, float):
            if math.isnan(other) or math.isinf(other):
                return op(0.0, other)
            else:
                return op(self, self.from_float(other))
        else:
            return NotImplemented