本文整理汇总了Python中sympy.nsimplify函数的典型用法代码示例。如果您正苦于以下问题:Python nsimplify函数的具体用法?Python nsimplify怎么用?Python nsimplify使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了nsimplify函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: symbolic_hamiltonian
def symbolic_hamiltonian(self):
variable_phase_symbols = []
variable_charge_symbols = []
for variable_id, variable in enumerate(self.variables):
variable.phase_symbol = sympy.Symbol(variable.name)
if variable.variable_type=='variable':
variable.charge_symbol = sympy.Symbol('n'+variable.name)
else:
variable.charge_symbol = sympy.Symbol('U'+variable.name)
variable_phase_symbols.append(variable.phase_symbol)
variable_charge_symbols.append(variable.charge_symbol)
variable_phase_symbols = sympy.Matrix(variable_phase_symbols)
variable_charge_symbols = sympy.Matrix(variable_charge_symbols)
node_phase_symbols = self.linear_coordinate_transform*variable_phase_symbols
for node_id, node in enumerate(self.nodes):
node.phase_symbol = node_phase_symbols[node_id]
kinetic_energy = 0.5*sympy.nsimplify((variable_charge_symbols.T * self.capacitance_matrix_legendre_transform(symbolic=True) * variable_charge_symbols)[0,0])
potential_energy = 0
for element in self.elements:
if element.is_phase():
element_node_phases = []
element_node_voltages = []
for wire in self.wires:
if wire[0]==element.name:
for node_id, node in enumerate(self.nodes):
if wire[1]==node.name:
element_node_phases.append(sympy.nsimplify(node.phase_symbol))
potential_energy += element.symbolic_energy_term(element_node_phases, 0)
return kinetic_energy + potential_energy
示例2: formula_to_string
def formula_to_string(formula):
"""
Parameters
----------
formula : dictionary or counter
Chemical formula
Returns
-------
formula_string : string
A formula string, with element order based loosely
on electronegativity, following the scheme suggested by IUPAC,
except that H comes after the Group 16 elements, not before them.
If one or more keys in the dictionary are not one of the elements
in the periodic table, then they are added at the end of the string.
"""
IUPAC_element_order=['v', 'Og', 'Rn', 'Xe', 'Kr', 'Ar', 'Ne', 'He', # Group 18
'Fr', 'Cs', 'Rb', 'K', 'Na', 'Li', # Group 1 (omitting H)
'Ra', 'Ba', 'Sr', 'Ca', 'Mg', 'Be', # Group 2
'Lr', 'No', 'Md', 'Fm', 'Es', 'Cf', 'Bk', 'Cm',
'Am', 'Pu', 'Np', 'U', 'Pa', 'Th', 'Ac', # Actinides
'Lu', 'Yb', 'Tm', 'Er', 'Ho', 'Dy', 'Tb', 'Gd',
'Eu', 'Sm', 'Pm', 'Nd', 'Pr', 'Ce', 'La', # Lanthanides
'Y', 'Sc', # Group 3
'Rf', 'Hf', 'Zr', 'Ti', # Group 4
'Db', 'Ta', 'Nb', 'V', # Group 5
'Sg', 'W', 'Mo', 'Cr', # Group 6
'Bh', 'Re', 'Tc', 'Mn', # Group 7
'Hs', 'Os', 'Ru', 'Fe', # Group 8
'Mt', 'Ir', 'Rh', 'Co', # Group 9
'Ds', 'Pt', 'Pd', 'Ni', # Group 10
'Rg', 'Au', 'Ag', 'Cu', # Group 11
'Cn', 'Hg', 'Cd', 'Zn', # Group 12
'Nh', 'Tl', 'In', 'Ga', 'Al', 'B', # Group 13
'Fl', 'Pb', 'Sn', 'Ge', 'Si', 'C', # Group 14
'Mc', 'Bi', 'Sb', 'As', 'P', 'N', # Group 15
'Lv', 'Po', 'Te', 'Se', 'S', 'O', # Group 16
'H', # hydrogen
'Ts', 'At', 'I', 'Br', 'Cl', 'F']# Group 17
formula_string = ''
for e in IUPAC_element_order:
if e in formula and np.abs(formula[e])>1.e-12:
if np.abs(formula[e] - 1.) < 1.e-12:
formula_string += e
else:
formula_string += e + str(nsimplify(formula[e]))
for e in formula:
if e not in IUPAC_element_order:
if e in formula and np.abs(formula[e])>1.e-12:
if np.abs(formula[e] - 1.) < 1.e-12:
formula_string += e
else:
formula_string += e + str(nsimplify(formula[e]))
return formula_string
示例3: random_complex_number
def random_complex_number(a=2, b=-1, c=3, d=1, rational=False):
"""
Return a random complex number.
To reduce chance of hitting branch cuts or anything, we guarantee
b <= Im z <= d, a <= Re z <= c
"""
A, B = uniform(a, c), uniform(b, d)
if not rational:
return A + I * B
return nsimplify(A, rational=True) + I * nsimplify(B, rational=True)
示例4: nsimplify_matrix
def nsimplify_matrix(A_expr,constants=[],tolerance=None,full=False,rational=False):
A_nsimplified_expr = sympy.Matrix.zeros(A_expr.rows,A_expr.cols)
for r in range(A_expr.rows):
for c in range(A_expr.cols):
A_nsimplified_expr[r,c] = sympy.nsimplify(A_expr[r,c],constants,tolerance,full,rational)
return A_nsimplified_expr
示例5: test_issue_2877
def test_issue_2877():
f = Float(2.0)
assert (x + f).subs({f: 2}) == x + 2
def r(a,b,c):
return factor(a*x**2 + b*x + c)
e = r(5/6, 10, 5)
assert nsimplify(e) == 5*x**2/6 + 10*x + 5
示例6: simplify_matrix
def simplify_matrix(matrix):
"""
Replaces floats with ints and puts elements with fractions
on a single demoninator.
"""
m = matrix[:, :]
for i, e in enumerate(m):
m[i] = nsimplify(e, rational=True).cancel()
return m
示例7: mark
def mark(self):
"""Splits up input into point location and MinMax Value"""
gradient = 0
attempt = self.parser.parse()
attemptPoints = attempt[0]
attemptMinMax = attempt[1]
function = equationMaker(self.qvariables)
diff = sympy.diff(function, x)
# Sympy can only solve for 0, so must take gradient from function
diff -= gradient
results = sympy.solve(diff, x)
# Simplify results and answer to avoid issue with fractions
for i in range(len(results)):
results[i] = sympy.nsimplify(results[i])
for i in range(len(attemptPoints)):
attemptPoints[i] = sympy.nsimplify(attemptPoints[i])
"""Differentiates a second time, works out if the point is positive, negative
or 0 and then sets the list accordingly. Minimum point is -1, Max is 1."""
diff2 = sympy.diff(diff, x)
minOrMax = []
for i in range(len(results)):
j = diff2.subs(x, results[i])
if j > 0:
minOrMax.append(-1)
elif j < 0:
minOrMax.append(1)
else:
minOrMax.append(0)
"""Redundant code for if we split marks up, if so it gives value for each part
correctly answered:
half = 1 if (set(minOrMax) == set(attemptMinMax)) else 0
half += 1 if (set(attemptPoints) == set(results)) else 0
"""
return True if (set(minOrMax) == set(attemptMinMax)) and (set(attemptPoints) == set(results)) else False
示例8: _decimal
def _decimal(self, nbr, prec=None, fractions=None):
if prec is None:
prec = self.precision_calcul
if fractions is None:
fractions = self.convertir_decimaux_en_fractions
if fractions:
# On indique qu'il faudra reconvertir les résultats en décimaux.
self.reconvertir_en_decimaux = True
return nsimplify(nbr, rational=True)
return Float(nbr, prec)
示例9: capacitance_matrix_variables
def capacitance_matrix_variables(self, symbolic=False):
"""
Calculates the capacitance matrix for the energy term of the qubit Lagrangian in the variable respresentation.
"""
if symbolic:
C = self.linear_coordinate_transform.T*self.capacitance_matrix(symbolic)*self.linear_coordinate_transform
C = sympy.Matrix([sympy.nsimplify(sympy.ratsimp(x)) for x in C]).reshape(*(C.shape))
else:
C = np.einsum('ji,jk,kl->il', self.linear_coordinate_transform,self.capacitance_matrix(symbolic),self.linear_coordinate_transform)
return C
示例10: isEquivalentExpressions
def isEquivalentExpressions(response, rubric, allowChangeOfVariable = False, allowSimplify = True, trigIdentities = False, logIdentities = False, forceAssumptions = False):
if not allowChangeOfVariable:
if isinstance(response, bool):
return (type(response) == type(rubric) and response == rubric)
elif trigIdentities:
return simplify(expand(nsimplify(response - rubric, rational=True), trig=True)) == 0
elif logIdentities and forceAssumptions:
return simplify(expand(nsimplify(response - rubric, rational=True), log=True, force=True)) == 0
elif logIdentities:
return simplify(expand(nsimplify(response - rubric, rational=True), log=True)) == 0
elif allowSimplify:
return simplify(nsimplify(response - rubric, rational=True)) == 0
else:
return response == rubric
if len(response.free_symbols) == 0:
return isEquivalent(response, rubric)
if len(response.free_symbols) > 1:
raise Exception("Don't know how to test change of variable equivalence of 2 expressions if they have more than 1 variable. Yet")
if len(response.free_symbols) != len(rubric.free_symbols):
return False
return isEquivalent(response.subs(response.free_symbols.pop(),rubric.free_symbols.pop()), rubric)
示例11: as_expr
def as_expr(self):
expr = 0
for i in range(len(self.coefs)):
fact = 1
for j in range(len(self.vars)):
fact = fact*self.vars[j]**self.exps[i][j]
if self.rs is None:
expr += self.coefs[i]*fact
else:
coef = 0
for j in range(len(self.rs)):
coef += self.rs[j]*self.coefs[i][j]
expr += coef*fact
return spy.nsimplify(expr)
示例12: test_action_verbs
def test_action_verbs():
assert nsimplify((1/(exp(3*pi*x/5)+1))) == (1/(exp(3*pi*x/5)+1)).nsimplify()
assert ratsimp(1/x + 1/y) == (1/x + 1/y).ratsimp()
assert trigsimp(log(x), deep=True) == (log(x)).trigsimp(deep = True)
assert radsimp(1/(2+sqrt(2))) == (1/(2+sqrt(2))).radsimp()
assert powsimp(x**y*x**z*y**z, combine='all') == (x**y*x**z*y**z).powsimp(combine='all')
assert simplify(x**y*x**z*y**z) == (x**y*x**z*y**z).simplify()
assert together(1/x + 1/y) == (1/x + 1/y).together()
assert separate((x*(y*z)**3)**2) == ((x*(y*z)**3)**2).separate()
assert collect(a*x**2 + b*x**2 + a*x - b*x + c, x) == (a*x**2 + b*x**2 + a*x - b*x + c).collect(x)
assert apart(y/(y+2)/(y+1), y) == (y/(y+2)/(y+1)).apart(y)
assert combsimp(y/(x+2)/(x+1)) == (y/(x+2)/(x+1)).combsimp()
assert factor(x**2+5*x+6) == (x**2+5*x+6).factor()
assert refine(sqrt(x**2)) == sqrt(x**2).refine()
assert cancel((x**2+5*x+6)/(x+2)) == ((x**2+5*x+6)/(x+2)).cancel()
示例13: printTransformations
def printTransformations(infisAll, allVariables):
n = len(infisAll[0])
length1 = 8
length2 = 13
length3 = 14
transformations = [0]*len(infisAll)
types = [0]*len(infisAll)
outputs = []
for l in range(len(infisAll)):
for i in range(n):
infisAll[l][i] = spy.nsimplify(infisAll[l][i])
transformations[l], types[l] = buildTransformation(infisAll[l], allVariables)
outputs.append([])
for i in range(n):
if infisAll[l][i] != 0:
# get stuff for output line
outputs[-1].append(\
[str(allVariables[i]), str(infisAll[l][i]), str(transformations[l][i])])
# remove string extension
for v in ['Q', 'C', 'O', 'S', 'I', 'N', 'E']:
outputs[-1][-1][0] = outputs[-1][-1][0].replace(v + extension_str, v)
outputs[-1][-1][1] = outputs[-1][-1][1].replace(v + extension_str, v)
outputs[-1][-1][2] = outputs[-1][-1][2].replace(v + extension_str, v)
# search for longest string
if len(outputs[-1][-1][0]) > length1:
length1 = len(outputs[-1][-1][0])
if len(outputs[-1][-1][1]) > length2:
length2 = len(outputs[-1][-1][1])
if len(outputs[-1][-1][2]) > length3:
length3 = len(outputs[-1][-1][2])
# print all stuff
print ('{0:'+str(length1)+'s} : ').format('variable') \
+ ('{0:'+str(length2)+'s} : ').format('infinitesimal')\
+ str('transformation')
for l in range(len(infisAll)):
print '-'*(length1+length2+length3+6)
print '#' + str(l+1) + ': ' + types[l]
for lst in outputs[l]:
print ('{0:'+str(length1)+'s} : ').format(lst[0]) \
+ ('{0:'+str(length2)+'s} : ').format(str(lst[1]))\
+ str(lst[2])
示例14: emit
def emit(name, iname, cdf, args, no_small=False):
V = []
for arg in sorted(args):
y = cdf(*arg)
if isinstance(y, mpf):
e = sp.nsimplify(y, rational=True)
if e.is_Rational and e.q <= 1000 and mp.almosteq(e, y, 1e-25):
y = e
else:
y = N(y)
V.append(arg + (y,))
for v in V:
if name:
test(name, *v)
for v in V:
if iname and (not no_small or 1/1000 <= v[-1] <= 999/1000):
test(iname, *(v[:-2] + v[:-3:-1]))
示例15: test_power
def test_power():
"""
Take units to some power.
"""
from sympy import nsimplify
pc_cgs = cm_per_pc
mK_cgs = 1e-3
u1_dims = mass * length**2 * time**-3 * temperature**4
u1 = Unit("g * pc**2 * s**-3 * mK**4")
u2 = u1**2
yield assert_true, u2.dimensions == u1_dims**2
yield assert_allclose_units, u2.base_value, (pc_cgs**2 * mK_cgs**4)**2, 1e-12
u3 = u1**(-1.0/3)
yield assert_true, u3.dimensions == nsimplify(u1_dims**(-1.0/3))
yield assert_allclose_units, u3.base_value, (pc_cgs**2 * mK_cgs**4)**(-1.0/3), 1e-12