当前位置: 首页>>代码示例>>Python>>正文


Python math.fsum方法代码示例

本文整理汇总了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 
开发者ID:mwshinn,项目名称:PyDDM,代码行数:25,代码来源:solution.py

示例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),
    ]) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:19,代码来源:test_random.py

示例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 
开发者ID:FSecureLABS,项目名称:Jandroid,代码行数:25,代码来源:commits.py

示例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 
开发者ID:Qiskit,项目名称:qiskit-aqua,代码行数:26,代码来源:quadratic_program.py

示例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 
开发者ID:imiolek-ireneusz,项目名称:eduActiv8,代码行数:27,代码来源:ratio_hq.py

示例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 
开发者ID:nschloe,项目名称:meshplex,代码行数:21,代码来源:mesh_tetra_test.py

示例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 
开发者ID:ConvLab,项目名称:ConvLab,代码行数:43,代码来源:nlp.py

示例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 
开发者ID:XiaoYee,项目名称:emotion_classification,代码行数:7,代码来源:utils.py

示例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 
开发者ID:nschloe,项目名称:optimesh,代码行数:35,代码来源:helpers.py

示例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 
开发者ID:virtualrealitysystems,项目名称:aumfor,代码行数:11,代码来源:text.py

示例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() 
开发者ID:mwshinn,项目名称:PyDDM,代码行数:14,代码来源:solution.py

示例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) 
开发者ID:mwshinn,项目名称:PyDDM,代码行数:5,代码来源:solution.py

示例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) 
开发者ID:mwshinn,项目名称:PyDDM,代码行数:5,代码来源:solution.py

示例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 
开发者ID:mwshinn,项目名称:PyDDM,代码行数:9,代码来源:solution.py

示例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)) 
开发者ID:mwshinn,项目名称:PyDDM,代码行数:15,代码来源:unit_tests.py


注:本文中的math.fsum方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。