本文整理匯總了Python中math.fsum方法的典型用法代碼示例。如果您正苦於以下問題:Python math.fsum方法的具體用法?Python math.fsum怎麽用?Python math.fsum使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類math
的用法示例。
在下文中一共展示了math.fsum方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: import math [as 別名]
# 或者: from math import fsum [as 別名]
def __init__(self, pdf_corr, pdf_err, model, conditions, pdf_undec=None, pdf_evolution=None):
"""Create a Solution object from the results of a model
simulation.
Constructor takes four arguments.
- `pdf_corr` - a size N numpy ndarray describing the correct portion of the joint pdf
- `pdf_err` - a size N numpy ndarray describing the error portion of the joint pdf
- `model` - the Model object used to generate `pdf_corr` and `pdf_err`
- `conditions` - a dictionary of condition names/values used to generate the solution
- `pdf_undec` - a size M numpy ndarray describing the final state of the simulation. None if unavailable.
- `pdf_evolution` - a size M-by-N numpy ndarray describing the state of the simulation at each time step. None if unavailable.
"""
self.model = copy.deepcopy(model) # TODO this could cause a memory leak if I forget it is there...
self.corr = pdf_corr
self.err = pdf_err
self.undec = pdf_undec
self.evolution = pdf_evolution
# Correct floating point errors to always get prob <= 1
if fsum(self.corr.tolist() + self.err.tolist()) > 1:
self.corr /= 1.00000000001
self.err /= 1.00000000001
self.conditions = conditions
示例2: gamma
# 需要導入模塊: import math [as 別名]
# 或者: from math import fsum [as 別名]
def gamma(z, sqrt2pi=(2.0*pi)**0.5):
# Reflection to right half of complex plane
if z < 0.5:
return pi / sin(pi*z) / gamma(1.0-z)
# Lanczos approximation with g=7
az = z + (7.0 - 0.5)
return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([
0.9999999999995183,
676.5203681218835 / z,
-1259.139216722289 / (z+1.0),
771.3234287757674 / (z+2.0),
-176.6150291498386 / (z+3.0),
12.50734324009056 / (z+4.0),
-0.1385710331296526 / (z+5.0),
0.9934937113930748e-05 / (z+6.0),
0.1659470187408462e-06 / (z+7.0),
])
示例3: main
# 需要導入模塊: import math [as 別名]
# 或者: from math import fsum [as 別名]
def main():
for repository in _REPOSITORIES:
commit_times = CommitTimes(repository, _REVISION_COUNT)
commit_durations = []
for time1, time2 in Pairwise(commit_times):
#if not (IsWeekday(time1) and IsWeekday(time2)):
# continue
commit_durations.append((time1 - time2).total_seconds() / 60.)
commit_durations.sort()
print 'REPOSITORY:', repository
print 'Start Date:', min(commit_times), 'PDT'
print ' End Date:', max(commit_times), 'PDT'
print ' Duration:', max(commit_times) - min(commit_times)
print ' n:', len(commit_times)
for p in (0.25, 0.50, 0.90):
percentile = Percentile(commit_durations, p)
print '%3d%% commit duration:' % (p * 100), '%6.1fm' % percentile
mean = math.fsum(commit_durations) / len(commit_durations)
print 'Mean commit duration:', '%6.1fm' % mean
print
示例4: _quadratic_constraints
# 需要導入模塊: import math [as 別名]
# 或者: from math import fsum [as 別名]
def _quadratic_constraints(self) -> bool:
feasible = True
for quad_cst in self._src.quadratic_constraints:
const1, lin1 = self._linear_expression(quad_cst.linear)
const2, lin2, quadratic = self._quadratic_expression(quad_cst.quadratic)
rhs = -fsum([-quad_cst.rhs] + const1 + const2)
linear = lin1.coefficients + lin2.coefficients
if quadratic.coefficients.nnz > 0:
self._dst.quadratic_constraint(name=quad_cst.name, linear=linear,
quadratic=quadratic.coefficients,
sense=quad_cst.sense, rhs=rhs)
elif linear.nnz > 0:
name = quad_cst.name
lin_names = set(lin.name for lin in self._dst.linear_constraints)
while name in lin_names:
name = '_' + name
self._dst.linear_constraint(name=name, linear=linear, sense=quad_cst.sense, rhs=rhs)
else:
if not self._feasible(quad_cst.sense, rhs):
logger.warning('constraint %s is infeasible due to substitution', quad_cst.name)
feasible = False
return feasible
示例5: draw_minicircles
# 需要導入模塊: import math [as 別名]
# 或者: from math import fsum [as 別名]
def draw_minicircles(self):
ttl = int(fsum(self.numbers))
angle_step = 2 * pi / ttl
angle_start = -pi / 2
r = self.size // 2.5
r2 = self.size // 17
# manually draw the arc - the 100% width of the arc does not impress
for i in range(ttl):
# angle for line
angle = angle_start + angle_step * i
# Calculate the x,y for the end point
x = r * cos(angle) + self.center[0]
y = r * sin(angle) + self.center[1]
if i < self.numbers[0]:
pygame.draw.circle(self.canvas, self.color1, [int(x), int(y)], r2, 0)
pygame.draw.circle(self.canvas, self.border_color1, [int(x), int(y)], r2, 2)
elif i < self.numbers[0] + self.numbers[1]:
pygame.draw.circle(self.canvas, self.color2, [int(x), int(y)], r2, 0)
pygame.draw.circle(self.canvas, self.border_color2, [int(x), int(y)], r2, 2)
else:
pygame.draw.circle(self.canvas, self.color3, [int(x), int(y)], r2, 0)
pygame.draw.circle(self.canvas, self.border_color3, [int(x), int(y)], r2, 2)
# Draw the line from the self.center to the calculated end point
示例6: test_toy_geometric
# 需要導入模塊: import math [as 別名]
# 或者: from math import fsum [as 別名]
def test_toy_geometric():
mesh = meshplex.read(this_dir / "meshes" / "toy.vtk")
mesh = meshplex.MeshTetra(mesh.node_coords, mesh.cells["nodes"])
run(
mesh,
volume=9.3875504672601107,
convol_norms=[0.20175742659663737, 0.0093164692200450819],
ce_ratio_norms=[13.497977312281323, 0.42980191511570004],
cellvol_norms=[0.091903119589148916, 0.0019959463063558944],
tol=1.0e-6,
)
cc = mesh.cell_circumcenters
cc_norm_2 = fsum(cc.flat)
cc_norm_inf = max(cc.flat)
assert abs(cc_norm_2 - 1103.7038287583791) < 1.0e-12
assert abs(cc_norm_inf - 3.4234008596539662) < 1.0e-12
示例7: sentence_bleu_4
# 需要導入模塊: import math [as 別名]
# 或者: from math import fsum [as 別名]
def sentence_bleu_4(hyp, refs, weights=[0.25, 0.25, 0.25, 0.25]):
# input : single sentence, multiple references
count = [0, 0, 0, 0]
clip_count = [0, 0, 0, 0]
r = 0
c = 0
for i in range(4):
hypcnts = Counter(ngrams(hyp, i + 1))
cnt = sum(hypcnts.values())
count[i] += cnt
# compute clipped counts
max_counts = {}
for ref in refs:
refcnts = Counter(ngrams(ref, i + 1))
for ng in hypcnts:
max_counts[ng] = max(max_counts.get(ng, 0), refcnts[ng])
clipcnt = dict((ng, min(count, max_counts[ng])) \
for ng, count in hypcnts.items())
clip_count[i] += sum(clipcnt.values())
bestmatch = [1000, 1000]
for ref in refs:
if bestmatch[0] == 0:
break
diff = abs(len(ref) - len(hyp))
if diff < bestmatch[0]:
bestmatch[0] = diff
bestmatch[1] = len(ref)
r = bestmatch[1]
c = len(hyp)
p0 = 1e-7
bp = math.exp(-abs(1.0 - float(r) / float(c + p0)))
p_ns = [float(clip_count[i]) / float(count[i] + p0) + p0 for i in range(4)]
s = math.fsum(w * math.log(p_n) for w, p_n in zip(weights, p_ns) if p_n)
bleu_hyp = bp * math.exp(s)
return bleu_hyp
示例8: softmax
# 需要導入模塊: import math [as 別名]
# 或者: from math import fsum [as 別名]
def softmax(x):
y = [math.exp(k) for k in x]
sum_y = math.fsum(y)
z = [k/sum_y for k in y]
return z
示例9: run
# 需要導入模塊: import math [as 別名]
# 或者: from math import fsum [as 別名]
def run(mesh, volume, convol_norms, ce_ratio_norms, cellvol_norms, tol=1.0e-12):
# Check cell volumes.
total_cellvolume = fsum(mesh.cell_volumes)
assert abs(volume - total_cellvolume) < tol * volume
norm2 = numpy.linalg.norm(mesh.cell_volumes, ord=2)
norm_inf = numpy.linalg.norm(mesh.cell_volumes, ord=numpy.Inf)
assert near_equal(cellvol_norms, [norm2, norm_inf], tol)
# If everything is Delaunay and the boundary elements aren't flat, the
# volume of the domain is given by
# 1/n * edge_lengths * ce_ratios.
# Unfortunately, this isn't always the case.
# ```
# total_ce_ratio = \
# fsum(mesh.edge_lengths**2 * mesh.get_ce_ratios_per_edge() / dim)
# self.assertAlmostEqual(volume, total_ce_ratio, delta=tol * volume)
# ```
# Check ce_ratio norms.
# TODO reinstate
alpha2 = fsum((mesh.get_ce_ratios() ** 2).flat)
alpha_inf = max(abs(mesh.get_ce_ratios()).flat)
assert near_equal(ce_ratio_norms, [alpha2, alpha_inf], tol)
# Check the volume by summing over the absolute value of the control
# volumes.
vol = fsum(mesh.get_control_volumes())
assert abs(volume - vol) < tol * volume
# Check control volume norms.
norm2 = numpy.linalg.norm(mesh.get_control_volumes(), ord=2)
norm_inf = numpy.linalg.norm(mesh.get_control_volumes(), ord=numpy.Inf)
assert near_equal(convol_norms, [norm2, norm_inf], tol)
return
示例10: partition_width
# 需要導入模塊: import math [as 別名]
# 或者: from math import fsum [as 別名]
def partition_width(self, widths):
"""Determines if the widths are over the maximum available space, and if so shrinks them"""
if math.fsum(widths) + (len(widths) - 1) > self.max_width:
remainder = (int(math.fsum(widths)) + (len(widths) - 1)) - self.max_width
# Take from the largest column first, eventually evening out
for i in range(remainder):
col_index = widths.index(max(widths))
widths[col_index] -= 1
return widths
示例11: _test
# 需要導入模塊: import math [as 別名]
# 或者: from math import fsum [as 別名]
def _test(v):
# TODO should these be Positive0 instead of Number?
assert v.corr in NDArray(d=1, t=Number), "Invalid corr histogram"
assert v.err in NDArray(d=1, t=Number), "Invalid err histogram"
if v.undec is not None:
assert v.undec in NDArray(d=1, t=Number), "Invalid err histogram"
assert len(v.undec) == len(v.model.x_domain(conditions=v.conditions))
#assert v.model is Generic(Model), "Invalid model" # TODO could cause inf recursion issue
assert len(v.corr) == len(v.err) == len(v.model.t_domain()), "Histogram lengths must match"
assert 0 <= fsum(v.corr.tolist() + v.err.tolist()) <= 1, "Histogram does not integrate " \
" to 1, not to " + str(fsum(v.corr.tolist() + v.err.tolist()))
assert v.conditions in Conditions()
示例12: prob_correct
# 需要導入模塊: import math [as 別名]
# 或者: from math import fsum [as 別名]
def prob_correct(self):
"""Probability of correct response within the time limit."""
return fsum(self.corr)
示例13: prob_error
# 需要導入模塊: import math [as 別名]
# 或者: from math import fsum [as 別名]
def prob_error(self):
"""Probability of incorrect (error) response within the time limit."""
return fsum(self.err)
示例14: prob_undecided
# 需要導入模塊: import math [as 別名]
# 或者: from math import fsum [as 別名]
def prob_undecided(self):
"""The probability of not responding during the time limit."""
udprob = 1 - fsum(self.corr.tolist() + self.err.tolist())
if udprob < 0:
print("Warning, setting undecided probability from %f to 0" % udprob)
udprob = 0
return udprob
示例15: test_pdfs
# 需要導入模塊: import math [as 別名]
# 或者: from math import fsum [as 別名]
def test_pdfs(self):
"""Produce valid distributions which sum to one"""
dt = .02
for n,s in self.samps.items():
if n == "empty": continue
assert np.isclose(fsum([fsum(s.pdf_corr(T_dur=4, dt=dt))*dt, fsum(s.pdf_err(T_dur=4, dt=dt))*dt, s.prob_undecided()]), 1)
assert np.isclose(fsum(s.pdf_corr(T_dur=4, dt=dt)*dt), s.prob_correct())
assert np.isclose(fsum(s.pdf_err(T_dur=4, dt=dt)*dt), s.prob_error())
assert s.mean_decision_time() > 0
if s.prob_undecided() == 0:
assert s.prob_correct() == s.prob_correct_forced()
assert s.prob_error() == s.prob_error_forced()
assert len(s.pdf_corr(T_dur=4, dt=dt)) == len(s.t_domain(T_dur=4, dt=dt))