How
Contents
How#
How to create a symbolic numeric value#
To create a symbolic numerical value use sympy.S
.
Tip
sympy.S(a)
For example:
import sympy
value = sympy.S(3)
value
Attention
If we combine a symbolic value with a non symbolic value it will automatically give a symbolic value:
1 / value
How to get the numerical value of a symbolic expression#
We can get the numerical value of a symbolic value using float
or int
:
float
will give the numeric approximation in \(\mathbb{R}\)Tip
float(x)
int
will give the integer valueTip
int(x)
For example, let us 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
If we wanted the integer value:
int(value)
0
Attention
This is not rounding to the nearest integer. It is returning the integer part.
How to factor an expression#
We use the sympy.factor
tool to factor expressions.
Tip
sympy.factor(expression)
For example:
x = sympy.Symbol("x")
sympy.factor(x ** 2 - 9)
How to expand an expression#
We use the sympy.expand
tool to expand expressions.
Tip
sympy.expand(expression)
For example:
sympy.expand((x - 3) * (x + 3))
How to simplify an expression#
We use the sympy.simplify
tool to simplify an expression.
Tip
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
.
How to solve an equation#
We 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 we want to solve for.
Tip
sympy.solveset(equation, variable)
Here is how we can use sympy
to obtain the roots of the general quadratic:
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 we would solve the same equation but not for \(x\) but for \(b\):
sympy.solveset(quadratic, b)
It is however clearer to specifically write the equation that we want to solve:
equation = sympy.Eq(a * x ** 2 + b * x + c, 0)
sympy.solveset(equation, x)
How to substitute a value in to an expression#
Given a sympy
expression it is possible to substitute values in to it using
the .subs()
tool.
Tip
expression.subs({variable: value})
Attention
It is possible to pass multiple variables at a time.
For example we can substitute the values for \(a, b, c\) in to our quadratic:
quadratic = a * x ** 2 + b * x + c
quadratic.subs({a: 1, b: sympy.S(7) / 8, c: 0})