Python math.isnan() Examples
The following are 30
code examples of math.isnan().
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: fractions.py From jawfish with MIT License | 6 votes |
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 #2
Source File: testParse.py From hadrian with Apache License 2.0 | 6 votes |
def testParseDouble(self): engine, = PFAEngine.fromYaml(''' input: string output: double action: {parse.double: input} ''') self.assertEqual(engine.action(" 123 "), 123.0) self.assertEqual(engine.action(" -123 "), -123.0) self.assertEqual(engine.action(" 1.7976931348623157e308 "), 1.7976931348623157e308) self.assertEqual(engine.action(" -1.7976931348623157e308 "), -1.7976931348623157e308) self.assertEqual(engine.action(" 1.7976931348623159e308 "), float("inf")) self.assertEqual(engine.action(" -1.7976931348623159e308 "), float("-inf")) self.assertEqual(engine.action(" 4.9e-324 "), 4.9e-324) self.assertEqual(engine.action(" -4.9e-324 "), -4.9e-324) self.assertEqual(engine.action(" 1e-324 "), 0.0) self.assertEqual(engine.action(" 1e-324 "), 0.0) self.assertTrue(math.isnan(engine.action(" nAN "))) self.assertEqual(engine.action(" inf "), float("inf")) self.assertEqual(engine.action(" +inf "), float("inf")) self.assertEqual(engine.action(" -inf "), float("-inf"))
Example #3
Source File: testParse.py From hadrian with Apache License 2.0 | 6 votes |
def testParseFloat(self): engine, = PFAEngine.fromYaml(''' input: string output: float action: {parse.float: input} ''') self.assertEqual(engine.action(" 123 "), 123.0) self.assertEqual(engine.action(" -123 "), -123.0) self.assertEqual(engine.action(" 3.4028234e38 "), 3.4028234e38) self.assertEqual(engine.action(" -3.4028234e38 "), -3.4028234e38) self.assertEqual(engine.action(" 3.4028236e38 "), float("inf")) self.assertEqual(engine.action(" -3.4028236e38 "), float("-inf")) self.assertEqual(engine.action(" 1.4e-45 "), 1.4e-45) self.assertEqual(engine.action(" -1.4e-45 "), -1.4e-45) self.assertEqual(engine.action(" 1e-46 "), 0.0) self.assertEqual(engine.action(" -1e-46 "), 0.0) self.assertTrue(math.isnan(engine.action(" nAN "))) self.assertEqual(engine.action(" inf "), float("inf")) self.assertEqual(engine.action(" +inf "), float("inf")) self.assertEqual(engine.action(" -inf "), float("-inf"))
Example #4
Source File: dial-gauge.py From kivy-smoothie-host with GNU General Public License v3.0 | 6 votes |
def draw_setpoint(self, *args): # draw a setpoint if self.setpoint_canvas: self.canvas.after.remove(self.setpoint_canvas) self.setpoint_canvas = None if math.isnan(self.setpoint_value) or math.isinf(self.setpoint_value): return v = self.value_to_angle(self.setpoint_value) length = self.dial_diameter / 2.0 - self.tic_length if not self.setpoint_length else self.setpoint_length self.setpoint_canvas = InstructionGroup() self.setpoint_canvas.add(PushMatrix()) self.setpoint_canvas.add(Color(*self.setpoint_color)) self.setpoint_canvas.add(Rotate(angle=v, axis=(0, 0, -1), origin=self.dial_center)) self.setpoint_canvas.add(Translate(self.dial_center[0], self.dial_center[1])) self.setpoint_canvas.add(Line(points=[0, 0, 0, length], width=self.setpoint_thickness, cap='none')) # self.setpoint_canvas.add(SmoothLine(points=[0, 0, 0, length], width=self.setpoint_thickness)) self.setpoint_canvas.add(PopMatrix()) self.canvas.after.add(self.setpoint_canvas)
Example #5
Source File: dist.py From hadrian with Apache License 2.0 | 6 votes |
def __call__(self, state, scope, pos, paramTypes, x, size, prob): if math.isinf(prob) or math.isnan(prob) or size <= 0 or prob < 0 or prob > 1: raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos) elif math.isinf(x) or math.isnan(x): raise PFARuntimeException("invalid input", self.errcodeBase + 1, self.name, pos) elif x < 0: return 0.0 elif x >= size: return 1.0 elif prob == 1: if x < size: return 0.0 else: return 1.0 elif prob == 0: return 1.0 else: return BinomialDistribution(size, prob, self.errcodeBase + 0, self.name, pos).CDF(x)
Example #6
Source File: interp.py From hadrian with Apache License 2.0 | 6 votes |
def __call__(self, state, scope, pos, paramTypes, x, *args): if len(args) == 3: numbins, low, high = args if low >= high or math.isnan(low) or math.isnan(high): raise PFARuntimeException("bad histogram range", self.errcodeBase + 0, self.name, pos) if numbins < 1: raise PFARuntimeException("bad histogram scale", self.errcodeBase + 1, self.name, pos) if math.isnan(x) or x < low or x >= high: raise PFARuntimeException("x out of range", self.errcodeBase + 2, self.name, pos) out = int(math.floor(numbins * div((x - low), (high - low)))) if out < 0 or out >= numbins: raise PFARuntimeException("x out of range", self.errcodeBase + 2, self.name, pos) return out else: origin, width = args if math.isnan(origin) or math.isinf(origin): raise PFARuntimeException("bad histogram range", self.errcodeBase + 0, self.name, pos) if width <= 0.0 or math.isnan(width): raise PFARuntimeException("bad histogram scale", self.errcodeBase + 1, self.name, pos) if math.isnan(x) or math.isinf(x): raise PFARuntimeException("x out of range", self.errcodeBase + 2, self.name, pos) else: return int(math.floor(div((x - origin), width)))
Example #7
Source File: array.py From hadrian with Apache License 2.0 | 6 votes |
def __call__(self, state, scope, pos, paramTypes, a, p): if len(a) == 0: raise PFARuntimeException("empty array", self.errcodeBase + 0, self.name, pos) if math.isnan(p): raise PFARuntimeException("p not a number", self.errcodeBase + 1, self.name, pos) if p <= 0.0: return lowestN(a, 1, lambda x, y: compare(jsonNodeToAvroType(paramTypes[0]).items, x, y) < 0)[0] if p >= 1.0: return highestN(a, 1, lambda x, y: compare(jsonNodeToAvroType(paramTypes[0]).items, x, y) < 0)[0] sa = sorted(a, lambda x, y: compare(jsonNodeToAvroType(paramTypes[0]).items, x, y)) k = (len(a) - 1.0)*p f = math.floor(k) dataType = paramTypes[-1] if (dataType is "float") or (dataType is "double"): c = math.ceil(k) if f == c: return sa[int(k)] d0 = sa[int(f)] * (c - k) d1 = sa[int(c)] * (k - f) return d0 + d1 else: if len(sa) % 2 == 1: return sa[int(f)] else: return sa[int(k)]
Example #8
Source File: core.py From hadrian with Apache License 2.0 | 6 votes |
def __call__(self, state, scope, pos, paramTypes, x, y): if y == 0: if paramTypes[-1] == "int" or paramTypes[-1] == "long": raise PFARuntimeException("integer division by zero", self.errcodeBase + 0, self.name, pos) else: return float("nan") else: if not math.isnan(x) and not math.isinf(x) and math.isinf(y): return x else: out = x % y if x < 0 and out > 0: return out - abs(y) elif x > 0 and out < 0: return out + abs(y) else: return out
Example #9
Source File: pfatest.py From hadrian with Apache License 2.0 | 6 votes |
def __call__(self, state, scope, pos, paramTypes, state_): chi2 = state_["chi2"] dof = state_["dof"] if dof < 0: raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos) elif dof == 0: if chi2 > 0: return 1.0 else: return 0.0 elif math.isnan(chi2): return float("nan") elif math.isinf(chi2): if chi2 > 0: return 1.0 else: return 0.0 else: return float(Chi2Distribution(dof, self.errcodeBase + 0, self.name, pos).CDF(chi2))
Example #10
Source File: dist.py From hadrian with Apache License 2.0 | 6 votes |
def __call__(self, state, scope, pos, paramTypes, x, *others): if len(others) == 2: mu, sigma = others else: mu = others[0]["mean"] if math.isnan(others[0]["variance"]) or others[0]["variance"] < 0.0: raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos) else: sigma = math.sqrt(others[0]["variance"]) if math.isinf(mu) or math.isnan(mu) or math.isinf(sigma) or math.isnan(sigma) or sigma < 0.0: raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos) elif math.isinf(x) or math.isnan(x): raise PFARuntimeException("invalid input", self.errcodeBase + 1, self.name, pos) elif sigma == 0.0: if x != mu: return float("-inf") else: return float("inf") else: return GaussianDistribution(mu, sigma, self.errcodeBase + 0, self.name, pos).LL(x)
Example #11
Source File: dist.py From hadrian with Apache License 2.0 | 6 votes |
def __call__(self, state, scope, pos, paramTypes, x, *others): if len(others) == 2: mu, sigma = others else: mu = others[0]["mean"] if math.isnan(others[0]["variance"]) or others[0]["variance"] < 0.0: raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos) else: sigma = math.sqrt(others[0]["variance"]) if math.isinf(mu) or math.isnan(mu) or math.isinf(sigma) or math.isnan(sigma) or sigma < 0.0: raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos) elif math.isinf(x) or math.isnan(x): raise PFARuntimeException("invalid input", self.errcodeBase + 1, self.name, pos) elif sigma == 0.0: if x < mu: return 0.0 else: return 1.0 else: return GaussianDistribution(mu, sigma, self.errcodeBase + 0, self.name, pos).CDF(x)
Example #12
Source File: fractions.py From jawfish with MIT License | 6 votes |
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 #13
Source File: fractions.py From jawfish with MIT License | 6 votes |
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 #14
Source File: dist.py From hadrian with Apache License 2.0 | 6 votes |
def __call__(self, state, scope, pos, paramTypes, p, *others): if len(others) == 2: mu, sigma = others else: mu = others[0]["mean"] if math.isnan(others[0]["variance"]) or others[0]["variance"] < 0.0: raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos) else: sigma = math.sqrt(others[0]["variance"]) if math.isinf(mu) or math.isnan(mu) or math.isinf(sigma) or math.isnan(sigma) or sigma < 0.0: raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos) elif not (0.0 <= p <= 1.0): raise PFARuntimeException("invalid input", self.errcodeBase + 1, self.name, pos) elif p == 1.0: return float("inf") elif p == 0.0: return float("-inf") elif sigma == 0.0: return mu else: return GaussianDistribution(mu, sigma, self.errcodeBase + 0, self.name, pos).QF(p)
Example #15
Source File: solver.py From End-to-end-ASR-Pytorch with MIT License | 6 votes |
def write_log(self, log_name, log_dict): ''' Write log to TensorBoard log_name - <str> Name of tensorboard variable log_value - <dict>/<array> Value of variable (e.g. dict of losses), passed if value = None ''' if type(log_dict) is dict: log_dict = {key: val for key, val in log_dict.items() if ( val is not None and not math.isnan(val))} if log_dict is None: pass elif len(log_dict) > 0: if 'align' in log_name or 'spec' in log_name: img, form = log_dict self.log.add_image( log_name, img, global_step=self.step, dataformats=form) elif 'text' in log_name or 'hyp' in log_name: self.log.add_text(log_name, log_dict, self.step) else: self.log.add_scalars(log_name, log_dict, self.step)
Example #16
Source File: solver.py From End-to-end-ASR-Pytorch with MIT License | 6 votes |
def backward(self, loss): ''' Standard backward step with self.timer and debugger Arguments loss - the loss to perform loss.backward() ''' self.timer.set() loss.backward() grad_norm = torch.nn.utils.clip_grad_norm_( self.model.parameters(), self.GRAD_CLIP) if math.isnan(grad_norm): self.verbose('Error : grad norm is NaN @ step '+str(self.step)) else: self.optimizer.step() self.timer.cnt('bw') return grad_norm
Example #17
Source File: utils.py From DOTA_models with Apache License 2.0 | 6 votes |
def GenerateBinomialTable(m): """Generate binomial table. Args: m: the size of the table. Returns: A two dimensional array T where T[i][j] = (i choose j), for 0<= i, j <=m. """ table = numpy.zeros((m + 1, m + 1), dtype=numpy.float64) for i in range(m + 1): table[i, 0] = 1 for i in range(1, m + 1): for j in range(1, m + 1): v = table[i - 1, j] + table[i - 1, j -1] assert not math.isnan(v) and not math.isinf(v) table[i, j] = v return tf.convert_to_tensor(table)
Example #18
Source File: gaussian_moments.py From DOTA_models with Apache License 2.0 | 6 votes |
def _compute_delta(log_moments, eps): """Compute delta for given log_moments and eps. Args: log_moments: the log moments of privacy loss, in the form of pairs of (moment_order, log_moment) eps: the target epsilon. Returns: delta """ min_delta = 1.0 for moment_order, log_moment in log_moments: if moment_order == 0: continue if math.isinf(log_moment) or math.isnan(log_moment): sys.stderr.write("The %d-th order is inf or Nan\n" % moment_order) continue if log_moment < moment_order * eps: min_delta = min(min_delta, math.exp(log_moment - moment_order * eps)) return min_delta
Example #19
Source File: parse.py From hadrian with Apache License 2.0 | 6 votes |
def __call__(self, state, scope, pos, paramTypes, str): try: out = float(str) except ValueError: raise PFARuntimeException("not a double-precision float", self.errcodeBase + 0, self.name, pos) if math.isnan(out): return out elif math.isinf(out): return out elif out > DOUBLE_MAX_VALUE: return float("inf") elif -out > DOUBLE_MAX_VALUE: return float("-inf") elif abs(out) < DOUBLE_MIN_VALUE: return 0.0 else: return out
Example #20
Source File: accountant.py From DOTA_models with Apache License 2.0 | 6 votes |
def _compute_delta(self, log_moments, eps): """Compute delta for given log_moments and eps. Args: log_moments: the log moments of privacy loss, in the form of pairs of (moment_order, log_moment) eps: the target epsilon. Returns: delta """ min_delta = 1.0 for moment_order, log_moment in log_moments: if math.isinf(log_moment) or math.isnan(log_moment): sys.stderr.write("The %d-th order is inf or Nan\n" % moment_order) continue if log_moment < moment_order * eps: min_delta = min(min_delta, math.exp(log_moment - moment_order * eps)) return min_delta
Example #21
Source File: parse.py From hadrian with Apache License 2.0 | 6 votes |
def __call__(self, state, scope, pos, paramTypes, str): try: out = float(str) except ValueError: raise PFARuntimeException("not a single-precision float", self.errcodeBase + 0, self.name, pos) if math.isnan(out): return out elif math.isinf(out): return out elif out > FLOAT_MAX_VALUE: return float("inf") elif -out > FLOAT_MAX_VALUE: return float("-inf") elif abs(out) < FLOAT_MIN_VALUE: return 0.0 else: return out
Example #22
Source File: dns_oa.py From incubator-spot with Apache License 2.0 | 6 votes |
def _ingest_summary(self): # get date parameters. yr = self._date[:4] mn = self._date[4:6] dy = self._date[6:] self._logger.info("Getting ingest summary data for the day") ingest_summary_cols = ["date","total"] result_rows = [] df_filtered = pd.DataFrame() query_to_load = (""" SELECT frame_time, COUNT(*) as total FROM {0}.{1} WHERE y={2} AND m={3} AND d={4} AND unix_tstamp IS NOT NULL AND frame_time IS NOT NULL AND frame_len IS NOT NULL AND dns_qry_name IS NOT NULL AND ip_src IS NOT NULL AND (dns_qry_class IS NOT NULL AND dns_qry_type IS NOT NULL AND dns_qry_rcode IS NOT NULL ) GROUP BY frame_time; """).format(self._db,self._table_name, yr, mn, dy) results = impala.execute_query_as_list(query_to_load) df = pd.DataFrame(results) # Forms a new dataframe splitting the minutes from the time column df_new = pd.DataFrame([["{0}-{1}-{2} {3}:{4}".format(yr, mn, dy,\ val['frame_time'].replace(" "," ").split(" ")[3].split(":")[0].zfill(2),\ val['frame_time'].replace(" "," ").split(" ")[3].split(":")[1].zfill(2)),\ int(val['total']) if not math.isnan(val['total']) else 0 ] for key,val in df.iterrows()],columns = ingest_summary_cols) #Groups the data by minute sf = df_new.groupby(by=['date'])['total'].sum() df_per_min = pd.DataFrame({'date':sf.index, 'total':sf.values}) df_final = df_filtered.append(df_per_min, ignore_index=True).to_records(False,False) if len(df_final) > 0: query_to_insert=(""" INSERT INTO {0}.dns_ingest_summary PARTITION (y={1}, m={2}, d={3}) VALUES {4}; """).format(self._db, yr, mn, dy, tuple(df_final)) impala.execute_query(query_to_insert)
Example #23
Source File: cast.py From hadrian with Apache License 2.0 | 5 votes |
def __call__(self, state, scope, pos, paramTypes, x): try: if isinstance(x, float): if math.isnan(x): raise OverflowError else: out = int(math.floor(x + 0.5)) else: out = x if LONG_MIN_VALUE <= out <= LONG_MAX_VALUE: return out else: raise OverflowError except OverflowError: raise PFARuntimeException("long overflow", self.errcodeBase + 0, self.name, pos)
Example #24
Source File: dist.py From hadrian with Apache License 2.0 | 5 votes |
def __call__(self, state, scope, pos, paramTypes, x, shape, scale): if math.isinf(shape) or math.isnan(shape) or math.isinf(scale) or math.isnan(scale) or shape < 0 or scale < 0: raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos) elif math.isinf(x) or math.isnan(x): raise PFARuntimeException("invalid input", self.errcodeBase + 1, self.name, pos) elif shape == 0 or scale == 0: if x != 0: return 1.0 else: return 0.0 elif x < 0: return 0.0 else: return GammaDistribution(shape, scale, self.errcodeBase + 0, self.name, pos).CDF(x)
Example #25
Source File: dist.py From hadrian with Apache License 2.0 | 5 votes |
def __call__(self, state, scope, pos, paramTypes, p, lamda): if math.isinf(lamda) or math.isnan(lamda) or lamda < 0: raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos) elif not (0.0 <= p <= 1.0): raise PFARuntimeException("invalid input", self.errcodeBase + 1, self.name, pos) elif lamda == 0: return 0.0 elif p == 1: return float("inf") elif p == 0: return 0.0 else: return PoissonDistribution(lamda, self.errcodeBase + 0, self.name, pos).QF(p)
Example #26
Source File: dist.py From hadrian with Apache License 2.0 | 5 votes |
def __call__(self, state, scope, pos, paramTypes, p, location, scale): if math.isinf(location) or math.isnan(location) or math.isinf(scale) or math.isnan(scale) or scale <= 0: raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos) elif not (0.0 <= p <= 1.0): raise PFARuntimeException("invalid input", self.errcodeBase + 1, self.name, pos) elif p == 1: return float("inf") elif p == 0: return float("-inf") else: return CauchyDistribution(location, scale, self.errcodeBase + 0, self.name, pos).QF(p)
Example #27
Source File: dist.py From hadrian with Apache License 2.0 | 5 votes |
def __call__(self, state, scope, pos, paramTypes, x, lamda): if math.isinf(lamda) or math.isnan(lamda) or lamda < 0: raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos) elif math.isinf(x) or math.isnan(x): raise PFARuntimeException("invalid input", self.errcodeBase + 1, self.name, pos) elif lamda == 0: if x >= 0: return 1.0 else: return 0.0 else: return PoissonDistribution(lamda, self.errcodeBase + 0, self.name, pos).CDF(x)
Example #28
Source File: dist.py From hadrian with Apache License 2.0 | 5 votes |
def __call__(self, state, scope, pos, paramTypes, p, shape1, shape2): if math.isinf(shape1) or math.isnan(shape1) or math.isinf(shape2) or math.isnan(shape2) or shape1 <= 0 or shape2 <= 0: raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos) elif not (0.0 <= p <= 1.0): raise PFARuntimeException("invalid input", self.errcodeBase + 1, self.name, pos) elif p == 1: return 1.0 elif p == 0: return 0.0 else: return BetaDistribution(shape1, shape2, self.errcodeBase + 0, self.name, pos).QF(p)
Example #29
Source File: dist.py From hadrian with Apache License 2.0 | 5 votes |
def __call__(self, state, scope, pos, paramTypes, x, location, scale): if math.isinf(location) or math.isnan(location) or math.isinf(scale) or math.isnan(scale) or scale <= 0: raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos) elif math.isinf(x) or math.isnan(x): raise PFARuntimeException("invalid input", self.errcodeBase + 1, self.name, pos) else: return CauchyDistribution(location, scale, self.errcodeBase + 0, self.name, pos).CDF(x)
Example #30
Source File: dist.py From hadrian with Apache License 2.0 | 5 votes |
def __call__(self, state, scope, pos, paramTypes, x, lamda): if math.isinf(lamda) or math.isnan(lamda) or lamda < 0.0: raise PFARuntimeException("invalid parameterization", self.errcodeBase + 0, self.name, pos) elif lamda == 0: if x != 0: return 0.0 else: return 1.0 elif x < 0: return 0.0 else: return PoissonDistribution(lamda, self.errcodeBase + 0, self.name, pos).PDF(x)