- •Credits
- •About the Author
- •About the Reviewers
- •www.PacktPub.com
- •Preface
- •Getting started
- •More advanced graphics
- •Summary
- •Start Sage
- •Installing Sage
- •Starting Sage
- •Prerequisites
- •Installation
- •Summary
- •Command history
- •Working with code
- •Arithmetic operators
- •Strings
- •Functions
- •Functions with keyword arguments
- •Objects
- •Summary
- •Python 2 and Python 3
- •Running scripts
- •Strings
- •List comprehensions
- •Storing data in a dictionary
- •Summary
- •Vectors and vector spaces
- •Creating a vector space
- •Vector operators and methods
- •Decomposing matrices
- •Summary
- •Using graphics primitives
- •Summary
- •Substitutions
- •Finding roots
- •Derivatives
- •Integrals
- •Series and summations
- •Summary
- •Computing gradients
- •Constrained optimization
- •Probability
- •Summary
- •Making our tanks move
- •Unit testing
- •Summary
- •Introducing Python decorators
- •Making interactive graphics
- •Summary
- •Index
Making Symbolic Mathematics Easy
What just happened?
We defined a rational function, and demonstrated the utility methods numerator and denominator to obtain different parts of the expression. The method expand_rational separates the expression into a sum of terms by multiplying out products of sums and exponentials, splitting the numerator into terms, and distributing multiplication over addition. The method partial_fraction returns the partial fraction expansion of the expression. This is an extremely tedious calculation to perform by hand, and it is often the most time-consuming step in solving a differential equation with the Laplace transform.
Substitutions
When working with symbolic expressions, it is often necessary to substitute one variable or function for another. Substitution is often a critical step when deriving an equation or simplifying an expression.
Timeforaction–substitutingsymbolsinexpressions
Let's see how to perform symbolic substitutions with Sage. var('x, y')
f(x) = 1 / x + 3 * x^2 + cos(x) f.show()
print("Substitute for x with a keyword:") show(f.subs(x=(7 * x)))
print("Substitute for x with a relational expression:") show(f.substitute(x == 7 * x))
print("Substitute sine for cosine:") show(f.substitute_function(cos, sin)) print("Substitute using a dictionary:") show(f.substitute({1 / x: y^3, cos(x):sin(x)}))
[ 182 ]
Chapter 7
The results are shown in the following screenshot:
What just happened?
We used several methods to substitute both variables and functions in a callable symbolic expression. The methods called subs and substitute are identical. If you only need to replace a single symbol, a keyword argument can be used to specify which variable is to be replaced, and what expression should take its place. Multiple keywords can be used to make multiple substitutions at the same time. A relational expression can be used to replace a single symbol, or a sub-expression. We then used the method substitute_function to replace one function (sine) with another (cosine). Finally, we demonstrated that a dictionary can be passed to the substitute (or subs) method to specify the substitution. Each key:value pair in the dictionary describes one substitution. The key is the expression to
be replaced, and the value is the replacement. Using a dictionary is very flexible, because you can replace a variable, a sub-expression (such as 1/x), or a function. When you use a dictionary to replace a function, note that you have to describe the functions as cos(x) and sin(x), rather than cos and sin.
[ 183 ]
Making Symbolic Mathematics Easy
Another way to perform substitutions is with the substitute_expression method (and its synonym subs_expr). These methods use the subst command in Maxima, which performs a formal pattern substitution. The results may not be mathematically meaningful, so it is best to avoid these two methods if possible.
Expandingandfactoringpolynomials
Expanding a polynomial is the process of converting the polynomial from a product of sums to a sum of products. Factoring is the opposite process, in which a sum of products is converted into a product of factors.
Timeforaction–expandingandfactoringpolynomials
A number of methods are especially useful when working with polynomials. Let's see how they work:
var('x')
exp1 = (x + 3)^3 == (x - 1)^2 show(exp1)
print("Expanded expression:") exp2 = exp1.expand() show(exp2)
print("Expand left-hand side only:") show(exp1.expand('left'))
lhs = exp1.expand('left').lhs()
print("Factor LHS:") show(lhs.factor())
print("Information about the expanded LHS:")
print(" Highest degree of x on LHS: {0}".format(lhs.degree(x))) print(" Coefficients: {0}".format(lhs.coeffs(x)))
print(" Coefficient of x^2: {0}".format(lhs.coeff(x,2))) print(" Trailing coefficient of LHS: {0}".format
(lhs.trailing_coefficient(x)))
[ 184 ]
Chapter 7
The output is shown in the following screenshot:
What just happened?
We defined a relational symbolic expression that equates two polynomials. We used the expand method (with no arguments) to multiply out the polynomials on each side of the equality. We also used the expand method with the optional argument 'left' to expand only the left-hand side (you can also use 'right'). We then used the factor method to factor the expanded left-hand side of the expression, and recovered its original form. These two methods are complementary, and can be used to move back and forth between different representations of a polynomial.
We also demonstrated some methods that return information about polynomials. The method degree returns the largest exponent of the given symbol in the polynomial. The method coeffs (or coefficients) returns a list that contains the coefficients of each term in the polynomial. Each item in the list is another list. The first item is the coefficient, and the second item is the degree of the term with that coefficient. The coeff (or coefficient) method allows us to get the coefficient for a specific term. Its first argument specifies a symbol, and its second argument specifies the power of that symbol. You may need to expand or factor the polynomial before calling this method. Finally, the method trailing_coefficient (or trailing_coeff) was used to obtain the coefficient for the smallest power of x in the left-hand side.
[ 185 ]
Making Symbolic Mathematics Easy
The factor function in Sage is used to factor both polynomials and integers. This behaviour is different from Mathematica, where Factor[] is used to factor polynomials and FactorInteger[] is used to factorize integers.
Manipulatingtrigonometricexpressions
Expressions involving trigonometric functions can be difficult to manipulate because of the numerous trigonometric identities that can be used (http://en.wikipedia.org/wiki/ List_of_trigonometric_identities). Fortunately, Sage can automate this process.
Timeforaction–manipulatingtrigonometricexpressions
Sage has several methods that are used primarily when an expression involves trigonometric functions. Let's try them out.
var('x, y')
f(x, y) = sin(x) * cos(x)^3 + sin(y)^2 print("f(x, y)")
f.show()
g(x, y) = f.reduce_trig() |
# also trig_reduce |
|
print("After trig_reduce:") |
|
|
g.show() |
|
|
print("After expanding:") |
|
|
show(g.expand_trig()) |
# also trig_expand |
|
print("Simplify to get original expression:") |
||
show(g.expand_trig().trig_simplify()) |
# also simplify_trig |
|
The output is shown in the following screenshot:
[ 186 ]
Chapter 7
What just happened?
We demonstrated some useful methods that are specifically designed to manipulate expressions that involve trigonometric functions. expand_trig and reduce_trig (or trig_expand and trig_reduce) are complementary methods that have a similar function to those used in the previous example. We also introduced the method called trig_ simplify (or simplify_trig), which attempts to represent an expression in the most compact way.
Logarithms,rationalfunctions,andradicals
There are special rules for manipulating logarithms and radicals, so Sage has special methods for expanding and simplifying expressions involving these operations. There is also a separate method for simplifying rational expressions.
Timeforaction–simplifyingexpressions
In the following example, we will see how Sage can be used to simplify expressions that involve exponentials, logarithms, rational functions, and square roots:
var('x')
# Logs
f(x) = log(x^2 * sin(x) / sqrt(1 + x)) print("Original function:")
f.show()
print("This form is easier to work with:") show(f.expand_log())
print("Simplify expanded form:") show(f.expand_log().simplify_log())
# Rational functions
f(x) = (x + 1) / (x^2 + x)
print("Original function:") f.show() print("Simplified:") show(f.simplify_rational())
# Radicals
f(x) = sqrt(x^2+x)/sqrt(x) print("Original function:") f.show() print("Simplified:") show(f.simplify_radical())
[ 187 ]
Making Symbolic Mathematics Easy
The output is shown in the following screenshot:
[ 188 ]
Chapter 7
What just happened?
We demonstrated some special methods for expanding and simplifying expressions involving logs, rational functions, and radicals. The following table summarizes the methods available in Sage for simplifying and expanding expressions:
Method(s) |
Description |
|
expand_log log_ |
Expands logarithms of powers, logarithms of products, and logarithms |
|
expand |
of quotients |
|
simplify_log |
Attempt to simplify an expression involving logarithms |
|
log_simplify |
|
|
simplify_rational |
Attempt to simplify an expression involving rational expressions |
|
rational_simplify |
|
|
radical_simplify |
Attempt to simplify an expression involving radicals |
|
simplify_radical |
|
|
exp_simplify |
|
|
simplify_exp |
|
|
simplify_ |
Simplify an expression by combining factorials and expanding binomials |
|
factorial |
into factorials |
|
factorial_ |
|
|
simplify |
|
|
simplify_full |
Applies the following operations, in order: simplify_factorial, |
|
full_simplify |
simplify_trig, simplify_rational, simplify_radical, |
|
simplify_log, and again simplify_rational |
||
|
||
|
|
It can be tricky to get an expression in the form that you want. You may have to experiment with various combinations of expanding, simplifying, and factoring an expression. Part of the problem is that it is difficult to quantify the "simplest" form of an expression. Most of the commands in Sage that factor, expand, or simplify expressions accept optional arguments that control how they work. Look at the documentation for each method for more information.
Logarithms in Sage
The log function in Sage assumes the base of the logarithm is e. If you want to use a different base (such as 10), use the optional argument with keyword base to specify the base. For example: log(x, base=10)
[ 189 ]
Making Symbolic Mathematics Easy
Solvingequationsandfindingroots
Solving equations is a fundamental task in mathematics. A related task is finding the values of the independent variables for which a function is equal to zero, which is known as finding its roots.
Timeforaction–solvingequations
Enter the following code into an input cell in a worksheet, and evaluate the cell:
var('x, y')
#Solve a single equation f(x) = x^3 - 1
solution1 = solve(f == 0, x) for solution in solution1:
print(solution)
#Solve a system of equations
solutions = solve([x^2 + y^2 == 1, y^2 == x^3 + x + 1], x, y, solution_dict=True)
print("\nSolution to system:") for solution in solutions:
print("x = {0} y = {1}".format(solution[x], solution[y]))
#Solve an inequality print("\nSolution to inequality:")
solve(-20 * x - 30 <= 4 * x^3 - 7 * x, x)
#Plotted in previous example
The output is shown in the following screenshot:
[ 190 ]
