Python math.floor() Examples
The following are 30
code examples of math.floor().
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 Project: unicorn-hat-hd Author: pimoroni File: demo.py License: MIT License | 6 votes |
def checker(x, y, step): x -= (u_width / 2) y -= (u_height / 2) angle = (step / 10.0) s = math.sin(angle) c = math.cos(angle) xs = x * c - y * s ys = x * s + y * c xs -= math.sin(step / 200.0) * 40.0 ys -= math.cos(step / 200.0) * 40.0 scale = step % 20 scale /= 20 scale = (math.sin(step / 50.0) / 8.0) + 0.25 xs *= scale ys *= scale xo = abs(xs) - int(abs(xs)) yo = abs(ys) - int(abs(ys)) v = 0 if (math.floor(xs) + math.floor(ys)) % 2 else 1 if xo > .1 and yo > .1 else .5 r, g, b = hue_to_rgb[step % 255] return (r * (v * 255), g * (v * 255), b * (v * 255)) # weeee waaaah
Example #2
Source Project: Gurux.DLMS.Python Author: Gurux File: GXDLMSExtendedRegister.py License: GNU General Public License v2.0 | 6 votes |
def getValue(self, settings, e): if e.index == 1: return _GXCommon.logicalNameToBytes(self.logicalName) if e.index == 2: return self.value if e.index == 3: data = GXByteBuffer() data.setUInt8(DataType.STRUCTURE) data.setUInt8(2) _GXCommon.setData(settings, data, DataType.INT8, math.floor(math.log(self.scaler, 10))) _GXCommon.setData(settings, data, DataType.ENUM, int(self.unit)) return data.array() if e.index == 4: return self.status if e.index == 5: return self.captureTime e.error = ErrorCode.READ_WRITE_DENIED return None # # Set value of given attribute. #
Example #3
Source Project: Gurux.DLMS.Python Author: Gurux File: GXDLMSRegister.py License: GNU General Public License v2.0 | 6 votes |
def getValue(self, settings, e): if e.index == 1: return _GXCommon.logicalNameToBytes(self.logicalName) if e.index == 2: return self.value if e.index == 3: data = GXByteBuffer() data.setUInt8(DataType.STRUCTURE) data.setUInt8(2) _GXCommon.setData(settings, data, DataType.INT8, math.floor(math.log(self.scaler, 10))) _GXCommon.setData(settings, data, DataType.ENUM, int(self.unit)) return data.array() e.error = ErrorCode.READ_WRITE_DENIED return None # # Set value of given attribute. # #pylint: disable=broad-except
Example #4
Source Project: indras_net Author: gcallah File: sand.py License: GNU General Public License v3.0 | 6 votes |
def __init__(self, name, width, height, model_nm=None, props=None): super().__init__(name, width, height, torus=False, model_nm=model_nm, postact=True, props=props) self.center_agent = None self.set_var_color('0', disp.BLACK) self.set_var_color('1', disp.MAGENTA) self.set_var_color('2', disp.BLUE) self.set_var_color('3', disp.CYAN) self.set_var_color('4', disp.RED) self.set_var_color('5', disp.YELLOW) self.set_var_color('6', disp.GREEN) center_x = floor(self.width // 2) center_y = floor(self.height // 2) print("center = %i, %i" % (center_x, center_y)) for cell in self: (x, y) = cell.coords agent = SandAgent("Grainy", "Hold sand", cell) self.add_agent(agent, position=False) if x == center_x and y == center_y: self.center_agent = agent
Example #5
Source Project: BiblioPixelAnimations Author: ManiacalLabs File: HalvesRainbow.py License: MIT License | 6 votes |
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
Example #6
Source Project: python-panavatar Author: ondergetekende File: parameters.py License: MIT License | 6 votes |
def _get_octave(seed, coord): x = coord.real y = coord.imag cellx = math.floor(x) celly = math.floor(y) value00 = _perlin_random(seed, cellx, celly) value10 = _perlin_random(seed, cellx + 1, celly) value01 = _perlin_random(seed, cellx, celly + 1) value11 = _perlin_random(seed, cellx + 1, celly + 1) offsetx = x % 1.0 offsety = y % 1.0 value0 = offsetx * value10 + (1 - offsetx) * value00 value1 = offsetx * value11 + (1 - offsetx) * value01 result = offsety * value1 + (1 - offsety) * value0 return result * INV_MAX_VALUE
Example #7
Source Project: python-panavatar Author: ondergetekende File: parameters.py License: MIT License | 6 votes |
def __init__(self, seed, octaves=None, detail=None, min_value=0, max_value=1, size=1.0): if not octaves: octaves = max(1, int(math.floor(math.log(size / detail, 2)))) scales = [.5 ** o for o in range(octaves)] inv_total_scale = 1.0 / sum(scales) self.min_value = min_value self.max_value = max_value self.inv_size = 1.0 / size self.octaves = [ (inv_total_scale * scale, 1.0 / (inv_total_scale * scale), (seed ^ o * 541) & 0x3FFFFFFF) for (o, scale) in enumerate(scales)]
Example #8
Source Project: pyflowgraph Author: EricTRocks File: node.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def mouseMoveEvent(self, event): if self.__dragging: newPos = self.mapToScene(event.pos()) graph = self.getGraph() if graph.getSnapToGrid() is True: gridSize = graph.getGridSize() newNodePos = newPos - self._mouseDelta snapPosX = math.floor(newNodePos.x() / gridSize) * gridSize; snapPosY = math.floor(newNodePos.y() / gridSize) * gridSize; snapPos = QtCore.QPointF(snapPosX, snapPosY) newPosOffset = snapPos - newNodePos newPos = newPos + newPosOffset delta = newPos - self._lastDragPoint self.__graph.moveSelectedNodes(delta) self._lastDragPoint = newPos self._nodesMoved = True else: super(Node, self).mouseMoveEvent(event)
Example #9
Source Project: progressive_growing_of_GANs Author: preritj File: utils.py License: MIT License | 6 votes |
def grid_batch_images(self, images): n, h, w, c = images.shape a = int(math.floor(np.sqrt(n))) # images = (((images - images.min()) * 255) / (images.max() - images.min())).astype(np.uint8) images = images.astype(np.uint8) images_in_square = np.reshape(images[:a * a], (a, a, h, w, c)) new_img = np.zeros((h * a, w * a, c), dtype=np.uint8) for col_i, col_images in enumerate(images_in_square): for row_i, image in enumerate(col_images): new_img[col_i * h: (1 + col_i) * h, row_i * w: (1 + row_i) * w] = image resolution = self.cfg.resolution if self.cfg.resolution != h: scale = resolution / h new_img = cv2.resize(new_img, None, fx=scale, fy=scale, interpolation=cv2.INTER_NEAREST) return new_img
Example #10
Source Project: sixcells Author: oprypin File: editor.py License: GNU General Public License v3.0 | 6 votes |
def _place(self, p, kind=Cell.unknown): if not self.preview: self.preview = Cell() self.preview.kind = kind self.preview.setOpacity(0.4) self.addItem(self.preview) x, y = convert_pos(p.x(), p.y()) x = round(x) for yy in [round(y), int(math.floor(y - 1e-4)), int(math.ceil(y + 1e-4))]: self.preview.coord = (x, yy) if not any(isinstance(it, Cell) for it in self.preview.overlapping): break else: self.preview.coord = (round(x), round(y)) self.preview.upd() self.preview._text.setText('')
Example #11
Source Project: TVQAplus Author: jayleicn File: utils.py License: MIT License | 6 votes |
def get_bbox_target_single_box(single_box, spatial_dim=7, img_w=640., img_h=360., thd=0.5): """ :param single_box: a single box :param spatial_dim: :param img_w: :param img_h: :param thd: round thd :return: """ top = single_box["top"] left = single_box["left"] bottom = top + single_box["height"] right = left + single_box["width"] # map to 224x224 to 7x7 top = int(math.floor((top * spatial_dim) / img_h + thd)) bottom = int(math.ceil((bottom * spatial_dim) / img_h - thd)) left = int(math.floor((left * spatial_dim) / img_w + thd)) right = int(math.ceil((right * spatial_dim) / img_w - thd)) gt_att_map = np.zeros([spatial_dim, spatial_dim]).astype(np.float32) gt_att_map[top: bottom+1, left:right+1] = 1 # print(top, bottom, left, right) return gt_att_map
Example #12
Source Project: DeepLung Author: uci-cbcl File: noduleCADEvaluationLUNA16.py License: GNU General Public License v3.0 | 6 votes |
def compute_mean_ci(interp_sens, confidence = 0.95): sens_mean = np.zeros((interp_sens.shape[1]),dtype = 'float32') sens_lb = np.zeros((interp_sens.shape[1]),dtype = 'float32') sens_up = np.zeros((interp_sens.shape[1]),dtype = 'float32') Pz = (1.0-confidence)/2.0 print(interp_sens.shape) for i in range(interp_sens.shape[1]): # get sorted vector vec = interp_sens[:,i] vec.sort() sens_mean[i] = np.average(vec) sens_lb[i] = vec[int(math.floor(Pz*len(vec)))] sens_up[i] = vec[int(math.floor((1.0-Pz)*len(vec)))] return sens_mean,sens_lb,sens_up
Example #13
Source Project: argus-freesound Author: lRomul File: senet.py License: MIT License | 6 votes |
def __init__(self, inplanes, planes, groups, reduction, stride=1, downsample=None, base_width=4): super(SEResNeXtBottleneck, self).__init__() width = math.floor(planes * (base_width / 64)) * groups self.conv1 = nn.Conv2d(inplanes, width, kernel_size=1, bias=False, stride=1) self.bn1 = nn.BatchNorm2d(width) self.conv2 = nn.Conv2d(width, width, kernel_size=3, stride=stride, padding=1, groups=groups, bias=False) self.bn2 = nn.BatchNorm2d(width) self.conv3 = nn.Conv2d(width, planes * 4, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes * 4) self.relu = nn.ReLU(inplace=True) self.se_module = SEModule(planes * 4, reduction=reduction) self.downsample = downsample self.stride = stride
Example #14
Source Project: jawfish Author: war-and-code File: fractions.py License: MIT License | 6 votes |
def __round__(self, ndigits=None): """Will be round(self, ndigits) in 3.0. Rounds half toward even. """ if ndigits is None: floor, remainder = divmod(self.numerator, self.denominator) if remainder * 2 < self.denominator: return floor elif remainder * 2 > self.denominator: return floor + 1 # Deal with the half case: elif floor % 2 == 0: return floor else: return floor + 1 shift = 10**abs(ndigits) # See _operator_fallbacks.forward to check that the results of # these operations will always be Fraction and therefore have # round(). if ndigits > 0: return Fraction(round(self * shift), shift) else: return Fraction(round(self / shift) * shift)
Example #15
Source Project: Gurux.DLMS.Python Author: Gurux File: GXDLMSDemandRegister.py License: GNU General Public License v2.0 | 5 votes |
def getValue(self, settings, e): if e.index == 1: ret = _GXCommon.logicalNameToBytes(self.logicalName) elif e.index == 2: ret = self.currentAverageValue elif e.index == 3: ret = self.lastAverageValue elif e.index == 4: data = GXByteBuffer() data.setUInt8(DataType.STRUCTURE) data.setUInt8(2) _GXCommon.setData(settings, data, DataType.INT8, math.floor(math.log(self.scaler, 10))) _GXCommon.setData(settings, data, DataType.ENUM, int(self.unit)) ret = data.array() elif e.index == 5: ret = self.status elif e.index == 6: ret = self.captureTime elif e.index == 7: ret = self.startTimeCurrent elif e.index == 8: ret = self.period elif e.index == 9: ret = self.numberOfPeriods else: e.error = ErrorCode.READ_WRITE_DENIED return ret # # Set value of given attribute. # pylint: disable=broad-except
Example #16
Source Project: indras_net Author: gcallah File: wolfram.py License: GNU General Public License v3.0 | 5 votes |
def __init__(self, name, width, height, model_nm=None, props=None, rule_id=30): super().__init__(name, width, height, torus=False, model_nm=model_nm, postact=True, props=props) try: base_dir = props["base_dir"] except: base_dir = "" path = os.path.join(base_dir, "wolfram/wolfram_rules.txt") try: self.rules = self.read_wolfram_rules(path)[rule_id] except: self.rules = RULE30 logging.info("Rule dictionary not found. Using the default rule.") center_x = floor(self.width // 2) top_y = self.height-1 print("center top = %i, %i" % (center_x, top_y)) for cell in self: (x, y) = cell.coords agent = WolframAgent("Cell" + str((x, y)), "Show color", cell) self.add_agent(agent, position=False) if x == center_x and y == top_y: agent.state = B agent.postact() agent.is_active = False
Example #17
Source Project: indras_net Author: gcallah File: sand.py License: GNU General Public License v3.0 | 5 votes |
def restore_agent(self, agent_json): new_agent = SandAgent(name=agent_json["name"], goal=agent_json["goal"], cell=ge.Cell.from_json(agent_json["cell"]), sand_amt=agent_json["sand_amt"]) (x, y) = new_agent.cell.coords self.add_agent_from_json(new_agent, agent_json, x=x, y=y) center_x = floor(self.width // 2) center_y = floor(self.height // 2) if x == center_x and y == center_y: self.center_agent = new_agent
Example #18
Source Project: indras_net Author: gcallah File: sand_markov_model.py License: GNU General Public License v3.0 | 5 votes |
def __init__(self, name, width, height, model_nm, max_pile_size): super().__init__(name, width, height, torus=False, matrix_dim=max_pile_size, model_nm=model_nm, postact=True) self.max_pile_size = max_pile_size self.center_agent = None self.set_var_color('0', disp.BLACK) self.set_var_color('1', disp.MAGENTA) self.set_var_color('2', disp.BLUE) self.set_var_color('3', disp.CYAN) self.set_var_color('4', disp.RED) self.set_var_color('5', disp.YELLOW) self.set_var_color('6', disp.GREEN) center_x = floor(self.width // 2) center_y = floor(self.height // 2) print("center = %i, %i" % (center_x, center_y)) for cell in self: (x, y) = cell.coords # vLen contains the state of the agent # the state is the number of grains of sand # in the SandAgent. agent = SandAgent("Grainy", "Hold sand", vlen=self.max_pile_size, init_state=0, cell=cell) self.add_agent(agent, position=False) if x == center_x and y == center_y: self.center_agent = agent
Example #19
Source Project: clikit Author: sdispater File: progress_bar.py License: MIT License | 5 votes |
def bar_offset(self): # type: () -> int if self._max: return math.floor(self._percent * self.bar_width) else: if self.redraw_freq is None: return math.floor( (min(5, self.get_bar_width() / 15) * self._write_count) % self.bar_width ) return math.floor(self._step % self.bar_width)
Example #20
Source Project: clikit Author: sdispater File: progress_bar.py License: MIT License | 5 votes |
def _formatter_percent(self): return int(math.floor(self._percent * 100))
Example #21
Source Project: vergeml Author: mme File: crop.py License: MIT License | 5 votes |
def transform(self, img, rng): width, height = img.size if width < self.width: raise VergeMLError("Can't crop sample with width {} to {}.".format(width, self.width)) if height < self.height: raise VergeMLError("Can't crop sample with height {} to {}.".format(height, self.height)) if self.x or self.y: if width < self.width + self.x: raise VergeMLError("Can't crop sample with width {} to {} from x {}.".format(width, self.width, self.x)) if height < self.height + self.y: raise VergeMLError("Can't crop sample with height {} to {} from y {}.".format(height, self.height, self.y)) x = self.x y = self.y elif self.position == "top-left": x, y = 0,0 elif self.position == "top-right": x, y = width - self.width, 0 elif self.position == "bottom-left": x, y = 0, height - self.height elif self.position == "bottom-right": x, y = width - self.width, height - self.height elif self.position == "center": x, y = math.floor(width/2 - self.width/2), math.floor(height/2 - self.height/2) params = x, y, x + self.width, y + self.height return img.crop(params)
Example #22
Source Project: LipNet-PyTorch Author: sailordiary File: augmentation.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def round(x): return math.floor(x + 0.5)
Example #23
Source Project: backtrader-cn Author: pandalibin File: utils.py License: GNU General Public License v3.0 | 5 votes |
def split_data(cls, data, percent=0.3): """ Split the data into training data and test data. :param data(DataFrame): data to be split. :param percent(float): percent of data used as training data. :return: training data(DataFrame) and testing data(DataFrame) """ rows = len(data) train_rows = math.floor(rows * percent) test_rows = rows - train_rows return data.iloc[:train_rows], data.iloc[-test_rows:]
Example #24
Source Project: backtrader-cn Author: pandalibin File: ma.py License: GNU General Public License v3.0 | 5 votes |
def get_params_list(cls, training_data, stock_id): """ Get the params list for finding the best strategy. :param training_data(DateFrame): data for training. :param stock_id(integer): stock on which strategy works. :return: list(dict) """ params_list = [] data_len = len(training_data) ma_l_len = math.floor(data_len * 0.2) # data_len = 10 # ma_s_len is [1, data_len * 0.1) ma_s_len = math.floor(data_len * 0.1) for i in range(1, int(ma_s_len)): for j in range(i + 1, int(ma_l_len), 5): params = dict( ma_period_s=i, ma_period_l=j, stock_id=stock_id ) params_list.append(params) return params_list
Example #25
Source Project: drydock Author: airshipit File: test_maasdriver_calculate_bytes.py License: Apache License 2.0 | 5 votes |
def test_calculate_percent_blockdev(self): '''Convert a percent of total blockdev space to explicit byte count.''' drive_size = 20 * 10**6 # 20 mb drive part_size = math.floor(.2 * drive_size) # calculate 20% of drive size size_str = '20%' drive = BlockDevice(None, size=drive_size, available_size=drive_size) calc_size = ApplyNodeStorage.calculate_bytes( size_str=size_str, context=drive) assert calc_size == part_size
Example #26
Source Project: drydock Author: airshipit File: test_maasdriver_calculate_bytes.py License: Apache License 2.0 | 5 votes |
def test_calculate_percent_vg(self): '''Convert a percent of total blockdev space to explicit byte count.''' vg_size = 20 * 10**6 # 20 mb drive lv_size = math.floor(.2 * vg_size) # calculate 20% of drive size size_str = '20%' vg = VolumeGroup(None, size=vg_size, available_size=vg_size) calc_size = ApplyNodeStorage.calculate_bytes( size_str=size_str, context=vg) assert calc_size == lv_size
Example #27
Source Project: gated-graph-transformer-network Author: hexahedria File: main.py License: MIT License | 5 votes |
def helper_trim(bucketed, desired_total): """Trim bucketed fairly so that it has desired_total things total""" cur_total = sum(len(b) for b in bucketed) keep_frac = desired_total/cur_total if keep_frac > 1.0: print("WARNING: Asked to trim to {} items, but was already only {} items. Keeping original length.".format(desired_total, cur_total)) return bucketed keep_amts = [math.floor(len(b) * keep_frac) for b in bucketed] tmp_total = sum(keep_amts) addtl_to_add = desired_total - tmp_total assert addtl_to_add >= 0 keep_amts = [x + (1 if i < addtl_to_add else 0) for i,x in enumerate(keep_amts)] assert sum(keep_amts) == desired_total trimmed_bucketed = [b[:amt] for b,amt in zip(bucketed, keep_amts)] return trimmed_bucketed
Example #28
Source Project: Learning-Concurrency-in-Python Author: PacktPublishing File: poolImprovement.py License: MIT License | 5 votes |
def is_prime(n): if n % 2 == 0: return False sqrt_n = int(math.floor(math.sqrt(n))) for i in range(3, sqrt_n + 1, 2): if n % i == 0: return False return True
Example #29
Source Project: Learning-Concurrency-in-Python Author: PacktPublishing File: mpExample.py License: MIT License | 5 votes |
def is_prime(n): if n % 2 == 0: return False sqrt_n = int(math.floor(math.sqrt(n))) for i in range(3, sqrt_n + 1, 2): if n % i == 0: return False return True
Example #30
Source Project: mmdetection Author: open-mmlab File: wrappers.py License: Apache License 2.0 | 5 votes |
def forward(self, x): if x.numel() == 0 and torch.__version__ <= '1.4': out_shape = list(x.shape[:2]) for i, k, p, s, d in zip(x.shape[-2:], _pair(self.kernel_size), _pair(self.padding), _pair(self.stride), _pair(self.dilation)): o = (i + 2 * p - (d * (k - 1) + 1)) / s + 1 o = math.ceil(o) if self.ceil_mode else math.floor(o) out_shape.append(o) empty = NewEmptyTensorOp.apply(x, out_shape) return empty return super().forward(x)