本文整理汇总了Python中math.isfinite函数的典型用法代码示例。如果您正苦于以下问题:Python isfinite函数的具体用法?Python isfinite怎么用?Python isfinite使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了isfinite函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: exp
def exp(x):
z = _make_complex(x)
exp_special = [
[0+0j, None, complex(0, -0.0), 0+0j, None, 0+0j, 0+0j],
[nan+nanj, None, None, None, None, nan+nanj, nan+nanj],
[nan+nanj, None, 1-0j, 1+0j, None, nan+nanj, nan+nanj],
[nan+nanj, None, 1-0j, 1+0j, None, nan+nanj, nan+nanj],
[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, complex(float("nan"), -0.0), nan, nan+nanj, nan+nanj, nan+nanj]
]
if not isfinite(z):
if math.isinf(z.real) and math.isfinite(z.imag) and z.imag != 0:
if z.real > 0:
ret = complex(math.copysign(inf, math.cos(z.imag)),
math.copysign(inf, math.sin(z.imag)))
else:
ret = complex(math.copysign(0, math.cos(z.imag)),
math.copysign(0, math.sin(z.imag)))
else:
ret = exp_special[_special_type(z.real)][_special_type(z.imag)]
if math.isinf(z.imag) and (math.isfinite(z.real) or
(math.isinf(z.real) and z.real > 0)):
raise ValueError
return ret
if z.real > _LOG_LARGE_DOUBLE:
ret = e * rect(math.exp(z.real - 1), z.imag)
else:
ret = rect(math.exp(z.real), z.imag)
if math.isinf(ret.real) or math.isinf(ret.imag):
raise OverflowError
return ret
开发者ID:pombredanne,项目名称:ouroboros,代码行数:35,代码来源:cmath.py
示例2: test_isfinite
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))
开发者ID:Connor124,项目名称:Gran-Theft-Crop-Toe,代码行数:8,代码来源:test_cmath.py
示例3: test_my_sum_floats
def test_my_sum_floats(x, y):
print(x, y)
# math.isfinite was introduced in python 3.2
if sys.version_info[0:3] > (3, 2, 0):
assume(math.isfinite(x))
assume(math.isfinite(y))
else:
assume(not math.isnan(x) and not math.isinf(x))
assume(not math.isnan(y) and not math.isinf(y))
assert x + y == mysum(x, y)
开发者ID:fangohr,项目名称:travisci,代码行数:11,代码来源:test_code_fuzzy.py
示例4: test_isfinite
def test_isfinite(self):
import cmath
import math
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)
assert cmath.isfinite(z) == (math.isfinite(x) and math.isfinite(y))
开发者ID:Qointum,项目名称:pypy,代码行数:11,代码来源:test_cmath.py
示例5: backfill
def backfill(self, mfilter, target=None):
self.log.debug('backfill([filter], %s)', util.timestr(target))
live = [
b for b in self.buffers.values()
if (not b.get('deferred', False)
and (('min_eid' not in b or 'have_eid' not in b)
or b['have_eid'] > b['min_eid']))]
if target is None:
target = min(b.get('have_eid', 0) for b in live) - 1
elif math.isfinite(target):
target = int(target * 1000000)
live = [b for b in live if b.get('have_eid', 0) > target]
t0 = time.time()
nb = []
for task, when in self.backfillers:
if (t0 - when) > 30.0:
task.cancel()
if not task.done():
nb.append((task, when))
self.backfillers = nb
self.reap_tasks()
self.log.debug('%d backfillers active', len(self.backfillers))
if not self.backfillers:
for b in live:
t = asyncio.Task(self.backfill_buffer(b, target))
self.backfillers.append((t, t0))
self.tasks.append(t)
开发者ID:kcr,项目名称:snipe,代码行数:27,代码来源:irccloud.py
示例6: read_error
def read_error(data, attribute_name):
if hasattr(data, attribute_name):
attr = getattr(data, attribute_name)
if not isnan(attr) and isfinite(attr):
return attr
return SENSOR_ERROR_MAX
开发者ID:timdelbruegger,项目名称:freecopter,代码行数:7,代码来源:gps_state.py
示例7: sinh
def sinh(x):
_sinh_special = [
[inf+nanj, None, complex(-float("inf"), -0.0), -inf, None, inf+nanj, inf+nanj],
[nan+nanj, None, None, None, None, nan+nanj, nan+nanj],
[nanj, None, complex(-0.0, -0.0), complex(-0.0, 0.0), None, nanj, nanj],
[nanj, None, complex(0.0, -0.0), complex(0.0, 0.0), None, nanj, nanj],
[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, complex(float("nan"), -0.0), nan, nan+nanj, nan+nanj, nan+nanj]
]
z = _make_complex(x)
if not isfinite(z):
if math.isinf(z.imag) and not math.isnan(z.real):
raise ValueError
if math.isinf(z.real) and math.isfinite(z.imag) and z.imag != 0:
if z.real > 0:
return complex(math.copysign(inf, math.cos(z.imag)),
math.copysign(inf, math.sin(z.imag)))
return complex(-math.copysign(inf, math.cos(z.imag)),
math.copysign(inf, math.sin(z.imag)))
return _sinh_special[_special_type(z.real)][_special_type(z.imag)]
if abs(z.real) > _LOG_LARGE_DOUBLE:
x_minus_one = z.real - math.copysign(1, z.real)
return complex(math.cos(z.imag) * math.sinh(x_minus_one) * e,
math.sin(z.imag) * math.cosh(x_minus_one) * e)
return complex(math.cos(z.imag) * math.sinh(z.real),
math.sin(z.imag) * math.cosh(z.real))
开发者ID:pombredanne,项目名称:ouroboros,代码行数:31,代码来源:cmath.py
示例8: write
def write(self):
'''Finalize self to file. Totally overwrites old data with current data.'''
if not self._have_lock:
raise LockError("Can't use SequencesManager.write() without lock!")
# TODO: should these errors be (programmatically) distinguishable from
# unable-to-acquire-lock errors?
# ignore dropped seqs (HEAPENTRY)
out = [item[2] for item in self._heap if (isfinite(item[2]) and item[2] in self._data)]
# Find seqs that have been dropped from heap, they're just appended
# at the end, no heapifying
missing = set(self._data.keys()).difference(out)
out = [self._data[seq] for seq in out]
out.extend(self._data[seq] for seq in missing)
# TODO: This is effectively cleaning the heap. Should we actually save the cleaned heap?
# self._heap = _Heap(out) #(copies entire list)
outdict = {"aaData": out}
try:
outdict['resdatetime'] = self.resdatetime
except Exception:
pass
json_string = json.dumps(outdict, ensure_ascii=False, sort_keys=True).replace('],', '],\n') + '\n'
# sort_keys to get reproducible output for testing, ensure_ascii=False to allow fancy names
with open(self._jsonfile, 'w') as f:
f.write(json_string)
del json_string # Both outstrings generated here can be multiple megabytes each
if self._txtfile:
txt_string = ''.join(str(ali)+'\n' for ali in sorted(out, key=lambda ali: ali.seq) if ali.is_minimally_valid())
# we want to go easy on newly added seqs with invalid data
with open(self._txtfile, 'w') as f:
f.write(txt_string)
del txt_string
del out
开发者ID:dubslow,项目名称:MersenneForumAliquot,代码行数:35,代码来源:__init__.py
示例9: main
def main():
p = ArgumentParser()
p.add_argument('-N', type=int, default=[10001, 100001, 1000001], nargs='+')
p.add_argument('-Nrun', type=int, default=10)
p = p.parse_args()
times = {}
for N in p.N:
print('\nN=', N)
print('----------------')
t = benchmark_pisum(N, p.Nrun)
t = {k: v for k, v in t.items() if math.isfinite(v)}
times[N] = dict(sorted(t.items(), key=lambda x: x[1])) # Python >= 3.5
for k, v in t.items():
print(k, v)
if figure is not None and len(t) > 0:
ax = figure().gca()
for k, v in times.items():
ax.scatter(v.keys(), v.values(), label=str(k))
ax.set_title('PiSum, N={}'.format(p.N))
ax.set_ylabel('run time [sec.]')
ax.set_yscale('log')
ax.grid(True)
# ax.autoscale(True) # bug?
# leave nanmin/nanmax for where some iterations fail
ax.set_ylim((0.1*np.nanmin(list(times[min(p.N)].values())),
10*np.nanmax(list(times[max(p.N)].values()))))
ax.legend(loc='best')
show()
开发者ID:scienceopen,项目名称:python-performance,代码行数:33,代码来源:Pisum.py
示例10: is_finite
def is_finite(n):
"""Check if finite number"""
try:
a = float(n)
return math.isfinite(a)
except:
return False
开发者ID:vdhan,项目名称:RSA,代码行数:7,代码来源:An.py
示例11: backfill_buffer
def backfill_buffer(self, buf, target):
self.log.debug("backfill_buffer([%s %s], %s)", buf["bid"], buf.get("have_eid"), target)
try:
target = max(target, buf["have_eid"] - self.backfill_length * 1000000)
oob_data = yield from self._request(
"GET",
urllib.parse.urljoin(IRCCLOUD_API, "/chat/backlog"),
params={"cid", buf["cid"], "bid", buf["bid"], "num", 256, "beforeid", buf["have_eid"] - 1},
headers={"Cookie": "session=%s" % self.session},
compress="gzip",
)
included = []
if isinstance(oob_data, dict):
raise Exception(str(oob_data))
oldest = buf["have_eid"]
self.log.debug("t = %f", oldest / 1000000)
for m in oob_data:
if m["bid"] == -1:
self.log.error("? %s", repr(m))
continue
yield from self.process_message(included, m)
included.sort()
self.log.debug("processed %d messages", len(included))
clip = None
included.reverse()
for i, m in enumerate(included):
if m.data["eid"] >= oldest:
clip = i
self.log.debug("BETRAYAL %d %f %s", i, m.data["eid"] / 1000000, repr(m.data))
if clip is not None:
included = included[clip + 1 :]
included.reverse()
if included:
self.log.debug("merging %d messages", len(included))
l = len(self.messages)
self.messages = list(messages.merge([self.messages, included]))
self.log.debug("len(self.messages): %d -> %d", l, len(self.messages))
self.drop_cache()
self.redisplay(included[0], included[-1])
except asyncio.CancelledError:
return
except:
self.log.exception("backfilling %s", buf)
return
if (
math.isfinite(target)
and target < buf["have_eid"]
and ("min_eid" not in buf or buf["have_eid"] > buf["min_eid"])
):
yield from asyncio.sleep(0.1)
yield from self.backfill_buffer(buf, target)
开发者ID:kcr,项目名称:snipe,代码行数:60,代码来源:irccloud.py
示例12: _exact_ratio
def _exact_ratio(x):
"""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 = "can't convert type '{}' to numerator/denominator"
#Modified by SciDB, Inc., to remove "from None" that did not work on Python 2.
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)
开发者ID:cerbo,项目名称:scidb,代码行数:33,代码来源:statistics.py
示例13: _exact_ratio
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__))
开发者ID:Logotrop,项目名称:trida,代码行数:34,代码来源:statistics.py
示例14: ztest_maximum_win_deviation
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
开发者ID:feihujiang,项目名称:sawtooth-core,代码行数:27,代码来源:poet_settings_view.py
示例15: __init__
def __init__(self, n_cluster=2, max_iter=1000, n_init=10,
distance_func=lambda x, y: np.linalg.norm(x-y)):
# set number of clusters
if isinstance(n_cluster, int) and n_cluster > 0:
self.n_cluster = n_cluster
else:
raise ValueError("number of clusters should be positive integer")
# set number of iterations
if (isinstance(max_iter, int) and max_iter > 0) or isfinite(max_iter):
self.max_iter = max_iter
else:
raise ValueError("max iteration should be positive integer")
# set number of init
if isinstance(n_init, int) and n_init > 0:
self.n_init = n_init
else:
raise ValueError("n_init should be positive integers")
# set distance function
if callable(distance_func):
self.distance_func = distance_func
else:
raise ValueError("distance function should be callable")
开发者ID:hjiang36,项目名称:Python-Learner,代码行数:25,代码来源:KMeans.py
示例16: __init__
def __init__(self, data):
# for debugging purposes
self.rawfix = data.fix
self.utc = data.utc
self.time = data.fix.time
self.num_satellites = len(data.satellites)
self.latitude = data.fix.latitude
self.longitude = data.fix.longitude
# Longitude error estimate in meters, 95% confidence.
# Present if mode is 2 or 3 and DOPs can be calculated from the satellite view.
self.longitude_error = read_error(data.fix, 'epx')
# Latitude error estimate in meters, 95% confidence.
# Present if mode is 2 or 3 and DOPs can be calculated from the satellite view.
self.latitude_error = read_error(data.fix, 'epy')
# Climb/sink error estimate in meters/sec, 95% confidence.
# altitude in meters
self.altitude = data.fix.altitude
if isnan(self.altitude) or not isfinite(self.altitude):
# just some value so that the calculation can continue
# this will have next to no influence because the expected error is so high in this situation
self.altitude = 50
# accuracy depends on number of satellites
# Estimated vertical error in meters, 95% confidence.
# Present if mode is 3 and DOPs can be calculated from the satellite view.
self.altitude_error = read_error(data.fix, 'epv')
# Speed over ground, meters per second.
self.speed = data.fix.speed
# Speed error estimate in meters/sec, 95% confidence.
self.speed_error = read_error(data.fix, 'eps')
# Climb (positive) or sink (negative) rate, meters per second.
self.climb = data.fix.climb
# Climb/sink error estimate in meters/sec, 95% confidence.
self.climb_error = read_error(data.fix, 'epc')
# Course over ground, degrees from true north.
self.track = data.fix.track
# Direction error estimate in degrees, 95% confidence.
self.track_error = read_error(data.fix, 'epd')
# NMEA mode: %d, 0=no mode value yet seen, 1=no fix, 2=2D, 3=3D.
self.rawmode = data.fix.mode
# flags for different modes
self.has_no_fix = data.fix.mode <= 1
self.has_2d_fix = data.fix.mode >= 2
self.has_3d_fix = data.fix.mode == 3
开发者ID:timdelbruegger,项目名称:freecopter,代码行数:60,代码来源:gps_state.py
示例17: min_str
def min_str(s, t):
if s == '' and t == '':
return ''
counter = Counter(t)
missing = set(counter.keys())
min_start = 0
min_end = float('inf')
cursor_end = 0
s_len = len(s)
for cursor_start, char in enumerate(s):
if missing:
try:
cursor_end = advance_window_end(counter, cursor_end, missing, s, s_len)
except StopIteration:
break
if not missing:
if (min_end - min_start) > (cursor_end - cursor_start):
min_start = cursor_start
min_end = cursor_end
if char in counter:
counter[char] += 1
if counter[char] == 1:
missing.add(char)
if math.isfinite(min_end):
return s[min_start:min_end]
raise Exception()
开发者ID:renzon,项目名称:code_interview_training,代码行数:30,代码来源:min_str_window.py
示例18: cubic_reparameterize
def cubic_reparameterize(
cubic: Cubic,
points_offset: Sequence[Vector],
points_offset_len: int,
u: Vector,
) -> List[float]:
"""
Recalculate the values of u[] based on the Newton Raphson method
"""
# double *u_prime = new double[points_offset_len]
u_prime = [None] * points_offset_len
for i in range(points_offset_len):
u_prime[i] = cubic_find_root(cubic, points_offset[i], u[i])
if not math.isfinite(u_prime[i]):
del u_prime # free
return None
u_prime.sort()
if u_prime[0] < 0.0 or u_prime[points_offset_len - 1] > 1.0:
del u_prime
return None
assert(u_prime[0] >= 0.0)
assert(u_prime[points_offset_len - 1] <= 1.0)
return u_prime
开发者ID:Italic-,项目名称:blenderpython,代码行数:29,代码来源:add_curve_freehand.py
示例19: pop_n_todo
def pop_n_todo(self, n): # Should the two pop* methods be write-only?
'''A lazy iterator yielding the n highest priority sequences'''
while n > 0:
seq = self._heap.pop()[2] # HEAPENTRY
if isfinite(seq): # heap entries are sabotaged by setting seq=_Inf
n -= 1
yield seq
开发者ID:dubslow,项目名称:MersenneForumAliquot,代码行数:7,代码来源:__init__.py
示例20: cosh
def cosh(x):
_cosh_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],
[nan, None, 1, complex(1, -0.0), None, nan, nan],
[nan, None, complex(1, -0.0), 1, None, nan, nan],
[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]
]
z = _make_complex(x)
if not isfinite(z):
if math.isinf(z.imag) and not math.isnan(z.real):
raise ValueError
if math.isinf(z.real) and math.isfinite(z.imag) and z.imag != 0:
if z.real > 0:
return complex(math.copysign(inf, math.cos(z.imag)),
math.copysign(inf, math.sin(z.imag)))
return complex(math.copysign(inf, math.cos(z.imag)),
-math.copysign(inf, math.sin(z.imag)))
return _cosh_special[_special_type(z.real)][_special_type(z.imag)]
if abs(z.real) > _LOG_LARGE_DOUBLE:
x_minus_one = z.real - math.copysign(1, z.real)
ret = complex(e * math.cos(z.imag) * math.cosh(x_minus_one),
e * math.sin(z.imag) * math.sinh(x_minus_one))
else:
ret = complex(math.cos(z.imag) * math.cosh(z.real),
math.sin(z.imag) * math.sinh(z.real))
if math.isinf(ret.real) or math.isinf(ret.imag):
raise OverflowError
return ret
开发者ID:pombredanne,项目名称:ouroboros,代码行数:35,代码来源:cmath.py
注:本文中的math.isfinite函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论