Python math.log1p() Examples
The following are 30
code examples of math.log1p().
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: ironpython2 Author: IronLanguages File: test_math.py License: Apache License 2.0 | 7 votes |
def test_math_subclass(self): """verify subtypes of float/long work w/ math functions""" import math class myfloat(float): pass class mylong(long): pass mf = myfloat(1) ml = mylong(1) for x in math.log, math.log10, math.log1p, math.asinh, math.acosh, math.atanh, math.factorial, math.trunc, math.isinf: try: resf = x(mf) except ValueError: resf = None try: resl = x(ml) except ValueError: resl = None self.assertEqual(resf, resl)
Example #2
Source Project: tensor2tensor Author: tensorflow File: wiki_revision_utils.py License: Apache License 2.0 | 6 votes |
def include_revision(revision_num, skip_factor=1.1): """Decide whether to include a revision. If the number of revisions is large, we exclude some revisions to avoid a quadratic blowup in runtime, since the article is likely also large. We make the ratio between consecutive included revision numbers appproximately equal to "factor". Args: revision_num: an integer skip_factor: a floating point number >= 1.0 Returns: a boolean """ if skip_factor <= 1.0: return True return (int(math.log1p(revision_num) / math.log(skip_factor)) != int( math.log(revision_num + 2.0) / math.log(skip_factor)))
Example #3
Source Project: BERT Author: yyht File: wiki_revision_utils.py License: Apache License 2.0 | 6 votes |
def include_revision(revision_num, skip_factor=1.1): """Decide whether to include a revision. If the number of revisions is large, we exclude some revisions to avoid a quadratic blowup in runtime, since the article is likely also large. We make the ratio between consecutive included revision numbers appproximately equal to "factor". Args: revision_num: an integer skip_factor: a floating point number >= 1.0 Returns: a boolean """ if skip_factor <= 1.0: return True return (int(math.log1p(revision_num) / math.log(skip_factor)) != int( math.log(revision_num + 2.0) / math.log(skip_factor)))
Example #4
Source Project: ADRpy Author: sobester File: atmospheres.py License: GNU General Public License v3.0 | 6 votes |
def _isapressalt_m(self, pressure_pa): """Returns the geopotential alt (m) at which ISA has the given pressure""" press_it = np.nditer([pressure_pa, None]) for press_pa, alt_m in press_it: if press_pa > self._pLevel1: # Troposphere alt_m[...] = (press_pa ** (1 / self._E1) - self._C1) / self._D1 elif press_pa > self._pLevel2: # Lower stratopshere alt_m[...] = (1 / self._G2) * math.log1p(press_pa / self._F2 - 1) elif press_pa > self._pLevel3: # Upper stratopshere alt_m[...] = (press_pa ** (1 / self._E3) - self._C3) / self._D3 elif press_pa > self._pLevel4: # Between 32 and 47 km alt_m[...] = (press_pa ** (1 / self._E4) - self._C4) / self._D4 else: # Between 47km and 51km alt_m[...] = (1 / self._G5) * math.log1p(press_pa / self._F5 - 1) return press_it.operands[1]
Example #5
Source Project: ADRpy Author: sobester File: atmospheres.py License: GNU General Public License v3.0 | 6 votes |
def _isadensalt_m(self, dens_kgpm3): """Returns the geopotential alt (m) at which ISA has given density (kg/m^3)""" dense_it = np.nditer([dens_kgpm3, None]) for d_kgpm3, alt_m in dense_it: if d_kgpm3 > self._dLevel1: # Troposphere alt_m[...] = (d_kgpm3 ** (1 / self._L1) - self._I1) / self._J1 elif d_kgpm3 > self._dLevel2: # Lower stratopshere alt_m[...] = (1 / self._N2) * math.log1p(dens_kgpm3 / self._M2 - 1) elif d_kgpm3 > self._dLevel3: # Upper stratopshere alt_m[...] = (d_kgpm3 ** (1 / self._L3) - self._I3) / self._J3 elif dens_kgpm3 > self._dLevel4: # Between 32 and 47 km alt_m[...] = (d_kgpm3 ** (1 / self._L4) - self._I4) / self._J4 else: # Between 47km and 51km alt_m[...] = (1 / self._N5) * math.log1p(d_kgpm3 / self._M5 - 1) # Adjust for the temperature offset return dense_it.operands[1]
Example #6
Source Project: ironpython3 Author: IronLanguages File: test_math.py License: Apache License 2.0 | 6 votes |
def test_math_subclass(self): """verify subtypes of float/long work w/ math functions""" import math class myfloat(float): pass class mylong(long): pass mf = myfloat(1) ml = mylong(1) for x in math.log, math.log10, math.log1p, math.asinh, math.acosh, math.atanh, math.factorial, math.trunc, math.isinf: try: resf = x(mf) except ValueError: resf = None try: resl = x(ml) except ValueError: resl = None self.assertEqual(resf, resl)
Example #7
Source Project: Stone-Soup Author: dstl File: numeric.py License: MIT License | 6 votes |
def __add__(self, other): if other < 0: return self - -other log_other = self._log(other) if self.log_value > log_other: log_l, log_s = self.log_value, log_other elif self.log_value < log_other: log_l, log_s = log_other, self.log_value else: # Must be equal, so just double value return self * 2 if log_s == float("-inf"): # Just return largest value return Probability(log_l, log_value=True) return Probability(log_l + log1p(exp(log_s - log_l)), log_value=True)
Example #8
Source Project: Stone-Soup Author: dstl File: numeric.py License: MIT License | 6 votes |
def __sub__(self, other): if other < 0: return self + -other log_other = self._log(other) if self.log_value > log_other: log_l, log_s = self.log_value, log_other elif self.log_value < log_other: # Result will be negative return float(self) - other else: # Must be equal, so return 0 return Probability(float("-inf"), log_value=True) if log_s == float("-inf"): # Just return largest value return Probability(log_l, log_value=True) exp_diff = exp(log_s - log_l) if exp_diff == 1: # Diff too small, so result is effectively zero return Probability(float("-inf"), log_value=True) return Probability(log_l + log1p(-exp_diff), log_value=True)
Example #9
Source Project: Stone-Soup Author: dstl File: numeric.py License: MIT License | 6 votes |
def __rsub__(self, other): if other < 0: # Result will be negative return other + -float(self) log_other = self._log(other) if log_other > self.log_value: log_l, log_s = log_other, self.log_value elif log_other < self.log_value: # Result will be negative return other + -float(self) else: # Must be equal, so return 0 return Probability(float("-inf"), log_value=True) if log_s == float("-inf"): # Just return largest value return Probability(log_l, log_value=True) exp_diff = exp(log_s - log_l) if exp_diff == 1: # Diff too small, so result is effectively zero return Probability(float("-inf"), log_value=True) return Probability(log_l + log1p(-exp_diff), log_value=True)
Example #10
Source Project: hadrian Author: modelop File: dist.py License: Apache License 2.0 | 5 votes |
def PDF(self,x): if (x <= 0.0) or (x >= 1.0): return 0.0 else: logX = math.log(x) if (x < 0.0) and (x > 0.0): return 0.0 log1mX = math.log1p(-x) ret = math.exp((self.alpha - 1.0) * logX + (self.beta - 1.0) \ * log1mX - self.Z) return ret
Example #11
Source Project: workload-collocation-agent Author: intel File: numa_allocator.py License: Apache License 2.0 | 5 votes |
def _get_most_used_nodes(preferences: Preferences) -> Set[int]: d = {} for node in preferences: d[node] = round(math.log1p(preferences[node] * 1000)) nodes = sorted(d.items(), reverse=True, key=lambda x: x[1]) z = nodes[0][1] best_nodes = {x[0] for x in nodes if x[1] == z} return best_nodes
Example #12
Source Project: ironpython2 Author: IronLanguages File: test_math.py License: Apache License 2.0 | 5 votes |
def testLog1p(self): self.assertRaises(TypeError, math.log1p) self.ftest('log1p(1/e -1)', math.log1p(1/math.e-1), -1) self.ftest('log1p(0)', math.log1p(0), 0) self.ftest('log1p(e-1)', math.log1p(math.e-1), 1) self.ftest('log1p(1)', math.log1p(1), math.log(2)) self.assertEqual(math.log1p(INF), INF) self.assertRaises(ValueError, math.log1p, NINF) self.assertTrue(math.isnan(math.log1p(NAN))) n= 2**90 self.assertAlmostEqual(math.log1p(n), 62.383246250395075) self.assertAlmostEqual(math.log1p(n), math.log1p(float(n)))
Example #13
Source Project: transducer Author: awni File: decoders.py License: Apache License 2.0 | 5 votes |
def log_sum_exp(a, b): """ Stable log sum exp. """ return max(a, b) + math.log1p(math.exp(-abs(a-b)))
Example #14
Source Project: BinderFilter Author: dxwu File: test_math.py License: MIT License | 5 votes |
def testLog1p(self): self.assertRaises(TypeError, math.log1p) self.ftest('log1p(1/e -1)', math.log1p(1/math.e-1), -1) self.ftest('log1p(0)', math.log1p(0), 0) self.ftest('log1p(e-1)', math.log1p(math.e-1), 1) self.ftest('log1p(1)', math.log1p(1), math.log(2)) self.assertEqual(math.log1p(INF), INF) self.assertRaises(ValueError, math.log1p, NINF) self.assertTrue(math.isnan(math.log1p(NAN))) n= 2**90 self.assertAlmostEqual(math.log1p(n), 62.383246250395075) self.assertAlmostEqual(math.log1p(n), math.log1p(float(n)))
Example #15
Source Project: oss-ftp Author: aliyun File: test_math.py License: MIT License | 5 votes |
def testLog1p(self): self.assertRaises(TypeError, math.log1p) self.ftest('log1p(1/e -1)', math.log1p(1/math.e-1), -1) self.ftest('log1p(0)', math.log1p(0), 0) self.ftest('log1p(e-1)', math.log1p(math.e-1), 1) self.ftest('log1p(1)', math.log1p(1), math.log(2)) self.assertEqual(math.log1p(INF), INF) self.assertRaises(ValueError, math.log1p, NINF) self.assertTrue(math.isnan(math.log1p(NAN))) n= 2**90 self.assertAlmostEqual(math.log1p(n), 62.383246250395075) self.assertAlmostEqual(math.log1p(n), math.log1p(float(n)))
Example #16
Source Project: m2cgen Author: BayesWitnesses File: test_python.py License: MIT License | 5 votes |
def test_log1p_expr(): expr = ast.Log1pExpr(ast.NumVal(2.0)) interpreter = interpreters.PythonInterpreter() expected_code = """ import math def score(input): return math.log1p(2.0) """ utils.assert_code_equal(interpreter.interpret(expr), expected_code)
Example #17
Source Project: ufora Author: ufora File: MathTestCases.py License: Apache License 2.0 | 5 votes |
def test_pure_python_math_module(self): vals = [1, -.5, 1.5, 0, 0.0, -2, -2.2, .2] # not being tested: math.asinh, math.atanh, math.lgamma, math.erfc, math.acos def f(): functions = [ math.sqrt, math.cos, math.sin, math.tan, math.asin, math.atan, math.acosh, math.cosh, math.sinh, math.tanh, math.ceil, math.erf, math.exp, math.expm1, math.factorial, math.floor, math.log, math.log10, math.log1p ] tr = [] for idx1 in range(len(vals)): v1 = vals[idx1] for funIdx in range(len(functions)): function = functions[funIdx] try: tr = tr + [function(v1)] except ValueError as ex: pass return tr r1 = self.evaluateWithExecutor(f) r2 = f() self.assertGreater(len(r1), 100) self.assertTrue(numpy.allclose(r1, r2, 1e-6))
Example #18
Source Project: abydos Author: chrislit File: _unigram_corpus.py License: GNU General Public License v3.0 | 5 votes |
def idf(self, term: str) -> float: r"""Calculate the Inverse Document Frequency of a term in the corpus. Parameters ---------- term : str The term to calculate the IDF of Returns ------- float The IDF Examples -------- >>> tqbf = 'the quick brown fox jumped over the lazy dog\n\n' >>> tqbf += 'and then it slept\n\n and the dog ran off' >>> corp = UnigramCorpus(tqbf) >>> round(corp.idf('dog'), 10) 0.6931471806 >>> round(corp.idf('the'), 10) 0.6931471806 .. versionadded:: 0.4.0 """ if term in self.corpus: count, term_doc_count = self.corpus[term] return log1p(self.doc_count / term_doc_count) else: return float('inf')
Example #19
Source Project: abydos Author: chrislit File: _consonni_todeschini_iii.py License: GNU General Public License v3.0 | 5 votes |
def sim(self, src: str, tar: str) -> float: """Return the Consonni & Todeschini III similarity of two strings. Parameters ---------- src : str Source string (or QGrams/Counter objects) for comparison tar : str Target string (or QGrams/Counter objects) for comparison Returns ------- float Consonni & Todeschini III similarity Examples -------- >>> cmp = ConsonniTodeschiniIII() >>> cmp.sim('cat', 'hat') 0.1648161441769704 >>> cmp.sim('Niall', 'Neil') 0.1648161441769704 >>> cmp.sim('aluminum', 'Catalan') 0.10396755253417303 >>> cmp.sim('ATCG', 'TAGC') 0.0 .. versionadded:: 0.4.0 """ self._tokenize(src, tar) a = self._intersection_card() n = self._population_unique_card() if src == tar and n <= a: return 1.0 return log1p(a) / log1p(n)
Example #20
Source Project: abydos Author: chrislit File: _token_distance.py License: GNU General Public License v3.0 | 5 votes |
def _norm_log(x: float, _squares: int, _pop: float) -> float: return log1p(x)
Example #21
Source Project: abydos Author: chrislit File: _consonni_todeschini_iv.py License: GNU General Public License v3.0 | 5 votes |
def sim(self, src: str, tar: str) -> float: """Return the Consonni & Todeschini IV similarity of two strings. Parameters ---------- src : str Source string (or QGrams/Counter objects) for comparison tar : str Target string (or QGrams/Counter objects) for comparison Returns ------- float Consonni & Todeschini IV similarity Examples -------- >>> cmp = ConsonniTodeschiniIV() >>> cmp.sim('cat', 'hat') 0.5645750340535796 >>> cmp.sim('Niall', 'Neil') 0.4771212547196623 >>> cmp.sim('aluminum', 'Catalan') 0.244650542118226 >>> cmp.sim('ATCG', 'TAGC') 0.0 .. versionadded:: 0.4.0 """ if src == tar: return 1.0 self._tokenize(src, tar) a = self._intersection_card() b = self._src_only_card() c = self._tar_only_card() return log1p(a) / log1p(a + b + c)
Example #22
Source Project: abydos Author: chrislit File: _consonni_todeschini_ii.py License: GNU General Public License v3.0 | 5 votes |
def sim(self, src: str, tar: str) -> float: """Return the Consonni & Todeschini II similarity of two strings. Parameters ---------- src : str Source string (or QGrams/Counter objects) for comparison tar : str Target string (or QGrams/Counter objects) for comparison Returns ------- float Consonni & Todeschini II similarity Examples -------- >>> cmp = ConsonniTodeschiniII() >>> cmp.sim('cat', 'hat') 0.7585487129939101 >>> cmp.sim('Niall', 'Neil') 0.6880377723094788 >>> cmp.sim('aluminum', 'Catalan') 0.5841297898633079 >>> cmp.sim('ATCG', 'TAGC') 0.640262668568961 .. versionadded:: 0.4.0 """ if src == tar: return 1.0 self._tokenize(src, tar) b = self._src_only_card() c = self._tar_only_card() n = self._population_unique_card() return (log1p(n) - log1p(b + c)) / log1p(n)
Example #23
Source Project: abydos Author: chrislit File: _consonni_todeschini_i.py License: GNU General Public License v3.0 | 5 votes |
def sim(self, src: str, tar: str) -> float: """Return the Consonni & Todeschini I similarity of two strings. Parameters ---------- src : str Source string (or QGrams/Counter objects) for comparison tar : str Target string (or QGrams/Counter objects) for comparison Returns ------- float Consonni & Todeschini I similarity Examples -------- >>> cmp = ConsonniTodeschiniI() >>> cmp.sim('cat', 'hat') 0.9992336018090547 >>> cmp.sim('Niall', 'Neil') 0.998656222829757 >>> cmp.sim('aluminum', 'Catalan') 0.9971098629456009 >>> cmp.sim('ATCG', 'TAGC') 0.9980766131469967 .. versionadded:: 0.4.0 """ if src == tar: return 1.0 self._tokenize(src, tar) a = self._intersection_card() d = self._total_complement_card() n = self._population_unique_card() return log1p(a + d) / log1p(n)
Example #24
Source Project: recsys2019 Author: logicai-io File: accumulators.py License: Apache License 2.0 | 5 votes |
def get_stats(self, row, item): all_events_list = self.all_events_list[row["user_id"]] max_timestamp = row["timestamp"] obs = {} for action_type in all_events_list.keys(): for event_num, new_row in enumerate(all_events_list[action_type][::-1][:10]): impressions = new_row["fake_impressions"] prices = new_row["fake_prices"].split("|") # import ipdb; ipdb.set_trace() if action_type == "clickout item" and event_num <= 1: for rank, (item_id, price) in enumerate(zip(impressions, prices)): price = int(price) obs[f"co_price_{rank:02d}_{event_num:02d}"] = log1p(price) obs[f"{action_type}_{event_num:02d}_timestamp"] = log1p(max_timestamp - new_row["timestamp"]) if new_row["action_type"] in ACTIONS_WITH_ITEM_REFERENCE: impressions = new_row["fake_impressions"] if new_row["reference"] in impressions: obs[f"{action_type}_rank_{event_num:02d}"] = impressions.index(new_row["reference"]) + 1 obs[f"{action_type}_rank_{event_num:02d}_rel"] = item["rank"] - impressions.index( new_row["reference"] ) int_events_list = self.int_events_list[row["user_id"]] for event_num, new_row in enumerate(int_events_list[::-1][:10]): obs[f"interaction_{event_num:02d}_timestamp"] = log1p(max_timestamp - new_row["timestamp"]) impressions = new_row["fake_impressions"] if new_row["reference"] in impressions: obs[f"interaction_rank_{event_num:02d}"] = impressions.index(new_row["reference"]) + 1 obs[f"interaction_rank_{event_num:02d}_rel"] = item["rank"] - impressions.index(new_row["reference"]) return {"actions_tracker": json.dumps(obs)}
Example #25
Source Project: Gun-Detector Author: itsamitgoel File: core.py License: Apache License 2.0 | 5 votes |
def _log1mexp(x): """Numerically stable computation of log(1-exp(x)).""" if x < -1: return math.log1p(-math.exp(x)) elif x < 0: return math.log(-math.expm1(x)) elif x == 0: return -np.inf else: raise ValueError("Argument must be non-positive.")
Example #26
Source Project: Gun-Detector Author: itsamitgoel File: core.py License: Apache License 2.0 | 5 votes |
def compute_logq_gaussian(counts, sigma): """Returns an upper bound on ln Pr[outcome != argmax] for GNMax. Implementation of Proposition 7. Args: counts: A numpy array of scores. sigma: The standard deviation of the Gaussian noise in the GNMax mechanism. Returns: logq: Natural log of the probability that outcome is different from argmax. """ n = len(counts) variance = sigma**2 idx_max = np.argmax(counts) counts_normalized = counts[idx_max] - counts counts_rest = counts_normalized[np.arange(n) != idx_max] # exclude one index # Upper bound q via a union bound rather than a more precise calculation. logq = _logaddexp( scipy.stats.norm.logsf(counts_rest, scale=math.sqrt(2 * variance))) # A sketch of a more accurate estimate, which is currently disabled for two # reasons: # 1. Numerical instability; # 2. Not covered by smooth sensitivity analysis. # covariance = variance * (np.ones((n - 1, n - 1)) + np.identity(n - 1)) # logq = np.log1p(-statsmodels.sandbox.distributions.extras.mvnormcdf( # counts_rest, np.zeros(n - 1), covariance, maxpts=1e4)) return min(logq, math.log(1 - (1 / n)))
Example #27
Source Project: Gun-Detector Author: itsamitgoel File: core.py License: Apache License 2.0 | 5 votes |
def rdp_pure_eps(logq, pure_eps, orders): """Computes the RDP value given logq and pure privacy eps. Implementation of https://arxiv.org/abs/1610.05755, Theorem 3. The bound used is the min of three terms. The first term is from https://arxiv.org/pdf/1605.02065.pdf. The second term is based on the fact that when event has probability (1-q) for q close to zero, q can only change by exp(eps), which corresponds to a much smaller multiplicative change in (1-q) The third term comes directly from the privacy guarantee. Args: logq: Natural logarithm of the probability of a non-optimal outcome. pure_eps: eps parameter for DP orders: array_like list of moments to compute. Returns: Array of upper bounds on rdp (a scalar if orders is a scalar). """ orders_vec = np.atleast_1d(orders) q = math.exp(logq) log_t = np.full_like(orders_vec, np.inf) if q <= 1 / (math.exp(pure_eps) + 1): logt_one = math.log1p(-q) + ( math.log1p(-q) - _log1mexp(pure_eps + logq)) * ( orders_vec - 1) logt_two = logq + pure_eps * (orders_vec - 1) log_t = np.logaddexp(logt_one, logt_two) ret = np.minimum( np.minimum(0.5 * pure_eps * pure_eps * orders_vec, log_t / (orders_vec - 1)), pure_eps) if np.isscalar(orders): return np.asscalar(ret) else: return ret
Example #28
Source Project: Fluid-Designer Author: Microvellum File: test_math.py License: GNU General Public License v3.0 | 5 votes |
def testLog1p(self): self.assertRaises(TypeError, math.log1p) n= 2**90 self.assertAlmostEqual(math.log1p(n), math.log1p(float(n)))
Example #29
Source Project: lopocs Author: Oslandia File: utils.py License: GNU Lesser General Public License v2.1 | 5 votes |
def compute_scale_for_cesium(coordmin, coordmax): ''' Cesium quantized positions need to be in uint16 This function computes the best scale to apply to coordinates to fit the range [0, 65535] ''' max_int = np.iinfo(np.uint16).max delta = abs(coordmax - coordmin) scale = 10 ** -(math.floor(math.log1p(max_int / delta) / math.log1p(10))) return scale
Example #30
Source Project: ironpython3 Author: IronLanguages File: test_math.py License: Apache License 2.0 | 5 votes |
def testLog1p(self): self.assertRaises(TypeError, math.log1p) n= 2**90 self.assertAlmostEqual(math.log1p(n), math.log1p(float(n)))