def test_toy_geometric():
filename = download_mesh(
'toy.msh',
'1d125d3fa9f373823edd91ebae5f7a81'
)
mesh, _, _, _ = voropy.read(filename)
mesh = voropy.mesh_tetra.MeshTetra(
mesh.node_coords,
mesh.cells['nodes'],
mode='geometric'
)
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.get_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
return
python类fsum()的实例源码
def calc_arr_norm( v ):
mag = sqrt( fsum( [ c**2 for c in v ]) )
return tuple( [ ( c/mag) for c in v ] )
################################################################################
## DEFINE THE FUNCTION FOR COMPUTING DOT PRODUCT
################################################################################
# Define the function for computing dot product
def calc_arr_dot( u,v ) :
if ( len(u) != len(v) ) :
raise TypeError( 'Unequal lengths.' )
return fsum([ x[0]*x[1] for x in zip(u,v) ])
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
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
def fit(self, data):
self.data = data
self.real_indices = range(len(data))
for i in range(len(data)):
self.dic[ (i, i) ] = 0.
for j in range(i):
self.dic[ (i, j) ] = math.sqrt( math.fsum( ( (a-b)**2 for a, b in zip(self.data[i], self.data[j])) ) )
self.dic[ (j, i) ] = self.dic[ (i, j) ]
def mean_neg_log_likelihood(self):
return math.fsum([self.neg_sum_batch_log_likelihood(i) for i in xrange(self.num_batches)]) / self.num_samples # np.sum() has some precision problems here
def mean_unnormalized_neg_log_likelihood(self):
return math.fsum([self.unnormalized_neg_sum_batch_log_likelihood(i) for i in xrange(self.num_batches)]) / self.num_samples # np.sum() has some precision problems here
def eval_symb_reg(individual, points, values):
try:
func = toolbox.compile(expr=individual)
sqerrors = [(func(*z) - valx)**2 for z, valx in zip(points, values)]
return math.log10(math.sqrt(math.fsum(sqerrors)) / len(points)),
except OverflowError:
return 1000.0,
# register the selection and genetic operators - tournament selection and, one point crossover and sub-tree mutation
def lf_needed_fuel(dv, I_sp, m_p, f_e):
m_c = m_p/f_e * ((1/f_e) / (1+(1/f_e)-exp(1/g_0*fsum([dv[i]/I_sp[i] for i in range(len(dv))]))) - 1)
if m_c < 0:
return None
return m_c
def _get_duration(self):
duration = self._metadata.get('duration', None)
if duration is not None:
return duration
raw_values = self._get_raw_values(warmups=True)
return math.fsum(raw_values)
def get_total_duration(self):
durations = [run._get_duration() for run in self._runs]
return math.fsum(durations)
def _get_run_property(self, get_property):
# ignore calibration runs
values = [get_property(run) for run in self._runs
if not run._is_calibration()]
if len(set(values)) == 1:
return values[0]
# Compute the mean (float)
return math.fsum(values) / len(values)
def get_total_duration(self):
durations = [benchmark.get_total_duration() for benchmark in self]
return math.fsum(durations)
def test_compare_with_math_fsum(self):
# Compare with the math.fsum function.
# Ideally we ought to get the exact same result, but sometimes
# we differ by a very slight amount :-(
data = [random.uniform(-100, 1000) for _ in range(1000)]
self.assertApproxEqual(float(self.func(data)[1]), math.fsum(data), rel=2e-16)
symbol_regression.py 文件源码
项目:Artificial-Intelligence-with-Python
作者: PacktPublishing
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
def eval_func(individual, points):
# Transform the tree expression in a callable function
func = toolbox.compile(expr=individual)
# Evaluate the mean squared error
mse = ((func(x) - (2 * x**3 - 3 * x**2 + 4 * x - 1))**2 for x in points)
return math.fsum(mse) / len(points),
# Function to create the toolbox
line_follower_module.py 文件源码
项目:SunFounder_PiSmart_Car
作者: sunfounder
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def get_average(self, mount):
if not isinstance(mount, int):
raise ValueError("Mount must be interger")
average = [0, 0, 0, 0, 0]
lt_list = [[], [], [], [], []]
for times in range(0, mount):
lt = self.read_analog()
for lt_id in range(0, 5):
lt_list[lt_id].append(lt[lt_id])
for lt_id in range(0, 5):
average[lt_id] = int(math.fsum(lt_list[lt_id])/mount)
return average
def test_compare_with_math_fsum(self):
# Compare with the math.fsum function.
# Ideally we ought to get the exact same result, but sometimes
# we differ by a very slight amount :-(
data = [random.uniform(-100, 1000) for _ in range(1000)]
self.assertApproxEqual(self.func(data), math.fsum(data), rel=2e-16)
def max_flow(edges, source, sink):
"""Returns the maximum flow that can be routed from source to sink.
Uses the push-relabel algorithm (also known as pre-flow push) to push
flow to nodes, then divert any excess flow at the nodes to 'downhill'
(lower labeled) nodes until the flow reaches sink.
Args:
edges: A list of directed edge tuples of the form
(start, end, capacity), where start and end both represent nodes,
and capacity represents the maximum capacity that can pass through
this edge at once.
start and end may be strings or numbers, and capacity must be a
number.
source, sink: Node names identifying the start (source) and end (sink)
nodes of the paths. May be numbers or strings.
If both names are not included in edges, the maximum flow will be 0.
Returns:
A floating point number indicating the maximum flow that can be routed
from source to sink through edges.
"""
flow, labels, outgoing_edges, incoming_edges = _initialize(edges, source)
# Start with the nodes that are adjacent to source, since they can get flow
excess_nodes = [edge[1] for edge in outgoing_edges[source]]
while len(excess_nodes) > 0:
current = excess_nodes.pop()
pushed = _push(
outgoing_edges[current], incoming_edges[current], labels, flow)
if not (pushed or _relabel(outgoing_edges[current], labels)):
# Try next node if nothing could be pushed or relabeled
continue
# Only check nodes with outgoing edges
excess_nodes = [node for node in outgoing_edges if _excess(
flow, outgoing_edges[node], incoming_edges[node]) > 0]
# Use fsum for precision in case capacities are floats
return math.fsum(flow[x] for x in incoming_edges[sink])
def test_clenshaw(tol=1.0e-14):
n = 5
_, _, alpha, beta = \
orthopy.line.recurrence_coefficients.legendre(n, 'monic')
t = 1.0
a = numpy.ones(n+1)
value = orthopy.line.clenshaw(a, alpha, beta, t)
ref = math.fsum([
numpy.polyval(legendre(i, monic=True), t)
for i in range(n+1)])
assert abs(value - ref) < tol
return