本文整理汇总了Python中math.ceil方法的典型用法代码示例。如果您正苦于以下问题:Python math.ceil方法的具体用法?Python math.ceil怎么用?Python math.ceil使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类math
的用法示例。
在下文中一共展示了math.ceil方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: step
# 需要导入模块: import math [as 别名]
# 或者: from math import ceil [as 别名]
def step(self, amt=1):
center = float(self._maxLed) / 2
center_floor = math.floor(center)
center_ceil = math.ceil(center)
if self._centerOut:
self.layout.fill(
self.palette(self._step), int(center_floor - self._current), int(center_floor - self._current))
self.layout.fill(
self.palette(self._step), int(center_ceil + self._current), int(center_ceil + self._current))
else:
self.layout.fill(
self.palette(self._step), int(self._current), int(self._current))
self.layout.fill(
self.palette(self._step), int(self._maxLed - self._current), int(self._maxLed - self._current))
self._step += amt + self._rainbowInc
if self._current == center_floor:
self._current = self._minLed
else:
self._current += amt
示例2: __iter__
# 需要导入模块: import math [as 别名]
# 或者: from math import ceil [as 别名]
def __iter__(self):
indices = []
for i, size in enumerate(self.group_sizes):
if size == 0:
continue
indice = np.where(self.flag == i)[0]
assert len(indice) == size
np.random.shuffle(indice)
num_extra = int(np.ceil(size / self.samples_per_gpu)
) * self.samples_per_gpu - len(indice)
indice = np.concatenate(
[indice, np.random.choice(indice, num_extra)])
indices.append(indice)
indices = np.concatenate(indices)
indices = [
indices[i * self.samples_per_gpu:(i + 1) * self.samples_per_gpu]
for i in np.random.permutation(
range(len(indices) // self.samples_per_gpu))
]
indices = np.concatenate(indices)
indices = indices.astype(np.int64).tolist()
assert len(indices) == self.num_samples
return iter(indices)
示例3: _format_widgets
# 需要导入模块: import math [as 别名]
# 或者: from math import ceil [as 别名]
def _format_widgets(self):
result = []
expanding = []
width = self.term_width
for index, widget in enumerate(self.widgets):
if isinstance(widget, widgets.WidgetHFill):
result.append(widget)
expanding.insert(0, index)
else:
widget = widgets.format_updatable(widget, self)
result.append(widget)
width -= len(widget)
count = len(expanding)
while count:
portion = max(int(math.ceil(width * 1. / count)), 0)
index = expanding.pop()
count -= 1
widget = result[index].update(self, portion)
width -= len(widget)
result[index] = widget
return result
示例4: save_image
# 需要导入模块: import math [as 别名]
# 或者: from math import ceil [as 别名]
def save_image(data, epoch, image_size, batch_size, output_dir, padding=2):
""" save image """
data = data.asnumpy().transpose((0, 2, 3, 1))
datanp = np.clip(
(data - np.min(data))*(255.0/(np.max(data) - np.min(data))), 0, 255).astype(np.uint8)
x_dim = min(8, batch_size)
y_dim = int(math.ceil(float(batch_size) / x_dim))
height, width = int(image_size + padding), int(image_size + padding)
grid = np.zeros((height * y_dim + 1 + padding // 2, width *
x_dim + 1 + padding // 2, 3), dtype=np.uint8)
k = 0
for y in range(y_dim):
for x in range(x_dim):
if k >= batch_size:
break
start_y = y * height + 1 + padding // 2
end_y = start_y + height - padding
start_x = x * width + 1 + padding // 2
end_x = start_x + width - padding
np.copyto(grid[start_y:end_y, start_x:end_x, :], datanp[k])
k += 1
imageio.imwrite(
'{}/fake_samples_epoch_{}.png'.format(output_dir, epoch), grid)
示例5: compute_a
# 需要导入模块: import math [as 别名]
# 或者: from math import ceil [as 别名]
def compute_a(sigma, q, lmbd, verbose=False):
lmbd_int = int(math.ceil(lmbd))
if lmbd_int == 0:
return 1.0
a_lambda_first_term_exact = 0
a_lambda_second_term_exact = 0
for i in xrange(lmbd_int + 1):
coef_i = scipy.special.binom(lmbd_int, i) * (q ** i)
s1, s2 = 0, 0
for j in xrange(i + 1):
coef_j = scipy.special.binom(i, j) * (-1) ** (i - j)
s1 += coef_j * np.exp((j * j - j) / (2.0 * (sigma ** 2)))
s2 += coef_j * np.exp((j * j + j) / (2.0 * (sigma ** 2)))
a_lambda_first_term_exact += coef_i * s1
a_lambda_second_term_exact += coef_i * s2
a_lambda_exact = ((1.0 - q) * a_lambda_first_term_exact +
q * a_lambda_second_term_exact)
if verbose:
print "A: by binomial expansion {} = {} + {}".format(
a_lambda_exact,
(1.0 - q) * a_lambda_first_term_exact,
q * a_lambda_second_term_exact)
return _to_np_float64(a_lambda_exact)
示例6: make_even_size
# 需要导入模块: import math [as 别名]
# 或者: from math import ceil [as 别名]
def make_even_size(x):
"""Pad x to be even-sized on axis 1 and 2, but only if necessary."""
x_shape = x.get_shape().as_list()
assert len(x_shape) > 2, "Only 3+-dimensional tensors supported."
shape = [dim if dim is not None else -1 for dim in x_shape]
new_shape = x_shape # To make sure constant shapes remain constant.
if x_shape[1] is not None:
new_shape[1] = 2 * int(math.ceil(x_shape[1] * 0.5))
if x_shape[2] is not None:
new_shape[2] = 2 * int(math.ceil(x_shape[2] * 0.5))
if shape[1] % 2 == 0 and shape[2] % 2 == 0:
return x
if shape[1] % 2 == 0:
x, _ = pad_to_same_length(x, x, final_length_divisible_by=2, axis=2)
x.set_shape(new_shape)
return x
if shape[2] % 2 == 0:
x, _ = pad_to_same_length(x, x, final_length_divisible_by=2, axis=1)
x.set_shape(new_shape)
return x
x, _ = pad_to_same_length(x, x, final_length_divisible_by=2, axis=1)
x, _ = pad_to_same_length(x, x, final_length_divisible_by=2, axis=2)
x.set_shape(new_shape)
return x
示例7: main
# 需要导入模块: import math [as 别名]
# 或者: from math import ceil [as 别名]
def main(_):
shard_urls = fetch.get_urls_for_shard(FLAGS.urls_dir, FLAGS.shard_id)
num_groups = int(math.ceil(len(shard_urls) / fetch.URLS_PER_CLIENT))
tf.logging.info("Launching get_references_web_single_group sequentially for "
"%d groups in shard %d. Total URLs: %d",
num_groups, FLAGS.shard_id, len(shard_urls))
command_prefix = FLAGS.command.split() + [
"--urls_dir=%s" % FLAGS.urls_dir,
"--shard_id=%d" % FLAGS.shard_id,
"--debug_num_urls=%d" % FLAGS.debug_num_urls,
]
with utils.timing("all_groups_fetch"):
for i in range(num_groups):
command = list(command_prefix)
out_dir = os.path.join(FLAGS.out_dir, "process_%d" % i)
command.append("--out_dir=%s" % out_dir)
command.append("--group_id=%d" % i)
try:
# Even on 1 CPU, each group should finish within an hour.
sp.check_call(command, timeout=60*60)
except sp.TimeoutExpired:
tf.logging.error("Group %d timed out", i)
示例8: __init__
# 需要导入模块: import math [as 别名]
# 或者: from math import ceil [as 别名]
def __init__(self, title, varieties, width, height,
anim=True, data_func=None, is_headless=False, legend_pos=4):
"""
Setup a scatter plot.
varieties contains the different types of
entities to show in the plot, which
will get assigned different colors
"""
global anim_func
self.scats = None
self.anim = anim
self.data_func = data_func
self.s = ceil(4096 / width)
self.headless = is_headless
fig, ax = plt.subplots()
ax.set_xlim(0, width)
ax.set_ylim(0, height)
self.create_scats(varieties)
ax.legend(loc = legend_pos)
ax.set_title(title)
plt.grid(True)
if anim and not self.headless:
anim_func = animation.FuncAnimation(fig,
self.update_plot,
frames=1000,
interval=500,
blit=False)
示例9: add_content
# 需要导入模块: import math [as 别名]
# 或者: from math import ceil [as 别名]
def add_content(self, content): # type: (str) -> None
for line_content in content.split("\n"):
self._lines += (
math.ceil(
len(self.remove_format(line_content).replace("\t", " "))
/ self._terminal.width
)
or 1
)
self._content.append(line_content)
self._content.append("\n")
示例10: format_time
# 需要导入模块: import math [as 别名]
# 或者: from math import ceil [as 别名]
def format_time(secs): # type: (int) -> str
for fmt in _TIME_FORMATS:
if secs > fmt[0]:
continue
if len(fmt) == 2:
return fmt[1]
return "{} {}".format(math.ceil(secs / fmt[2]), fmt[1])
示例11: resize_image
# 需要导入模块: import math [as 别名]
# 或者: from math import ceil [as 别名]
def resize_image(img, width, height, method, mode, bg_color=(0, 0, 0, 0)):
# Some code from:
# https://github.com/charlesthk/python-resize-image/blob/master/resizeimage/resizeimage.py
# Thank you!
img = img.copy()
pil_method = getattr(Image, method.upper())
if mode == 'fill':
img = img.resize((width, height), pil_method)
elif mode == 'aspect-fill':
w,h = img.size
ratio = max(width / w, height / h)
nsize = (int(math.ceil(w * ratio)), int(math.ceil(h * ratio)))
img = img.resize(nsize, pil_method)
w,h = img.size
left = (w - width) / 2
top = (h - height) / 2
right = w - left
bottom = h - top
rect = (int(math.ceil(x)) for x in (left, top, right, bottom))
img = img.crop(rect)
elif mode == 'aspect-fit':
img.thumbnail((width, height), pil_method)
background = Image.new('RGBA', (width, height), bg_color)
img_position = (
int(math.ceil((width - img.width) / 2)),
int(math.ceil((height - img.height) / 2))
)
background.paste(img, img_position)
img = background.convert('RGB')
return img
示例12: round_to_multiple
# 需要导入模块: import math [as 别名]
# 或者: from math import ceil [as 别名]
def round_to_multiple(x, base):
return int(base * math.ceil(float(x)/base))
示例13: __init__
# 需要导入模块: import math [as 别名]
# 或者: from math import ceil [as 别名]
def __init__(self, titles, increasing, save_to_fp):
assert len(titles) == len(increasing)
n_plots = len(titles)
self.titles = titles
self.increasing = dict([(title, incr) for title, incr in zip(titles, increasing)])
self.colors = ["red", "blue", "cyan", "magenta", "orange", "black"]
self.nb_points_max = 500
self.save_to_fp = save_to_fp
self.start_batch_idx = 0
self.autolimit_y = False
self.autolimit_y_multiplier = 5
#self.fig, self.axes = plt.subplots(nrows=2, ncols=2, figsize=(20, 20))
nrows = max(1, int(math.sqrt(n_plots)))
ncols = int(math.ceil(n_plots / nrows))
width = ncols * 10
height = nrows * 10
self.fig, self.axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(width, height))
if nrows == 1 and ncols == 1:
self.axes = [self.axes]
else:
self.axes = self.axes.flat
title_to_ax = dict()
for idx, (title, ax) in enumerate(zip(self.titles, self.axes)):
title_to_ax[title] = ax
self.title_to_ax = title_to_ax
self.fig.tight_layout()
self.fig.subplots_adjust(left=0.05)
示例14: quoteboard
# 需要导入模块: import math [as 别名]
# 或者: from math import ceil [as 别名]
def quoteboard(self, ctx: Context, page: int = 1):
"""Show a leaderboard of users with the most quotes."""
users = ""
current = 1
start_from = (page - 1) * 10
async with self.bot.pool.acquire() as connection:
page_count = ceil(
await connection.fetchval(
"SELECT count(DISTINCT author_id) FROM quotes"
) / 10
)
if 1 > page > page_count:
return await ctx.send(":no_entry_sign: Invalid page number")
for result in await connection.fetch(
"SELECT author_id, COUNT(author_id) as quote_count FROM quotes "
"GROUP BY author_id ORDER BY quote_count DESC LIMIT 10 OFFSET $1",
start_from,
):
author, quotes = result.values()
users += f"{start_from + current}. <@{author}> - {quotes}\n"
current += 1
embed = Embed(colour=Colour(0xAE444A))
embed.add_field(name=f"Page {page}/{page_count}", value=users)
embed.set_author(name="Quotes Leaderboard", icon_url=CYBERDISC_ICON_URL)
await ctx.send(embed=embed)
示例15: _anchor_component
# 需要导入模块: import math [as 别名]
# 或者: from math import ceil [as 别名]
def _anchor_component(self, height, width):
# just to get the shape right
#height = int(math.ceil(self._im_info.data[0, 0] / self._feat_stride[0]))
#width = int(math.ceil(self._im_info.data[0, 1] / self._feat_stride[0]))
anchors, anchor_length = generate_anchors_pre(\
height, width,
self._feat_stride, self._anchor_scales, self._anchor_ratios)
self._anchors = Variable(torch.from_numpy(anchors).cuda())
self._anchor_length = anchor_length
开发者ID:Sunarker,项目名称:Collaborative-Learning-for-Weakly-Supervised-Object-Detection,代码行数:11,代码来源:network.py