本文整理汇总了Python中math.isnan函数的典型用法代码示例。如果您正苦于以下问题:Python isnan函数的具体用法?Python isnan怎么用?Python isnan使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了isnan函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_init
def test_init(self):
import numpy as np
import math
import sys
assert np.intp() == np.intp(0)
assert np.intp("123") == np.intp(123)
raises(TypeError, np.intp, None)
assert np.float64() == np.float64(0)
assert math.isnan(np.float64(None))
assert np.bool_() == np.bool_(False)
assert np.bool_("abc") == np.bool_(True)
assert np.bool_(None) == np.bool_(False)
assert np.complex_() == np.complex_(0)
# raises(TypeError, np.complex_, '1+2j')
assert math.isnan(np.complex_(None))
for c in ["i", "I", "l", "L", "q", "Q"]:
assert np.dtype(c).type().dtype.char == c
for c in ["l", "q"]:
assert np.dtype(c).type(sys.maxint) == sys.maxint
for c in ["L", "Q"]:
assert np.dtype(c).type(sys.maxint + 42) == sys.maxint + 42
assert np.float32(np.array([True, False])).dtype == np.float32
assert type(np.float32(np.array([True]))) is np.ndarray
assert type(np.float32(1.0)) is np.float32
a = np.array([True, False])
assert np.bool_(a) is a
示例2: load
def load(cls, filename):
""" @brief Loads a png from a file as a 16-bit heightmap.
@param filename Name of target .png image
@returns A 16-bit, 1-channel image.
"""
# Get various png parameters so that we can allocate the
# correct amount of storage space for the new image
dx, dy, dz = ctypes.c_float(), ctypes.c_float(), ctypes.c_float()
ni, nj = ctypes.c_int(), ctypes.c_int()
libfab.load_png_stats(filename, ni, nj, dx, dy, dz)
# Create a python image data structure
img = cls(ni.value, nj.value, channels=1, depth=16)
# Add bounds to the image
if math.isnan(dx.value):
print 'Assuming 72 dpi for x resolution.'
img.xmin, img.xmax = 0, 72*img.width/25.4
else: img.xmin, img.xmax = 0, dx.value
if math.isnan(dy.value):
print 'Assuming 72 dpi for y resolution.'
img.ymin, img.ymax = 0, 72*img.height/25.4
else: img.ymin, img.ymax = 0, dy.value
if not math.isnan(dz.value): img.zmin, img.zmax = 0, dz.value
# Load the image data from the file
libfab.load_png(filename, img.pixels)
img.filename = filename
return img
示例3: _align_top_level
def _align_top_level(self):
"""Temporary function to plot data. Expected to be
implemented in plotter
"""
result_1 = self._first_agg.aggregate(level="all")
result_2 = self._second_agg.aggregate(level="all")
s_x = self._resample(result_1[0])
s_y = self._resample(result_2[0])
front_x, front_y, front_shift = align(s_x, s_y, mode="front")
front_corr = self._correlate(front_x, front_y)
back_x, back_y, back_shift = align(s_x, s_y, mode="back")
back_corr = self._correlate(back_x, back_y)
if math.isnan(back_corr):
back_corr = 0
if math.isnan(front_corr):
front_corr = 0
if front_corr >= back_corr:
return front_shift
else:
return back_shift
示例4: _tabulate
def _tabulate(self, tablefmt="simple", rollups=False, rows=10):
"""Pretty tabulated string of all the cached data, and column names"""
if not self.is_valid(): self.fill(rows=rows)
# Pretty print cached data
d = collections.OrderedDict()
# If also printing the rollup stats, build a full row-header
if rollups:
col = next(iter(viewvalues(self._data))) # Get a sample column
lrows = len(col['data']) # Cached rows being displayed
d[""] = ["type", "mins", "mean", "maxs", "sigma", "zeros", "missing"] + list(map(str, range(lrows)))
# For all columns...
for k, v in viewitems(self._data):
x = v['data'] # Data to display
t = v["type"] # Column type
if t == "enum":
domain = v['domain'] # Map to cat strings as needed
x = ["" if math.isnan(idx) else domain[int(idx)] for idx in x]
elif t == "time":
x = ["" if math.isnan(z) else time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(z / 1000)) for z in x]
if rollups: # Rollups, if requested
mins = v['mins'][0] if v['mins'] and v["type"] != "enum" else None
maxs = v['maxs'][0] if v['maxs'] and v["type"] != "enum" else None
#Cross check type with mean and sigma. Set to None if of type enum.
if v['type'] == "enum":
v['mean'] = v['sigma'] = v['zero_count'] = None
x = [v['type'], mins, v['mean'], maxs, v['sigma'], v['zero_count'], v['missing_count']] + x
d[k] = x # Insert into ordered-dict
return tabulate.tabulate(d, headers="keys", tablefmt=tablefmt)
示例5: test_variance
def test_variance(self):
Case = namedtuple("Case", "array variance")
cases = [
Case([], float("nan")),
Case([1], float("nan")),
Case([1, 1], 0),
Case([1, 1, 1], 0),
Case([1, 2, 3, 4, 5], 2.5),
Case([1.5, 4.7, 24, 8.5], 99.38916666666665),
Case([-34, 5, 3.6, -104.95, 67.4], 3989.6705)
]
# Calculating the variance using the pystat module.
for case in cases:
runningStat = RunningStat()
# Push all elements.
for element in case.array:
runningStat.push(element)
# Ensures that both numbers are either NaNs or not NaNs.
self.assertEqual(math.isnan(runningStat.variance()),
math.isnan(case.variance))
# If the variance is not a NaN compare it to the expected variance.
if not math.isnan(runningStat.variance()):
precision = 0
if "." in str(case.variance):
precision = len(str(case.variance).split(".")[1])
self.assertEqual(round(runningStat.variance(), precision),
round(case.variance, precision))
示例6: test_max
def test_max(self):
Case = namedtuple("Case", "array max")
cases = [
Case([], float("nan")),
Case([1], 1),
Case([1, 1], 1),
Case([1, 1, 1], 1),
Case([1, 2, 3, 4, 5], 5),
Case([1.5, 4.7, 24, 8.5], 24),
Case([-34, 5, 3.6, -104.95, 67.4], 67.4)
]
# Calculating the max using the pystat module.
for case in cases:
runningStat = RunningStat()
# Push all elements.
for element in case.array:
runningStat.push(element)
# Ensures that both numbers are either NaNs or not NaNs.
self.assertEqual(math.isnan(runningStat.max()),
math.isnan(case.max))
# If the max is not a NaN compare it to the expected max.
if not math.isnan(runningStat.max()):
self.assertEqual(runningStat.max(), case.max)
示例7: testLdexp
def testLdexp(self):
self.assertRaises(TypeError, math.ldexp)
self.ftest('ldexp(0,1)', math.ldexp(0,1), 0)
self.ftest('ldexp(1,1)', math.ldexp(1,1), 2)
self.ftest('ldexp(1,-1)', math.ldexp(1,-1), 0.5)
self.ftest('ldexp(-1,1)', math.ldexp(-1,1), -2)
self.assertRaises(OverflowError, math.ldexp, 1., 1000000)
self.assertRaises(OverflowError, math.ldexp, -1., 1000000)
self.assertEquals(math.ldexp(1., -1000000), 0.)
self.assertEquals(math.ldexp(-1., -1000000), -0.)
self.assertEquals(math.ldexp(INF, 30), INF)
self.assertEquals(math.ldexp(NINF, -213), NINF)
self.assert_(math.isnan(math.ldexp(NAN, 0)))
# large second argument
for n in [10**5, 10L**5, 10**10, 10L**10, 10**20, 10**40]:
self.assertEquals(math.ldexp(INF, -n), INF)
self.assertEquals(math.ldexp(NINF, -n), NINF)
self.assertEquals(math.ldexp(1., -n), 0.)
self.assertEquals(math.ldexp(-1., -n), -0.)
self.assertEquals(math.ldexp(0., -n), 0.)
self.assertEquals(math.ldexp(-0., -n), -0.)
self.assert_(math.isnan(math.ldexp(NAN, -n)))
self.assertRaises(OverflowError, math.ldexp, 1., n)
self.assertRaises(OverflowError, math.ldexp, -1., n)
self.assertEquals(math.ldexp(0., n), 0.)
self.assertEquals(math.ldexp(-0., n), -0.)
self.assertEquals(math.ldexp(INF, n), INF)
self.assertEquals(math.ldexp(NINF, n), NINF)
self.assert_(math.isnan(math.ldexp(NAN, n)))
示例8: branch_calculte
def branch_calculte(filename):
f=open(WORKPATH+filename)
f.readline()
paml_rate = {}
for line in f:
line = line.strip()
paml_out = paml.read_line(line)
sp0 = round(((paml_out.sp1_sp0 + paml_out.sp2_sp0) - paml_out.sp2_sp1)/2,4)
sp1 = round(((paml_out.sp2_sp1 + paml_out.sp1_sp0) - paml_out.sp2_sp0)/2,4)
sp2 = round(((paml_out.sp2_sp1 + paml_out.sp2_sp0) - paml_out.sp1_sp0)/2,4)
if math.isnan(sp0) or math.isnan(sp1) or math.isnan(sp2):
pass
else:
sp0 = sp0 if sp0 > 0 else 0.0001
sp1 = sp1 if sp1 > 0 else 0.0001
sp0_devide_sp1 = sp0/sp1
sp0_devide_sp1 = 16 if sp0_devide_sp1 > 16 else sp0_devide_sp1
sp0_devide_sp1 = 0.0625 if sp0_devide_sp1 < 0.0625 else sp0_devide_sp1
paml_rate[paml_out.sp0name]=np.log2(sp0_devide_sp1) #paml-rate structure
'''
f = open(branch_file,"w")
f.write("sp0\tB_sp0\tB_sp1\tB_sp2\n")
for name in paml_rate:
f.write(name+"\t"+str(paml_rate[name][0])+\
"\t"+str(paml_rate[name][1])+\
"\t"+str(paml_rate[name][2])+"\n")
f.close()
'''
return paml_rate
示例9: test_pow
def test_pow(self):
import math
def pw(x, y):
return x ** y
def espeq(x, y):
return not abs(x-y) > 1e05
raises(ZeroDivisionError, pw, 0.0, -1)
assert pw(0, 0.5) == 0.0
assert espeq(pw(4.0, 0.5), 2.0)
assert pw(4.0, 0) == 1.0
assert pw(-4.0, 0) == 1.0
assert type(pw(-1.0, 0.5)) == complex
assert pw(-1.0, 2.0) == 1.0
assert pw(-1.0, 3.0) == -1.0
assert pw(-1.0, 1e200) == 1.0
if self.py26:
assert pw(0.0, float("-inf")) == float("inf")
assert math.isnan(pw(-3, float("nan")))
assert math.isnan(pw(-3., float("nan")))
assert pw(-1.0, -float('inf')) == 1.0
assert pw(-1.0, float('inf')) == 1.0
assert pw(float('inf'), 0) == 1.0
assert pw(float('nan'), 0) == 1.0
assert math.isinf(pw(-0.5, float('-inf')))
assert math.isinf(pw(+0.5, float('-inf')))
assert pw(-1.5, float('-inf')) == 0.0
assert pw(+1.5, float('-inf')) == 0.0
assert str(pw(float('-inf'), -0.5)) == '0.0'
assert str(pw(float('-inf'), -2.0)) == '0.0'
assert str(pw(float('-inf'), -1.0)) == '-0.0'
assert str(pw(float('-inf'), 1.0)) == '-inf'
assert str(pw(float('-inf'), 2.0)) == 'inf'
示例10: explorer
def explorer():
(metadata,pose_origin,pose_robot,pose_in_im,pose_in_map,copyData,image_array)=get_map_data()
remplissage_diff(metadata,pose_in_im)
scipy.misc.imsave('map.png', image_array)
(x_im,y_im)=find_ppv()
while(not (isnan(x_im) and isnan(y_im)) and rospy.is_shutdown()):
(x,y,theta)=pix_to_pose((x_im,y_im,0), pose_origin, metadata)
print(x,y,theta)
# Plotting the location of the robot
for i in range(-3,4):
for j in range(-3,4):
image_array[pose_in_im[0]+i, pose_in_im[1]+j] = (255, 0, 0)
# Plotting its orientation
for i in range(10):
image_array[int(pose_in_im[0]+i*sin(-pose_in_im[2])), int(pose_in_im[1]+i*cos(-pose_in_im[2]))] = (0, 0, 255)
print("Enregistrement de l'image")
scipy.misc.imsave('map.png', image_array)
reach_goal(x,y,theta)
(metadata,pose_origin,pose_robot,pose_in_im,pose_in_map,copyData,image_array)=get_map_data()
remplissage_diff()
scipy.misc.imsave('map.png', image_array)
(x_im,y_im)=find_ppv()
示例11: write_log
def write_log(task, data, in_rows, question, out_rows, out_cols, solution, version, git, fun, run, time_sec, mem_gb, cache, chk, chk_time_sec):
batch = os.getenv('BATCH', "")
timestamp = time.time()
csv_file = os.getenv('CSV_TIME_FILE', "time.csv")
nodename = platform.node()
comment = "" # placeholder for updates to timing data
time_sec = round(time_sec, 3)
chk_time_sec = round(chk_time_sec, 3)
mem_gb = round(mem_gb, 3)
if math.isnan(time_sec):
time_sec = ""
if math.isnan(mem_gb):
mem_gb = ""
log_row = [nodename, batch, timestamp, task, data, in_rows, question, out_rows, out_cols, solution, version, git, fun, run, time_sec, mem_gb, cache, chk, chk_time_sec, comment]
log_header = ["nodename","batch","timestamp","task","data","in_rows","question","out_rows","out_cols","solution","version","git","fun","run","time_sec","mem_gb","cache","chk","chk_time_sec","comment"]
append = os.path.isfile(csv_file)
csv_verbose = os.getenv('CSV_VERBOSE', "true")
if csv_verbose.lower()=="true":
print('# ' + ','.join(str(x) for x in log_row))
if append:
with open(csv_file, 'a') as f:
w = csv.writer(f, lineterminator='\n')
w.writerow(log_row)
else:
with open(csv_file, 'w+') as f:
w = csv.writer(f, lineterminator='\n')
w.writerow(log_header)
w.writerow(log_row)
return True
示例12: assertFloatsAreIdentical
def assertFloatsAreIdentical(self, x, y):
"""assert that floats x and y are identical, in the sense that:
(1) both x and y are nans, or
(2) both x and y are infinities, with the same sign, or
(3) both x and y are zeros, with the same sign, or
(4) x and y are both finite and nonzero, and x == y
"""
msg = 'floats {!r} and {!r} are not identical'
if isnan(x) or isnan(y):
if isnan(x) and isnan(y):
return
elif x == y:
if x != 0.0:
return
# both zero; check that signs match
elif copysign(1.0, x) == copysign(1.0, y):
return
else:
msg += ': zeros have different signs'
if test_support.due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28352"):
print msg.format(x, y)
return
self.fail(msg.format(x, y))
示例13: tradeRuleNVI
def tradeRuleNVI(nvit1, nvi, sma):
if math.isnan(nvit1) or math.isnan(nvi) or math.isnan(sma):
return np.nan
if nvit1 <= sma and nvi > sma:
return 1 # buy
else:
return 0 # hold
示例14: arith_min_same
def arith_min_same(self, other):
assert isinstance(other, values.W_Flonum)
if math.isnan(self.value):
return self
if math.isnan(other.value):
return other
return values.W_Number.arith_min_same(self, other)
示例15: bv2rgb
def bv2rgb(bv):
if math.isnan(bv):
bc = 0
if bv < -0.4: bv = -0.4
if bv > 2.0: bv = 2.0
if bv >= -0.40 and bv < 0.00:
t = (bv + 0.40) / (0.00 + 0.40)
r = 0.61 + 0.11 * t + 0.1 * t * t
g = 0.70 + 0.07 * t + 0.1 * t * t
b = 1.0
elif bv >= 0.00 and bv < 0.40:
t = (bv - 0.00) / (0.40 - 0.00)
r = 0.83 + (0.17 * t)
g = 0.87 + (0.11 * t)
b = 1.0
elif bv >= 0.40 and bv < 1.60:
t = (bv - 0.40) / (1.60 - 0.40)
r = 1.0
g = 0.98 - 0.16 * t
else:
t = (bv - 1.60) / (2.00 - 1.60)
r = 1.0
g = (0.82 - 0.5) * t * t
if bv >= 0.40 and bv < 1.50:
t = (bv - 0.40) / (1.50 - 0.40)
b = 1.00 - 0.47 * t + 0.1 * t * t
elif bv >= 1.50 and bv < 1.951:
t = (bv - 1.50) / (1.94 - 1.50)
b = 0.63 - 0.6 * t * t
else:
b = 0.0
if bv == 'nan' or math.isnan(bv):
g = 0.5
g /= 1.3
return "rgb({0}, {1}, {2})".format(int(r*255),int(g*255),int(b*255))