Python math.pow() Examples
The following are 30
code examples of math.pow().
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: run.py From TiebaTool with MIT License | 8 votes |
def calculate_similarity(text1,text2): raw1 = jieba.cut(text1) raw2 = jieba.cut(text2) raw1 = Counter(raw1) raw2 = Counter(raw2) same_words = set(raw1) & set(raw2) if (math.sqrt(len(raw1)) * math.sqrt(len(raw2))) != 0: dot_product = 0 mod1 = 0 mod2 = 0 for word in same_words: dot_product += raw1[word] * raw2[word] for word in raw1: mod1 += math.pow(raw1[word],2) for word in raw2: mod2 += math.pow(raw2[word],2) cos = dot_product/math.sqrt(mod1*mod2) else: cos = 0 return cos
Example #2
Source File: text8_data.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 6 votes |
def _load_data(name): buf = open(name).read() tks = buf.split(' ') vocab = {} freq = [0] data = [] for tk in tks: if len(tk) == 0: continue if tk not in vocab: vocab[tk] = len(vocab) + 1 freq.append(0) wid = vocab[tk] data.append(wid) freq[wid] += 1 negative = [] for i, v in enumerate(freq): if i == 0 or v < 5: continue v = int(math.pow(v * 1.0, 0.75)) negative += [i for _ in range(v)] return data, negative, vocab, freq
Example #3
Source File: utils.py From VTuber_Unity with MIT License | 6 votes |
def _gaussian( size=3, sigma=0.25, amplitude=1, normalize=False, width=None, height=None, sigma_horz=None, sigma_vert=None, mean_horz=0.5, mean_vert=0.5): # handle some defaults if width is None: width = size if height is None: height = size if sigma_horz is None: sigma_horz = sigma if sigma_vert is None: sigma_vert = sigma center_x = mean_horz * width + 0.5 center_y = mean_vert * height + 0.5 gauss = np.empty((height, width), dtype=np.float32) # generate kernel for i in range(height): for j in range(width): gauss[i][j] = amplitude * math.exp(-(math.pow((j + 1 - center_x) / ( sigma_horz * width), 2) / 2.0 + math.pow((i + 1 - center_y) / (sigma_vert * height), 2) / 2.0)) if normalize: gauss = gauss / np.sum(gauss) return gauss
Example #4
Source File: sabre-mmsys18.py From sabre with BSD 2-Clause "Simplified" License | 6 votes |
def push(self, time, tput, lat): global throughput global latency for i in range(len(self.half_life)): alpha = math.pow(0.5, time / self.half_life[i]) self.throughput[i] = alpha * self.throughput[i] + (1 - alpha) * tput alpha = math.pow(0.5, 1 / self.latency_half_life[i]) self.latency[i] = alpha * self.latency[i] + (1 - alpha) * lat self.weight_throughput += time self.weight_latency += 1 tput = None lat = None for i in range(len(self.half_life)): zero_factor = 1 - math.pow(0.5, self.weight_throughput / self.half_life[i]) t = self.throughput[i] / zero_factor tput = t if tput == None else min(tput, t) # conservative case is min zero_factor = 1 - math.pow(0.5, self.weight_latency / self.latency_half_life[i]) l = self.latency[i] / zero_factor lat = l if lat == None else max(lat, l) # conservative case is max throughput = tput latency = lat
Example #5
Source File: util.py From BiblioPixel with MIT License | 6 votes |
def genVector(width, height, x_mult=1, y_mult=1): """ Generates a map of vector lengths from the center point to each coordinate. width - width of matrix to generate height - height of matrix to generate x_mult - value to scale x-axis by y_mult - value to scale y-axis by """ center_x = (width - 1) / 2 center_y = (height - 1) / 2 def length(x, y): dx = math.pow(x - center_x, 2 * x_mult) dy = math.pow(y - center_y, 2 * y_mult) return int(math.sqrt(dx + dy)) return [[length(x, y) for x in range(width)] for y in range(height)]
Example #6
Source File: utils.py From AdaptiveWingLoss with Apache License 2.0 | 6 votes |
def _gaussian( size=3, sigma=0.25, amplitude=1, normalize=False, width=None, height=None, sigma_horz=None, sigma_vert=None, mean_horz=0.5, mean_vert=0.5): # handle some defaults if width is None: width = size if height is None: height = size if sigma_horz is None: sigma_horz = sigma if sigma_vert is None: sigma_vert = sigma center_x = mean_horz * width + 0.5 center_y = mean_vert * height + 0.5 gauss = np.empty((height, width), dtype=np.float32) # generate kernel for i in range(height): for j in range(width): gauss[i][j] = amplitude * math.exp(-(math.pow((j + 1 - center_x) / ( sigma_horz * width), 2) / 2.0 + math.pow((i + 1 - center_y) / (sigma_vert * height), 2) / 2.0)) if normalize: gauss = gauss / np.sum(gauss) return gauss
Example #7
Source File: train_csd.py From CSD-SSD with MIT License | 6 votes |
def rampweight(iteration): ramp_up_end = 32000 ramp_down_start = 100000 if(iteration<ramp_up_end): ramp_weight = math.exp(-5 * math.pow((1 - iteration / ramp_up_end),2)) elif(iteration>ramp_down_start): ramp_weight = math.exp(-12.5 * math.pow((1 - (120000 - iteration) / 20000),2)) else: ramp_weight = 1 if(iteration==0): ramp_weight = 0 return ramp_weight
Example #8
Source File: spec.py From hadrian with Apache License 2.0 | 6 votes |
def nChooseK(n, k): # is n an integer? nInt = (math.floor(n) == n) if n == k or k == 0: return 1 if (n < k) or (k < 0): raise Exception if (nInt) and (n < 0.0): b = pow(-1.0, k) * math.exp(math.lgamma(abs(n + k)) \ - math.lgamma(k + 1.0) \ - math.lgamma(abs(n))) return round(b) if (n >= k): b = math.exp(math.lgamma(n + 1.0) - math.lgamma(k + 1.0) \ - math.lgamma(n - k + 1.0)) return round(b) if not (nInt) and (n < k): b = (1.0/math.pi) * math.exp(math.lgamma(n + 1.0) \ - math.lgamma(k + 1) \ + math.lgamma(k - n) \ + math.log(math.sin(math.pi * (n - k + 1.0)))) return round(b) return 0.0
Example #9
Source File: util.py From holodeck with MIT License | 6 votes |
def human_readable_size(size_bytes): """Gets a number of bytes as a human readable string. Args: size_bytes (:obj:`int`): The number of bytes to get as human readable. Returns: :obj:`str`: The number of bytes in a human readable form. """ if size_bytes == 0: return "0B" size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") base = int(math.floor(math.log(size_bytes, 1024))) power = math.pow(1024, base) size = round(size_bytes / power, 2) return "%s %s" % (size, size_name[base])
Example #10
Source File: misc.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 6 votes |
def __call__(self, iteration): """ Call to schedule current learning rate. Parameters ---------- iteration: int Current iteration count. """ if not self.init: self.init = True self.old_lr = self.base_lr lr = self.base_lr * math.pow(self.factor, int(iteration / self.step)) if lr != self.old_lr: self.old_lr = lr logging.info("At Iteration [%d]: Swith to new learning rate %.5f", iteration, lr) return lr
Example #11
Source File: functions.py From worker with GNU General Public License v3.0 | 6 votes |
def pow(requestContext, seriesList, factor): """ Takes one metric or a wildcard seriesList followed by a constant, and raises the datapoint by the power of the constant provided at each point. Example: .. code-block:: none &target=pow(Server.instance01.threads.busy,10) &target=pow(Server.instance*.threads.busy,10) """ yield defer.succeed(None) for series in seriesList: series.name = "pow(%s,%g)" % (series.name, float(factor)) series.pathExpression = series.name for i, value in enumerate(series): series[i] = safePow(value, factor) returnValue(seriesList)
Example #12
Source File: demo.py From unicorn-hat-hd with MIT License | 6 votes |
def swirl(x, y, step): x -= (u_width / 2) y -= (u_height / 2) dist = math.sqrt(pow(x, 2) + pow(y, 2)) / 2.0 angle = (step / 10.0) + (dist * 1.5) s = math.sin(angle) c = math.cos(angle) xs = x * c - y * s ys = x * s + y * c r = abs(xs + ys) r = r * 12.0 r -= 20 return (r, r + (s * 130), r + (c * 130)) # roto-zooming checker board
Example #13
Source File: sabre.py From sabre with BSD 2-Clause "Simplified" License | 6 votes |
def push(self, time, tput, lat): global throughput global latency for i in range(len(self.half_life)): alpha = math.pow(0.5, time / self.half_life[i]) self.throughput[i] = alpha * self.throughput[i] + (1 - alpha) * tput alpha = math.pow(0.5, 1 / self.latency_half_life[i]) self.latency[i] = alpha * self.latency[i] + (1 - alpha) * lat self.weight_throughput += time self.weight_latency += 1 tput = None lat = None for i in range(len(self.half_life)): zero_factor = 1 - math.pow(0.5, self.weight_throughput / self.half_life[i]) t = self.throughput[i] / zero_factor tput = t if tput == None else min(tput, t) # conservative case is min zero_factor = 1 - math.pow(0.5, self.weight_latency / self.latency_half_life[i]) l = self.latency[i] / zero_factor lat = l if lat == None else max(lat, l) # conservative case is max throughput = tput latency = lat
Example #14
Source File: bloom.py From BiblioPixelAnimations with MIT License | 6 votes |
def genCubeVector(x, y, z, x_mult=1, y_mult=1, z_mult=1): """Generates a map of vector lengths from the center point to each coordinate x - width of matrix to generate y - height of matrix to generate z - depth of matrix to generate x_mult - value to scale x-axis by y_mult - value to scale y-axis by z_mult - value to scale z-axis by """ cX = (x - 1) / 2.0 cY = (y - 1) / 2.0 cZ = (z - 1) / 2.0 def vect(_x, _y, _z): return int(math.sqrt(math.pow(_x - cX, 2 * x_mult) + math.pow(_y - cY, 2 * y_mult) + math.pow(_z - cZ, 2 * z_mult))) return [[[vect(_x, _y, _z) for _z in range(z)] for _y in range(y)] for _x in range(x)]
Example #15
Source File: graph_layout.py From EDeN with MIT License | 6 votes |
def _compute_dE(self, pos=None, lengths=None, weights=None, m=None): dEx = 0 dEy = 0 d2Ex2 = 0 d2Ey2 = 0 d2Exy = 0 d2Eyx = 0 for i in pos: if i != m: xmi = pos[m][0] - pos[i][0] ymi = pos[m][1] - pos[i][1] xmi2 = xmi * xmi ymi2 = ymi * ymi xmi_ymi2 = xmi2 + ymi2 lmi = lengths[m][i] kmi = weights[m][i] / (lmi * lmi) dEx += kmi * (xmi - (lmi * xmi) / math.sqrt(xmi_ymi2)) dEy += kmi * (ymi - (lmi * ymi) / math.sqrt(xmi_ymi2)) d2Ex2 += kmi * (1 - (lmi * ymi2) / math.pow(xmi_ymi2, 1.5)) d2Ey2 += kmi * (1 - (lmi * xmi2) / math.pow(xmi_ymi2, 1.5)) res = kmi * (lmi * xmi * ymi) / math.pow(xmi_ymi2, 1.5) d2Exy += res d2Eyx += res return dEx, dEy, d2Ex2, d2Ey2, d2Exy, d2Eyx
Example #16
Source File: GXDLMSRegister.py From Gurux.DLMS.Python with GNU General Public License v2.0 | 6 votes |
def setValue(self, settings, e): if e.index == 1: self.logicalName = _GXCommon.toLogicalName(e.value) elif e.index == 2: if self.scaler != 1 and e.value is not None: try: if settings.isServer: self.value = e.value else: self.value = e.value * self.scaler except Exception: # Sometimes scaler is set for wrong Object type. self.value = e.value else: self.value = e.value elif e.index == 3: # Set default values. if not e.value: self.scaler = 1 self.unit = Unit.NONE else: self.scaler = math.pow(10, e.value[0]) self.unit = Unit(e.value[1]) else: e.error = ErrorCode.READ_WRITE_DENIED
Example #17
Source File: sabre-tomm19.py From sabre with BSD 2-Clause "Simplified" License | 6 votes |
def push(self, time, tput, lat): global throughput global latency for i in range(len(self.half_life)): alpha = math.pow(0.5, time / self.half_life[i]) self.throughput[i] = alpha * self.throughput[i] + (1 - alpha) * tput alpha = math.pow(0.5, 1 / self.latency_half_life[i]) self.latency[i] = alpha * self.latency[i] + (1 - alpha) * lat self.weight_throughput += time self.weight_latency += 1 tput = None lat = None for i in range(len(self.half_life)): zero_factor = 1 - math.pow(0.5, self.weight_throughput / self.half_life[i]) t = self.throughput[i] / zero_factor tput = t if tput == None else min(tput, t) # conservative case is min zero_factor = 1 - math.pow(0.5, self.weight_latency / self.latency_half_life[i]) l = self.latency[i] / zero_factor lat = l if lat == None else max(lat, l) # conservative case is max throughput = tput latency = lat
Example #18
Source File: repeat_factor.py From Parsing-R-CNN with MIT License | 5 votes |
def _get_repeat_factors(self, dataset_dicts): """ Compute (fractional) per-image repeat factors. Args: dataset_dicts (list) : per-image annotations Returns: torch.Tensor: the i-th element is the repeat factor for the dataset_dicts image at index i. """ # 1. For each category c, compute the fraction of images that contain it: f(c) category_freq = defaultdict(int) for dataset_dict in dataset_dicts: # For each image (without repeats) cat_ids = {ann["category_id"] for ann in dataset_dict["annotations"]} for cat_id in cat_ids: category_freq[cat_id] += 1 num_images = len(dataset_dicts) for k, v in category_freq.items(): category_freq[k] = v / num_images # 2. For each category c, compute the category-level repeat factor: # lvis paper: r(c) = max(1, sqrt(t / f(c))) # common: r(c) = max(i, min(a,pow(t / f(c),alpha))) category_rep = { cat_id: max(self.config.MIN_REPEAT_TIMES, min(self.config.MAX_REPEAT_TIMES, math.pow( (self.config.REPEAT_THRESHOLD / cat_freq), self.config.POW))) for cat_id, cat_freq in category_freq.items() } # 3. For each image I, compute the image-level repeat factor: # r(I) = max_{c in I} r(c) rep_factors = [] for dataset_dict in dataset_dicts: cat_ids = {ann["category_id"] for ann in dataset_dict["annotations"]} rep_factor = max({category_rep[cat_id] for cat_id in cat_ids}) rep_factors.append(rep_factor) logging_rank('max(rep_factors): {} , min(rep_factors): {} , len(rep_factors): {}'. format(max(rep_factors), min(rep_factors), len(rep_factors)), distributed=1, local_rank=self.rank) return torch.tensor(rep_factors, dtype=torch.float32)
Example #19
Source File: math_utils.py From ludwig with Apache License 2.0 | 5 votes |
def convert_size(size_bytes): if size_bytes == 0: return '0B' size_name = ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB') i = int(math.floor(math.log(size_bytes, 1024))) p = math.pow(1024, i) s = round(size_bytes / p, 2) return '{} {}'.format(s, size_name[i])
Example #20
Source File: PILTransform.py From ext_portrait_segmentation with MIT License | 5 votes |
def __call__(self, rgb_img, label_img): w, h = rgb_img.size rand_log_scale = math.log(self.scale[0], 2) + random.random() * (math.log(self.scale[1], 2) - math.log(self.scale[0], 2)) random_scale = math.pow(2, rand_log_scale) new_size = (int(round(w * random_scale)), int(round(h * random_scale))) rgb_img = rgb_img.resize(new_size, Image.ANTIALIAS) label_img = label_img.resize(new_size, Image.NEAREST) return rgb_img, label_img
Example #21
Source File: number.py From mathematics_dataset with Apache License 2.0 | 5 votes |
def integer(entropy, signed, min_abs=0, coprime_to=1): """Returns an integer from a set of size ceil(10**entropy). If `signed` is True, then includes negative integers, otherwise includes just positive integers. Args: entropy: Float >= 0. signed: Boolean. Whether to also return negative numbers. min_abs: Integer >= 0. The minimum absolute value. coprime_to: Optional integer >= 1. The returned integer is guaranteed to be coprime to `coprime_to`, with entropy still accounted for. Returns: Integer. """ assert isinstance(min_abs, int) and not isinstance(min_abs, bool) coprime_to = abs(coprime_to) assert min_abs >= 0 max_ = math.pow(10, entropy) max_ += min_abs if coprime_to >= 2: max_ = max_ / _coprime_density(coprime_to) + 1 if signed: max_ = int(math.ceil(max_ / 2)) range_ = [-max_, max_] else: max_ = int(math.ceil(max_)) range_ = [min_abs, max_] while True: value = random.randint(*range_) if abs(value) >= min_abs and sympy.gcd(value, coprime_to) == 1: break return sympy.Integer(value)
Example #22
Source File: transforms_rbbox.py From AerialDetection with Apache License 2.0 | 5 votes |
def cal_line_length(point1, point2): return math.sqrt( math.pow(point1[0] - point2[0], 2) + math.pow(point1[1] - point2[1], 2))
Example #23
Source File: stats.py From OpenBench with GNU General Public License v3.0 | 5 votes |
def bayeselo_to_proba(elo, drawelo): pwin = 1.0 / (1.0 + math.pow(10.0, (-elo + drawelo) / 400.0)) ploss = 1.0 / (1.0 + math.pow(10.0, ( elo + drawelo) / 400.0)) pdraw = 1.0 - pwin - ploss return pwin, pdraw, ploss
Example #24
Source File: fao.py From PyETo with BSD 3-Clause "New" or "Revised" License | 5 votes |
def net_out_lw_rad(tmin, tmax, sol_rad, cs_rad, avp): """ Estimate net outgoing longwave radiation. This is the net longwave energy (net energy flux) leaving the earth's surface. It is proportional to the absolute temperature of the surface raised to the fourth power according to the Stefan-Boltzmann law. However, water vapour, clouds, carbon dioxide and dust are absorbers and emitters of longwave radiation. This function corrects the Stefan- Boltzmann law for humidity (using actual vapor pressure) and cloudiness (using solar radiation and clear sky radiation). The concentrations of all other absorbers are assumed to be constant. The output can be converted to equivalent evaporation [mm day-1] using ``energy2evap()``. Based on FAO equation 39 in Allen et al (1998). :param tmin: Absolute daily minimum temperature [degrees Kelvin] :param tmax: Absolute daily maximum temperature [degrees Kelvin] :param sol_rad: Solar radiation [MJ m-2 day-1]. If necessary this can be estimated using ``sol+rad()``. :param cs_rad: Clear sky radiation [MJ m-2 day-1]. Can be estimated using ``cs_rad()``. :param avp: Actual vapour pressure [kPa]. Can be estimated using functions with names beginning with 'avp_from'. :return: Net outgoing longwave radiation [MJ m-2 day-1] :rtype: float """ tmp1 = (STEFAN_BOLTZMANN_CONSTANT * ((math.pow(tmax, 4) + math.pow(tmin, 4)) / 2)) tmp2 = (0.34 - (0.14 * math.sqrt(avp))) tmp3 = 1.35 * (sol_rad / cs_rad) - 0.35 return tmp1 * tmp2 * tmp3
Example #25
Source File: fao.py From PyETo with BSD 3-Clause "New" or "Revised" License | 5 votes |
def delta_svp(t): """ Estimate the slope of the saturation vapour pressure curve at a given temperature. Based on equation 13 in Allen et al (1998). If using in the Penman-Monteith *t* should be the mean air temperature. :param t: Air temperature [deg C]. Use mean air temperature for use in Penman-Monteith. :return: Saturation vapour pressure [kPa degC-1] :rtype: float """ tmp = 4098 * (0.6108 * math.exp((17.27 * t) / (t + 237.3))) return tmp / math.pow((t + 237.3), 2)
Example #26
Source File: fao.py From PyETo with BSD 3-Clause "New" or "Revised" License | 5 votes |
def atm_pressure(altitude): """ Estimate atmospheric pressure from altitude. Calculated using a simplification of the ideal gas law, assuming 20 degrees Celsius for a standard atmosphere. Based on equation 7, page 62 in Allen et al (1998). :param altitude: Elevation/altitude above sea level [m] :return: atmospheric pressure [kPa] :rtype: float """ tmp = (293.0 - (0.0065 * altitude)) / 293.0 return math.pow(tmp, 5.26) * 101.3
Example #27
Source File: trimming.py From NURBS-Python with MIT License | 5 votes |
def detect_intersection(start_pt, end_pt, test_pt, tol): dist_num = abs(((end_pt[1] - start_pt[1]) * test_pt[0]) - ((end_pt[0] - start_pt[0]) * test_pt[1]) + (end_pt[0] * start_pt[1]) - (end_pt[1] * start_pt[0])) dist_denom = math.sqrt(math.pow(end_pt[1] - start_pt[1], 2) + math.pow(end_pt[0] - start_pt[0], 2)) dist = dist_num / dist_denom if abs(dist) < tol: return True return False
Example #28
Source File: linalg.py From NURBS-Python with MIT License | 5 votes |
def matrix_pivot(m, sign=False): """ Computes the pivot matrix for M, a square matrix. This function computes * the permutation matrix, :math:`P` * the product of M and P, :math:`M \\times P` * determinant of P, :math:`det(P)` if ``sign = True`` :param m: input matrix :type m: list, tuple :param sign: flag to return the determinant of the permutation matrix, P :type sign: bool :return: a tuple containing the matrix product of M x P, P and det(P) :rtype: tuple """ mp = deepcopy(m) n = len(mp) p = matrix_identity(n) # permutation matrix num_rowswap = 0 for j in range(0, n): row = j a_max = 0.0 for i in range(j, n): a_abs = abs(mp[i][j]) if a_abs > a_max: a_max = a_abs row = i if j != row: num_rowswap += 1 for q in range(0, n): # Swap rows p[j][q], p[row][q] = p[row][q], p[j][q] mp[j][q], mp[row][q] = mp[row][q], mp[j][q] if sign: return mp, p, math.pow(-1, num_rowswap) return mp, p
Example #29
Source File: mask_head.py From vehicle_counting_tensorflow with MIT License | 5 votes |
def _get_mask_predictor_conv_depth(self, num_feature_channels, num_classes, class_weight=3.0, feature_weight=2.0): """Computes the depth of the mask predictor convolutions. Computes the depth of the mask predictor convolutions given feature channels and number of classes by performing a weighted average of the two in log space to compute the number of convolution channels. The weights that are used for computing the weighted average do not need to sum to 1. Args: num_feature_channels: An integer containing the number of feature channels. num_classes: An integer containing the number of classes. class_weight: Class weight used in computing the weighted average. feature_weight: Feature weight used in computing the weighted average. Returns: An integer containing the number of convolution channels used by mask predictor. """ num_feature_channels_log = math.log(float(num_feature_channels), 2.0) num_classes_log = math.log(float(num_classes), 2.0) weighted_num_feature_channels_log = ( num_feature_channels_log * feature_weight) weighted_num_classes_log = num_classes_log * class_weight total_weight = feature_weight + class_weight num_conv_channels_log = round( (weighted_num_feature_channels_log + weighted_num_classes_log) / total_weight) return int(math.pow(2.0, num_conv_channels_log))
Example #30
Source File: dota_utils.py From AerialDetection with Apache License 2.0 | 5 votes |
def cal_line_length(point1, point2): return math.sqrt( math.pow(point1[0] - point2[0], 2) + math.pow(point1[1] - point2[1], 2))