How to
Contents
How to#
Create a symbolic numeric value#
To create a symbolic numerical value use sympy.S.
Usage
sympy.S(a)
For example:
import sympy
value = sympy.S(3)
value
Attention
If you combine a symbolic value with a non symbolic value it will automatically give a symbolic value:
1 / value
Get the numerical value of a symbolic expression#
You can get the numerical value of a symbolic value using float or
int:
floatwill give the numeric approximation in \(\mathbb{R}\)Usage
float(x)
intwill give the integer valueUsage
int(x)
For example, to create a symbolic numeric variable with value \(\frac{1}{5}\):
value = 1 / sympy.S(5)
value
To get the numerical value:
float(value)
0.2
To get the integer value:
int(value)
0
Attention
This is not rounding to the nearest integer. It is returning the integer part.
Factor an expression#
Use the sympy.factor tool to factor expressions.
Usage
sympy.factor(expression)
For example:
x = sympy.Symbol("x")
sympy.factor(x ** 2 - 9)
Factor an expression#
Use the sympy.factor tool to factor expressions.
Usage
sympy.expand(expression)
For example:
sympy.expand((x - 3) * (x + 3))
Simplify an expression#
Use the sympy.simplify tool to simplify an expression.
Usage
sympy.simplify(expression)
For example:
sympy.simplify((x - 3) * (x + 3))
Attention
This will not always give the expected (or any) result. At times it could be
more beneficial to use sympy.expand and/or sympy.factor.
Solve an equation#
Use the sympy.solveset tool to solve an equation. It takes two values
as inputs. The first is either:
An expression for which a root is to be found
An equation
The second is the variable you want to solve for.
Usage
sympy.solveset(equation, variable)
Here is how you can use sympy to obtain the roots of the general :
a = sympy.Symbol("a")
b = sympy.Symbol("b")
c = sympy.Symbol("c")
quadratic = a * x ** 2 + b * x + c
sympy.solveset(quadratic, x)
Here is how to solve the same equation but not for \(x\) but for \(b\):
sympy.solveset(quadratic, b)
It is however clearer to specifically write the equation to solve:
equation = sympy.Eq(a * x ** 2 + b * x + c, 0)
sympy.solveset(equation, x)
Substitute a value in to an expression#
Given a sympy expression it is possible to substitute values in to it
using the .subs() tool.
Usage
expression.subs({variable: value})
Attention
It is possible to pass multiple variables at a time. For example to substitute the values for \(a, b, c\) in to the expression: