Python math.isfinite() Examples
The following are 30
code examples of math.isfinite().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
math
, or try the search function
.
Example #1
Source File: distributions.py From Neuraxle with Apache License 2.0 | 7 votes |
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 #2
Source File: _canonicalise.py From hypothesis-jsonschema with Mozilla Public License 2.0 | 6 votes |
def iterencode(self, o: Any, _one_shot: bool = False) -> Any: """Replace a stdlib method, so we encode integer-valued floats as ints.""" def floatstr(o: float) -> str: # This is the bit we're overriding - integer-valued floats are # encoded as integers, to support JSONschemas's uniqueness. assert math.isfinite(o) if o == int(o): return repr(int(o)) return repr(o) return _make_iterencode( {}, self.default, encode_basestring_ascii, self.indent, floatstr, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, _one_shot, )(o, 0)
Example #3
Source File: compiler.py From ibis with Apache License 2.0 | 6 votes |
def _number_literal_format(translator, expr): value = expr.op().value if math.isfinite(value): formatted = repr(value) else: if math.isnan(value): formatted_val = 'NaN' elif math.isinf(value): if value > 0: formatted_val = 'Infinity' else: formatted_val = '-Infinity' formatted = "CAST({!r} AS DOUBLE)".format(formatted_val) return formatted
Example #4
Source File: compiler.py From ibis with Apache License 2.0 | 6 votes |
def _number_literal_format(translator, expr): value = expr.op().value if math.isfinite(value): # Spark interprets dotted number literals as decimals, not floats. # i.e. "select 1.0 as tmp" is a decimal(2,1), not a float or double if isinstance(expr.op().dtype, dt.Float64): formatted = "{}d".format(repr(value)) elif isinstance(expr.op().dtype, dt.Floating): formatted = "CAST({} AS FLOAT)".format(repr(value)) else: formatted = repr(value) else: if math.isnan(value): formatted_val = 'NaN' elif math.isinf(value): if value > 0: formatted_val = 'Infinity' else: formatted_val = '-Infinity' formatted = "CAST({!r} AS DOUBLE)".format(formatted_val) return formatted
Example #5
Source File: boolean.py From tartiflette with MIT License | 6 votes |
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 #6
Source File: defuzzifier.py From pyfuzzylite with GNU Affero General Public License v3.0 | 6 votes |
def defuzzify(self, term: Term, minimum: float, maximum: float) -> float: if not math.isfinite(minimum + maximum): return nan resolution = self.resolution dx = (maximum - minimum) / resolution counter = resolution left = right = 0 x_left, x_right = (minimum, maximum) left_area = right_area = 0.0 # TODO: Improve? while counter > 0: counter = counter - 1 if left_area <= right_area: x_left = minimum + (left + 0.5) * dx left_area += term.membership(x_left) left += 1 else: x_right = maximum - (right + 0.5) * dx right_area += term.membership(x_right) right += 1 # Inverse weighted average to compensate return (left_area * x_right + right_area * x_left) / (left_area + right_area)
Example #7
Source File: float.py From tartiflette with MIT License | 6 votes |
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 #8
Source File: defuzzifier.py From pyfuzzylite with GNU Affero General Public License v3.0 | 6 votes |
def defuzzify(self, term: Term, minimum: float, maximum: float) -> float: if not math.isfinite(minimum + maximum): return nan resolution = self.resolution dx = (maximum - minimum) / resolution y_max = -math.inf x_smallest = minimum x_largest = maximum find_x_largest = False for i in range(0, resolution): x = minimum + (i + 0.5) * dx y = term.membership(x) if Op.gt(y, y_max): y_max = y x_smallest = x x_largest = x find_x_largest = True elif find_x_largest and Op.eq(y, y_max): x_largest = x elif Op.lt(y, y_max): find_x_largest = False return (x_largest + x_smallest) / 2.0
Example #9
Source File: test_object.py From pikepdf with Mozilla Public License 2.0 | 6 votes |
def test_decimal_from_float(f): d = Decimal(f) if isfinite(f) and d.is_finite(): try: # PDF is limited to ~5 sig figs decstr = str(d.quantize(Decimal('1.000000'))) except InvalidOperation: return # PDF doesn't support exponential notation try: py_d = Object.parse(decstr) except RuntimeError as e: if 'overflow' in str(e) or 'underflow' in str(e): py_d = Object.parse(str(f)) assert isclose(py_d, d, abs_tol=1e-5), (d, f.hex()) else: with pytest.raises(PdfError): Object.parse(str(d))
Example #10
Source File: chaikin_oscillator.py From bfx-hf-indicators-py with Apache License 2.0 | 6 votes |
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
Source File: chaikin_oscillator.py From bfx-hf-indicators-py with Apache License 2.0 | 6 votes |
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
Source File: acceleration.py From bfx-hf-indicators-py with Apache License 2.0 | 6 votes |
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
Source File: macd.py From bfx-hf-indicators-py with Apache License 2.0 | 6 votes |
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
Source File: distributions.py From Neuraxle with Apache License 2.0 | 6 votes |
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 #15
Source File: float.py From tartiflette with MIT License | 6 votes |
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 #16
Source File: test_backtest.py From gluon-ts with Apache License 2.0 | 6 votes |
def test_forecast_parser(): # verify that logged for estimator, datasets and metrics can be recovered # from their string representation dataset_info, train_ds, test_ds = constant_dataset() estimator = make_estimator( dataset_info.metadata.freq, dataset_info.prediction_length ) assert repr(estimator) == repr(load_code(repr(estimator))) stats = calculate_dataset_statistics(train_ds) assert stats == eval( repr(stats), globals(), {"gluonts": gluonts} ) # TODO: use load evaluator = Evaluator(quantiles=[0.1, 0.5, 0.9]) agg_metrics, _ = backtest_metrics(train_ds, test_ds, estimator, evaluator) # reset infinite metrics to 0 (otherwise the assertion below fails) for key, val in agg_metrics.items(): if not math.isfinite(val): agg_metrics[key] = 0.0 assert agg_metrics == load_code(dump_code(agg_metrics))
Example #17
Source File: distributed_fused_adam.py From apex with BSD 3-Clause "New" or "Revised" License | 6 votes |
def revert_step(self): """Revert effect of previously calling partial_step. """ # Call undo kernel once per step combined_scale = self._global_scale if self._param_group['max_grad_norm'] > 0 and math.isfinite(self.L2_grad_norm): combined_scale = self._param_group['max_grad_norm'] / (self.L2_grad_norm / self._global_scale + 1e-6) combined_scale = self._global_scale / min(1, combined_scale) bias_correction = 1 if self._param_group['bias_correction'] else 0 beta1, beta2 = self._param_group['betas'] fused_adam_cuda.maybe_adam_undo( torch.empty([0]), self._fp32_p, self._fp32_m, self._fp32_v, self._fp16_g, self._param_group['lr'], beta1, beta2, self._param_group['eps'], combined_scale, self._param_state['step']+1, self.eps_mode, bias_correction, self._param_group['weight_decay'])
Example #18
Source File: distributed_fused_adam.py From apex with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __launch_step_kernel(self, p, p_copy, m, v, g): combined_scale = self._global_scale if self._param_group['max_grad_norm'] > 0 and math.isfinite(self.L2_grad_norm): combined_scale = self._param_group['max_grad_norm'] / (self.L2_grad_norm / self._global_scale + 1e-6) combined_scale = self._global_scale / min(1, combined_scale) bias_correction = 1 if self._param_group['bias_correction'] else 0 beta1, beta2 = self._param_group['betas'] fused_adam_cuda.reversible_adam( p, p_copy, m, v, g, self._param_group['lr'], beta1, beta2, self._param_group['eps'], combined_scale, self._param_state['step']+1, self.eps_mode, bias_correction, self._param_group['weight_decay'])
Example #19
Source File: distributed_fused_adam_v2.py From apex with BSD 3-Clause "New" or "Revised" License | 6 votes |
def revert_step(self): """Revert effect of previously calling partial_step. """ # Call undo kernel once per step combined_scale = self._global_scale if self._param_group['max_grad_norm'] > 0 and math.isfinite(self.L2_grad_norm): combined_scale = self._param_group['max_grad_norm'] / (self.L2_grad_norm / self._global_scale + 1e-6) combined_scale = self._global_scale / min(1, combined_scale) bias_correction = 1 if self._param_group['bias_correction'] else 0 beta1, beta2 = self._param_group['betas'] fused_adam_cuda.maybe_adam_undo( torch.empty([0]), self._fp32_p, self._fp32_m, self._fp32_v, self._fp16_g, self._param_group['lr'], beta1, beta2, self._param_group['eps'], combined_scale, self._param_state['step']+1, self.eps_mode, bias_correction, self._param_group['weight_decay'])
Example #20
Source File: distributed_fused_adam_v2.py From apex with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __launch_step_kernel(self, p, p_copy, m, v, g): combined_scale = self._global_scale if self._param_group['max_grad_norm'] > 0 and math.isfinite(self.L2_grad_norm): combined_scale = self._param_group['max_grad_norm'] / (self.L2_grad_norm / self._global_scale + 1e-6) combined_scale = self._global_scale / min(1, combined_scale) bias_correction = 1 if self._param_group['bias_correction'] else 0 beta1, beta2 = self._param_group['betas'] fused_adam_cuda.reversible_adam( p, p_copy, m, v, g, self._param_group['lr'], beta1, beta2, self._param_group['eps'], combined_scale, self._param_state['step']+1, self.eps_mode, bias_correction, self._param_group['weight_decay'])
Example #21
Source File: test.py From oj with MIT License | 6 votes |
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 #22
Source File: point.py From influxdb-client-python with MIT License | 6 votes |
def _append_fields(fields): _return = [] for field, value in sorted(iteritems(fields)): if value is None: continue if isinstance(value, float) or isinstance(value, Decimal): if not math.isfinite(value): continue _return.append(f'{_escape_key(field)}={str(value)}') elif isinstance(value, int) and not isinstance(value, bool): _return.append(f'{_escape_key(field)}={str(value)}i') elif isinstance(value, bool): _return.append(f'{_escape_key(field)}={str(value).lower()}') elif isinstance(value, str): _return.append(f'{_escape_key(field)}="{_escape_string(value)}"') else: raise ValueError() return f"{','.join(_return)}"
Example #23
Source File: evaluate.py From tg2019task with MIT License | 6 votes |
def mean_average_precision_score(gold, pred, callback=None): total, count = 0., 0 for question in gold.values(): if question.id in pred: ranks = compute_ranks(list(question.explanations), pred[question.id]) score = average_precision(ranks) if not math.isfinite(score): score = 0. total += score count += 1 if callback: callback(question.id, score) mean_ap = total / count if count > 0 else 0. return mean_ap
Example #24
Source File: algorithms.py From archipack with GNU General Public License v3.0 | 6 votes |
def intersection(p1, p2, q1, q2, ret): px = p1.y - p2.y py = p2.x - p1.x pw = p1.x * p2.y - p2.x * p1.y qx = q1.y - q2.y qy = q2.x - q1.x qw = q1.x * q2.y - q2.x * q1.y x = py * qw - qy * pw y = qx * pw - px * qw w = px * qy - qx * py xInt = x / w yInt = y / w if not isfinite(xInt) or not isfinite(yInt): raise ArithmeticError() ret.x, ret.y = xInt, yInt
Example #25
Source File: relative_volatility_index.py From bfx-hf-indicators-py with Apache License 2.0 | 6 votes |
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 #26
Source File: test_cmath.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
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 #27
Source File: test_math.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
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 #28
Source File: is_finite.py From graphql-core with MIT License | 5 votes |
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 #29
Source File: fields.py From bioforum with MIT License | 5 votes |
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 #30
Source File: statistics.py From odoo13-x64 with GNU General Public License v3.0 | 5 votes |
def _isfinite(x): try: return x.is_finite() # Likely a Decimal. except AttributeError: return math.isfinite(x) # Coerces to float first.