DIFF
This function computes symbolic derivatives with respect to a chosen variable and derivative order.
For a function f(x), the first derivative is:
\frac{d}{dx}f(x)
and the n-th derivative is:
\frac{d^n}{dx^n}f(x)
The result is returned as a symbolic expression string.
Excel Usage
=DIFF(expression, variable, order)
expression(str, required): Expression to differentiate.variable(str, optional, default: “x”): Variable name for differentiation.order(int, optional, default: 1): Positive integer derivative order.
Returns (str): String representation of the symbolic derivative.
Example 1: First derivative of a polynomial
Inputs:
| expression | variable | order |
|---|---|---|
| x**3 + 2*x | x | 1 |
Excel formula:
=DIFF("x**3 + 2*x", "x", 1)
Expected output:
"3*x**2 + 2"
Example 2: Second derivative of a polynomial
Inputs:
| expression | variable | order |
|---|---|---|
| x4 + x2 | x | 2 |
Excel formula:
=DIFF("x**4 + x**2", "x", 2)
Expected output:
"2*(6*x**2 + 1)"
Example 3: Derivative of a trigonometric expression
Inputs:
| expression | variable | order |
|---|---|---|
| sin(x) | x | 1 |
Excel formula:
=DIFF("sin(x)", "x", 1)
Expected output:
"cos(x)"
Example 4: Derivative using custom variable
Inputs:
| expression | variable | order |
|---|---|---|
| t**5 | t | 3 |
Excel formula:
=DIFF("t**5", "t", 3)
Expected output:
"60*t**2"
Python Code
from sympy import Symbol
from sympy import sympify
from sympy import diff as sympy_diff
def diff(expression, variable='x', order=1):
"""
Compute a symbolic derivative of an expression.
See: https://docs.sympy.org/latest/modules/core.html#sympy.core.function.diff
This example function is provided as-is without any representation of accuracy.
Args:
expression (str): Expression to differentiate.
variable (str, optional): Variable name for differentiation. Default is 'x'.
order (int, optional): Positive integer derivative order. Default is 1.
Returns:
str: String representation of the symbolic derivative.
"""
try:
derivative_order = int(order)
if derivative_order < 1:
return "Error: order must be a positive integer"
variable_symbol = Symbol(variable)
normalized_expression = expression.replace("^", "**")
expr = sympify(normalized_expression)
result = sympy_diff(expr, variable_symbol, derivative_order)
return str(result)
except Exception as e:
return f"Error: {str(e)}"Online Calculator
Expression to differentiate.
Variable name for differentiation.
Positive integer derivative order.