本文整理汇总了Python中sympy.diff方法的典型用法代码示例。如果您正苦于以下问题:Python sympy.diff方法的具体用法?Python sympy.diff怎么用?Python sympy.diff使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sympy
的用法示例。
在下文中一共展示了sympy.diff方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: marginal_product_capital
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import diff [as 别名]
def marginal_product_capital(self):
r"""
Symbolic expression for the marginal product of capital (per
unit effective labor).
:getter: Return the current marginal product of capital (per
unit effective labor).
:type: sym.Basic
Notes
-----
The marginal product of capital is defined as follows:
.. math::
\frac{\partial F(K, AL)}{\partial K} \equiv f'(k)
where :math:`k=K/AL` is capital stock (per unit effective labor)
"""
return sym.diff(self.intensive_output, k)
示例2: testCalculusIntegrate
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import diff [as 别名]
def testCalculusIntegrate(self):
dataset_objects = algorithmic_math.math_dataset_init(
8, digits=5, functions={"log": "L"})
counter = 0
for d in algorithmic_math.calculus_integrate(8, 0, 3, 10):
counter += 1
decoded_input = dataset_objects.int_decoder(d["inputs"])
var, expression = decoded_input.split(":")
target = dataset_objects.int_decoder(d["targets"])
for fn_name, fn_char in six.iteritems(dataset_objects.functions):
target = target.replace(fn_char, fn_name)
# Take the derivative of the target.
derivative = str(sympy.diff(target, var))
# Check that the derivative of the integral equals the input.
self.assertEqual(0, sympy.simplify("%s-(%s)" % (expression, derivative)))
self.assertEqual(counter, 10)
示例3: marginal_product_capital
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import diff [as 别名]
def marginal_product_capital(self):
r"""
Symbolic expression for the marginal product of capital (per unit
effective labor).
:getter: Return the current marginal product of capital.
:type: sympy.Basic
Notes
-----
The marginal product of capital is defined as follows:
.. math::
\frac{\partial F(K, AL)}{\partial K} \equiv f'(k)
where :math:`k=K/AL` is capital stock (per unit effective labor).
"""
return sym.diff(self.intensive_output, k)
示例4: newton_raphson
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import diff [as 别名]
def newton_raphson(func: str, a: int, precision: int = 10 ** -10) -> float:
""" Finds root from the point 'a' onwards by Newton-Raphson method
>>> newton_raphson("sin(x)", 2)
3.1415926536808043
>>> newton_raphson("x**2 - 5*x +2", 0.4)
0.4384471871911695
>>> newton_raphson("x**2 - 5", 0.1)
2.23606797749979
>>> newton_raphson("log(x)- 1", 2)
2.718281828458938
"""
x = a
while True:
x = Decimal(x) - (Decimal(eval(func)) / Decimal(eval(str(diff(func)))))
# This number dictates the accuracy of the answer
if abs(eval(func)) < precision:
return float(x)
# Let's Execute
示例5: Simple_manifold_with_scalar_function_derivative
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import diff [as 别名]
def Simple_manifold_with_scalar_function_derivative():
coords = (x,y,z) = symbols('x y z')
basis = (e1, e2, e3, grad) = MV.setup('e_1 e_2 e_3',metric='[1,1,1]',coords=coords)
# Define surface
mfvar = (u,v) = symbols('u v')
X = u*e1+v*e2+(u**2+v**2)*e3
print X
MF = Manifold(X,mfvar)
# Define field on the surface.
g = (v+1)*log(u)
# Method 1: Using old Manifold routines.
VectorDerivative = (MF.rbasis[0]/MF.E_sq)*diff(g,u) + (MF.rbasis[1]/MF.E_sq)*diff(g,v)
print 'Vector derivative =', VectorDerivative.subs({u:1,v:0})
# Method 2: Using new Manifold routines.
dg = MF.Grad(g)
print 'Vector derivative =', dg.subs({u:1,v:0})
return
示例6: Simple_manifold_with_scalar_function_derivative
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import diff [as 别名]
def Simple_manifold_with_scalar_function_derivative():
Print_Function()
coords = (x,y,z) = symbols('x y z')
basis = (e1, e2, e3, grad) = MV.setup('e_1 e_2 e_3',metric='[1,1,1]',coords=coords)
# Define surface
mfvar = (u,v) = symbols('u v')
X = u*e1+v*e2+(u**2+v**2)*e3
print '\\f{X}{u,v} =',X
MF = Manifold(X,mfvar)
(eu,ev) = MF.Basis()
# Define field on the surface.
g = (v+1)*log(u)
print '\\f{g}{u,v} =',g
# Method 1: Using old Manifold routines.
VectorDerivative = (MF.rbasis[0]/MF.E_sq)*diff(g,u) + (MF.rbasis[1]/MF.E_sq)*diff(g,v)
print '\\eval{\\nabla g}{u=1,v=0} =', VectorDerivative.subs({u:1,v:0})
# Method 2: Using new Manifold routines.
dg = MF.Grad(g)
print '\\eval{\\f{Grad}{g}}{u=1,v=0} =', dg.subs({u:1,v:0})
dg = MF.grad*g
print '\\eval{\\nabla g}{u=1,v=0} =', dg.subs({u:1,v:0})
return
示例7: _is_non_decreasing
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import diff [as 别名]
def _is_non_decreasing(fn, q, bounds):
"""Verifies whether the function is non-decreasing within a range.
Args:
fn: Symbolic function of a single variable.
q: The name of f's variable.
bounds: Pair of (lower_bound, upper_bound) reals.
Returns:
True iff the function is non-decreasing in the range.
"""
diff_fn = sp.diff(fn, q) # Symbolically compute the derivative.
diff_fn_lambdified = sp.lambdify(
q,
diff_fn,
modules=[
"numpy", {
"erfc": scipy.special.erfc,
"erfcinv": scipy.special.erfcinv
}
])
r = scipy.optimize.minimize_scalar(
diff_fn_lambdified, bounds=bounds, method="bounded")
assert r.success, "Minimizer failed to converge."
return r.fun >= 0 # Check whether the derivative is non-negative.
示例8: _computeTransitionJacobian
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import diff [as 别名]
def _computeTransitionJacobian(self):
if self._GMat is None:
self._computeDependencyMatrix()
F = sympy.zeros(self.num_transitions, self.num_transitions)
for i in range(self.num_transitions):
for j, eqn in enumerate(self._transitionVector):
for k, state in enumerate(self._iterStateList()):
diffEqn = sympy.diff(eqn, state, 1)
tempEqn, isDifficult = simplifyEquation(diffEqn)
F[i,j] += tempEqn*self._vMat[k,i]
self._isDifficult = self._isDifficult or isDifficult
self._transitionJacobian = F
self._hasNewTransition.reset('transitionJacobian')
return F
示例9: _integrate_exact
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import diff [as 别名]
def _integrate_exact(f, c2):
xi = sympy.DeferredVector("xi")
pxi = (
c2[0] * 0.25 * (1.0 + xi[0]) * (1.0 + xi[1])
+ c2[1] * 0.25 * (1.0 - xi[0]) * (1.0 + xi[1])
+ c2[2] * 0.25 * (1.0 - xi[0]) * (1.0 - xi[1])
+ c2[3] * 0.25 * (1.0 + xi[0]) * (1.0 - xi[1])
)
pxi = [sympy.expand(pxi[0]), sympy.expand(pxi[1])]
# determinant of the transformation matrix
det_J = +sympy.diff(pxi[0], xi[0]) * sympy.diff(pxi[1], xi[1]) - sympy.diff(
pxi[1], xi[0]
) * sympy.diff(pxi[0], xi[1])
# we cannot use abs(), see <https://github.com/sympy/sympy/issues/4212>.
abs_det_J = sympy.Piecewise((det_J, det_J >= 0), (-det_J, det_J < 0))
g_xi = f(pxi)
exact = sympy.integrate(
sympy.integrate(abs_det_J * g_xi, (xi[1], -1, 1)), (xi[0], -1, 1)
)
return float(exact)
示例10: test_stencil_derivative
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import diff [as 别名]
def test_stencil_derivative(self, SymbolType, dim):
"""Test symbolic behaviour when expanding stencil derivatives"""
i = dim(self.grid)
u = SymbolType(name='u', grid=self.grid)
u.data[:] = 66.6
di = u.diff(i)
dii = u.diff(i, i)
# Check for sympy Derivative objects
assert(isinstance(di, Derivative) and isinstance(dii, Derivative))
s_di = di.as_finite_difference([i - i.spacing, i])
s_dii = dii.as_finite_difference([i - i.spacing, i, i + i.spacing])
# Check stencil length of first and second derivatives
assert(len(s_di.args) == 2 and len(s_dii.args) == 3)
u_di = s_di.args[0].args[1]
u_dii = s_di.args[0].args[1]
# Ensure that devito meta-data survived symbolic transformation
assert(u_di.grid.shape == self.shape and u_dii.grid.shape == self.shape)
assert(u_di.shape == u.shape and u_dii.shape == u.shape)
assert(np.allclose(u_di.data, 66.6))
assert(np.allclose(u_dii.data, 66.6))
示例11: _njacobian
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import diff [as 别名]
def _njacobian(self):
"""
:return: The `numerical_jacobian` of the components of the ODEModel with
regards to the dependent variables. This is not to be confused with
the jacobian of the model as a whole, which is 2D and computed with
regards to the dependent vars and the fit parameters, and the
ODEModel still needs to integrated to compute that.
Instead, this function is used by the ODE integrator, and is not
meant for human consumption.
"""
return [
[sympy_to_py(
sympy.diff(expr, var), self.independent_vars + self.dependent_vars + self.model_params
) for var in self.dependent_vars
] for _, expr in self.items()
]
示例12: spherical_bessel_formulas
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import diff [as 别名]
def spherical_bessel_formulas(n):
x = sym.symbols('x')
f = [sym.sin(x) / x]
a = sym.sin(x) / x
for i in range(1, n):
b = sym.diff(a, x) / x
f += [sym.simplify(b * (-x)**i)]
a = sym.simplify(b)
return f
示例13: uniform_bspline_basis
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import diff [as 别名]
def uniform_bspline_basis(d, p=0):
"""Generate a "Numpy friendly" function to facilitate fast evaluation of
uniform B-spline basis functions.
Parameters
----------
d : int
The degree of the uniform B-spline.
p : optional, int
The order of the derivative with respect to the interpolation
parameter.
Returns
-------
uniform_bspline_basis_d : function
"Numpy friendly" function to evaluate the uniform B-spline
interpolation components.
"""
t = sp.Symbol('t')
b = basis_functions(d, t)
for i in range(p):
b = [sp.diff(e, t) for e in b]
func_name = 'uniform_bspline_basis_{}_{}'.format(d, p)
W = [' W[:, {}] = {}'.format(ie[0], ie[1].evalf())
for ie in enumerate(b)]
code = UNIFORM_BSPLINE_TEMPLATE.format(func_name=func_name,
num_control_points=len(W),
W='\n'.join(W))
globals_ = {'np' : np}
exec(code, globals_)
return globals_[func_name]
# UniformBSpline
示例14: __init__
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import diff [as 别名]
def __init__(self, **traits):
TaylorPoly.__init__(self, **traits)
#Declare the analytical function
Z=sympy.Function("Z")
Ax,Ay,Kx,Ky=sympy.symbols(("Ax","Ay","Kx","Ky"))
x, y =sympy.symbols('xy')
Z=(Ax*x**2+Ay*y**2)/(1+sympy.sqrt(1-(1+Kx)*Ax**2*x**2-(1+Ky)*Ay**2*y**2));
#Calculate taylor polynomial coheficients
cohef=[[Z, ],]
order=self.n
for i in range(0, order+1, 2):
if i!=0:
cohef.append([sympy.diff(cohef[i/2-1][0], y, 2), ])
for j in range(2, order-i+1, 2):
cohef[i/2].append(sympy.diff(cohef[i/2][j/2 -1], x, 2))
A_x=self.Ax
A_y=self.Ay
K_x=self.Kx
K_y=self.Ky
c=zeros((self.n+1, self.n+1))
for i in range(0, order/2+1):
for j in range(0,order/2- i+1):
cohef[j][i]=cohef[j][i].subs(x, 0).subs(y, 0).subs(Ax, A_x).subs(Ay, A_y).subs(Kx, K_x).subs(Ky, K_y)/(sympy.factorial(2*i)*sympy.factorial(2*j))
c[2*j, 2*i]=cohef[j][i].evalf()
# Add the high order corrections
if len(self.ho_cohef.shape)==2:
cx, cy = c.shape
dx, dy =self.ho_cohef.shape
mx=array((cx, dx)).max()
my=array((cy, dy)).max()
self.cohef=zeros((mx, my))
self.cohef[0:cx, 0:cy]=c
self.cohef[0:dy, 0:dy]=self.cohef[0:dy, 0:dy]+self.ho_cohef
else:
self.cohef=c
示例15: grad
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import diff [as 别名]
def grad(f, basis, for_numerical=True):
"""
Compute the symbolic gradient of a vector-valued function with respect to a
basis.
Parameters
----------
f : 1D array_like of sympy Expressions
The vector-valued function to compute the gradient of.
basis : 1D array_like of sympy symbols
The basis symbols to compute the gradient with respect to.
for_numerical : bool, optional
A placeholder for the option of numerically computing the gradient.
Returns
-------
grad : 2D array_like of sympy Expressions
The symbolic gradient.
"""
if hasattr(f, '__len__'): # as of version 1.1.1, Array isn't supported
f = sp.Matrix(f)
return f.__class__([
[
sp.diff(f[x], basis[y])
if not for_numerical or not f[x].has(sp.sign(basis[y])) else 0
for y in range(len(basis))
] for x in range(len(f))
])