Mathematica Notes
Compiled by Jeremy Kelly
www.anthemion.org
Printed UNKNOWN
These are my Mathematica notes, covering basic features in Mathematica 12. They aren't quite done, but they cover the basics pretty well. If you find a mistake, let me know.
This page includes a two-column print style. For best results, print in landscape, apply narrow margins, change the Scale setting in your browser’s print options to 70%, and enable background graphics. Firefox and Chrome each have their own set of printing bugs, but one of them usually works.
Contents
- Notebooks
- Expressions
- Lists
- Spans
- Iterators
- Associations
- Replacements
- Pattern matching
- Assignment
- Functions
- Pure functions
- Applying arguments
- Mapping functions
- Operator forms
- Algebra and Trigonometry
- Simplifying expressions
- Expanding expressions
- Factoring expressions
- Solving equations and inequalities
- Calculus
- Differentiation
- Integration
- Differential equations
- Power series
- Graphing
- Other graph types
- Interactive graphics
- Sources
Notebooks
Mathematica stores headings, text, commands, and output in cells, which are listed sequentially within a notebook. One cell can store multiple commands. The current cell is executed by pressing Shift+Enter. Adding a semicolon to the end of a command suppresses output.
Mathematica automatically numbers input and output cells as they are evaluated. The cell number starts with one, and increases with each evaluation. If the same input is re-evaluated, that cell and its output are renumbered. The last output can be referenced with %
.
Most output is displayed in a form similar to traditional math notation. When math output is copied, however, a text representation is added to the clipboard. Sometimes this text differs greatly from the display. In these notes, both styles are used. Cells rendered with a fixed-width font give the output as copied, while cells using a proportional font give the output as displayed.
Variable and function definitions persist for the lifetime of the Mathematica kernel session. They are also global to all open notebooks. To clear such definitions:
Remove["Global`*"]
The most recent result can be retrieved with the %
operator.
All built-in functions are capitalized. A short reference for most built-in functions can be displayed in the notebook by executing the ?
command:
? sym
Similar information can be displayed in a pop-up window by mousing over a built-in function and clicking one of the help buttons that appear.
A cell can be made to display formatted text by selecting Format / Style / Text from the menu. The Style menu also offers a variety of heading styles.
Expressions
Every expression has a head, which is the type or operation at the topmost level of evaluation:
Head[1/3]
Head[(2 * a) + b]
Rational
Plus
For accuracy, Mathematica represents values as rational expressions until a decimal result is required. A decimal value can be obtained with the N
function:
N[2/7]
0.285714
The second argument, if supplied, defines the precision of the output:
N[Pi, 16]
The *^
operator allows numbers to be entered with a form of scientific notation:
2.5*^3
2500.
The ^^
operator specifies an arbitrary base:
16^^A0
160
Within input cells, the imaginary unit is represented by I
. In output, Mathematica displays this in lowercase, with the blackboard font:
Solve[x^2 + 1 == 0, x]
{{x -> -I}, {x -> I}}
The real and imaginary parts of an expression can be extracted with the Re
and Im
functions. If variables in this expression are undefined, Mathematica will return terms that themselves contain Re
or Im
:
x = a + b I;
Im[x]
Im[a] + Re[b]
In this example, a
could itself be a complex expression, so only the imaginary part of that expression is returned. Similarly, b
could be complex, and only the real part — when multiplied by I
— would produce an imaginary number.
Equivalence is tested with the ==
operator. Boolean values are represented as True
and False
. Boolean operators include &&
, ||
, and !
.
Placing a space between two symbols implicitly multiplies them:
s t == s * t
True
Omitting the space would produce a new symbol, st
.
Greek letters can be used as symbols, or as parts of symbols. To enter one, press Esc, type the LaTeX markup for the letter, and then press Esc again. Alternatively:
- Press Esc;
- Type one or more letters of the symbol name, without the LaTeX backslash;
- Select the desired symbol from the popup list;
- Press Enter to insert the symbol. There is no need to press Esc again.
Lists
A list is defined by enclosing zero or more comma-delimited values in curly braces:
{4, 6, 9}
Lists can be generated automatically with the Range
function:
Range[min, max, step]
If the third argument is omitted, the step length is set to one:
i = Range[2, 4]
{2, 3, 4}
Lists are one-indexed. An element can be extracted with the Part
function, or by enclosing the index within double square brackets:
i[[2]]
3
Negative indices count backwards from the end, with negative one returning the last element. No element is referenced by index zero.
When elements are extracted from nested lists, the leftmost index applies to the outermost list:
l = {{1, 2, 3}, {3, 4, 5}};
l[[1]][[2]]
2
When applied to a list, scalar operations produce a new list with an equivalent structure. The operation is recursively applied to each element:
{4, {1}} / 10
{2/5, {1/10}}
When applied to two lists of the same length, many operations produce a new list that contains the element-wise result of the operation:
{1, 4, 9} / {2, 4, 3}
{1/2, 1, 3}
These operations produce an error if the list lengths differ.
Spans
A span of elements can be specified with the ;;
operator:
first;;last
Note that the second argument gives the index of the last element, not the length of the span. A step size can also be specified:
first;;last;;step
Omitting first causes elements from the start to be returned. Omitting last returns elements through the end:
{2, 3, 4, 5, 6}[[3;; ;;2]]
{4, 6}
If first and last fail to overlap, an empty list will be returned. A value can be assigned to a span, but doing so replaces every element in the span with a copy of the value. It does not change the length of the list:
i = {11, 12, 13, 14};
i[[2 ;; 3]] = {0};
i
{11, {0}, {0}, 14}
However, if a list with the same length as the span is assigned, its elements will replace the corresponding elements in the span:
i[[2 ;; 3]] = {102, 103};
i
{11, 102, 103, 14}
Iterators
Some functions, like Table
:
Table[expr, iter]
use the iterator syntax to generate values. In particular, Table
passes the values to an expression, which it uses to generate elements in a list:
Table[x^2, {x, 3}]
{1, 4, 9}
The iterator is an argument list. When two scalar arguments are provided, var ranges from one to valMax:
{var, valMax}
When three are provided, it ranges from valMin to valMax:
{var, valMin, valMax}
A fourth argument sets the step size:
{var, valMin, valMax, step}
If the second argument is another list, those values will be iterated:
{var, {val1, val2, ...}}
Table
can also accept multiple iterators:
Table[expr, iter1, iter2, ...]
This variant produces a nested list, with one level for each iterator. The left-most iterator corresponds to the outer level of the list:
Table[(x^2 + y^2), {x, 3}, {y, 2}]
{{2, 5}, {5, 8}, {10, 13}}
If the second Table
argument is a scalar:
Table[expr, count]
It returns count copies of expr.
Associations
A rule is a value pair, typically specified as:
key -> val
In Mathematica, associative arrays are known as associations. One is defined by enclosing a set of rules in angle braces and pipes. The keys are typically strings:
m = <|"min" -> 0, "max" -> 10|>;
Values are allowed to vary in type. A value is retrieved by passing the key to the association in square braces:
m["max"]
10
Replacements
The ReplaceAll
function:
-
ReplaceAll[expr, rules]
causes elements in expr to be replaced with new values, as specified by rules. The same operation is performed by the /.
operator:
expr /. rules
This can be used to replace open variables with specific values:
a + b /. {a -> 1, b -> 2}
3
If only one replacement is made, the rule can be specified without a list:
a + b /. a -> 1
1 + b
If a list of rule lists are applied to an expression, a list of results will be returned:
a + b /. {{a -> 1}, {b -> 2}, {a -> 3, b -> 4}}
{1 + b, 2 + a, 7}
This can be used to extract values from a solution list:
eq = (x^2 + x - 12 == 0);
Solve[eq, x]
x /. %
{{x -> -4}, {x -> 3}}
{-4, 3}
The standard rule syntax causes repl to be evaluated once, when the rule is defined:
orig -> repl
The delayed syntax:
orig :> repl
causes repl to be evaluated every time it is used:
i = 0;
{x, x^2, x^3} /. x :> ++i
{1, 4, 27}
Pattern matching
Cases
returns list elements that match some pattern:
Cases[{expr1, expr2, ...}, patt]
Patterns typically contain underscores called blanks. These can represent any expression:
Cases[{x^2, x^2 + 2, x^2 + y, y^2 + 1}, (x^2 + _)]
{2 + x^2, x^2 + y}
If a blank is prefixed with a name, the expression matched by that blank can be referenced. Another Cases
variant combines the pattern with a rule:
Cases[{expr1, expr2, ...}, patt -> val]
This rule can reference the named blank in its value. Note that the underscore is not included when the name is used:
Cases[{x, y^2, z^4}, b_^e_ -> b * e]
{2 y, 4 z}
Appending a head to the blank causes it to match expressions of that type only:
Cases[{0, 1, x}, _Integer]
{0, 1}
The condition operator /;
modifies a pattern so that it matches only when the expression that follows is true:
p = x_ /; (x > 0);
Cases[{-1, 0, 1, 2}, p]
{1, 2}
Conditions can also be added to rules, typically delayed rules so the condition can be evaluated at replacement time:
orig :> repl /; cond
When a condition is added to an assignment:
var := expr /; cond
the assignment applies only when the condition is true:
f[x_] := Sqrt[x] /; (x >= 0);
f[-1]
f[-1]
Other pattern-matching operators are useful when defining functions. These include the blank sequence and the blank null sequence, described below.
Alternative values can be delimited with the |
operator:
Cases[{a[0], b[1], c[2]}, _[1 | 2 | 3]]
{b[1], c[2]}
Except
inverts the pattern match result, so that non-matching elements are selected:
Cases[{0, x, y}, Except[_Integer]]
{x, y}
Other Cases
variants allow matches to be found at varying depths within nested lists.
Assignment
An expression can be assigned to a variable with the =
operator. This produces immediate assignment, which copies the current value:
a = 10;
x = a;
a = 20;
x
10
The :=
operator produces delayed assignment, which causes the expression to be re-evaluated when the variable itself is evaluated:
y := a;
a = 30;
y
30
An assignment can be removed with the =.
operator:
y =.
By default, Mathematica displays unrecognized names in blue. After a variable with the name has been assigned, it is displayed in black.
Functions
A function is a name followed by a list of zero or more arguments in square braces. It can be defined with immediate:
func[args] = expr
or delayed assignment:
func[args] := expr
Arguments are often specified as named blanks in the argument list. As expected, these are referenced without underscores in the expression that follows:
y[x_] = (x / 2) + 4;
Custom functions are invoked like built-in functions:
y[10]
9
Direct assignment causes the function expression to be evaluated, as far as possible, when the function is defined. As a result, this case:
di[x_] = D[x^2, x];
is equivalent to:
di[x_] = 2x
Delayed assignment stores the expression in its original form, and evaluates it from scratch when the function is invoked. When this is done, Mathematica displays arguments within the function expression in green to show what will be replaced. Passing a numeric argument to this function:
dd[x_] := D[x^2, x];
would set the second D
argument to a number, producing an error.
Where one underscore produces a blank, two underscores produce a blank sequence, which matches a series of one or more comma-delimited expressions. Three underscores produce a blank null sequence, which matches zero or more expressions. These can be used to define variable-argument functions:
f[x__] := Length[{x}]^Plus[x];
f[1, 2]
8
Note that delayed assignment is necessary in this case to ensure that the expression is evaluated when the function is invoked, rather than when it is defined.
Mathematica functions are essentially pattern transformations, so arguments can match very specific parts of the input:
o[x^n_] = n;
{o[x^2], o[y^2]}
{2, o[y^2]}
This pattern matching may not capture the sense of the definition, however, and Mathematica may simplify the input in a way that contradicts the pattern:
{o[x], o[x^1], o[x^2]}
{o[x], o[x], 2}
Functions can also be assigned with piecewise definitions, which apply to specific inputs:
g[1] = 10;
{g[1], g[2]}
{10, g[2]}
These take precedence over any pattern-matching definition that might exist.
A function can be undefined with the Clear
function.
Pure functions
A pure function is Mathematica's analog of a lambda expresssion. It is defined by appending an ampersand to an expression. It is invoked, like any other function, by appending square braces:
1&[]
1
Normally, the expression includes one or more arguments, represented by pound signs:
(# * 10)&[3]
30
When there are multiple arguments, they are distinguished by appending numbers to the pound signs. The first argument is #1
:
(#1^#2)&[2, 3]
8
If an association is passed to the function, its values can be retrieved by appending key names to the pound signs:
m = <|"first" -> 2, "last" -> 4|>;
(Table[x^2, {x, #first, #last}])&[m]
{4, 9, 16}
Pure functions are typically passed to other functions, like Select
:
Select[{2, 4, 6}, (Mod[#, 3] == 1)&]
{4}
Applying arguments
The prefix operator @
:
expr @ arg
applies arg to expr as if it were a function argument, producing:
expr[arg]
The Apply
function:
Apply[expr, arg]
replaces the head of an expression with another expression. If the head of a list is replaced with a function, the list elements become function arguments:
Apply[f, {0, x, y/2}]
f[0, x, y/2]
The same operation can be performed with the @@
operator:
Times @@ {3, 4, x}
12 x
Other Apply
variants accept a level specification, which allows heads to be replaced within nested elements. The @@@
operator replaces heads at the first level within the list:
g @@@ {0, {1}, {{2}}}
{0, g[1], g[{2}]}
The postfix operator //
:
arg // expr
reverses the functionality of the prefix operator:
x^2 + 3 y // h
h[x^2 + 3 y]
Mapping functions
Map
passes every element in a list to some function, then returns a new list that contains the results:
Map[(#^2)&, {2, 3, 4}]
{4, 9, 16}
The same operation is performed by the /@
operator:
Sqrt /@ {2, 3, 4}
{Sqrt[2], Sqrt[3], 2}
Another Map
variant accepts a level specification, which allows nested elements to be passed to the function.
Operator forms
Some built-in functions are usable in operator form, which is a new function that predefines some arguments while leaving others open. An example is Select
:
Select[list, func]
which applies func to the elements in list, and returns a new list containing the elements for which func returned True. Invoking Select
without the list produces a new function:
c[x_] = (Sqrt[x] < 10);
s = Select[c];
which can then be used with any list:
s[{64, 81, 100}]
{64, 81}
Algebra and Trigonometry
AddSides
, SubtractSides
, MultiplySides
, and DivideSides
combine an expression with both sides of an equation or inequality. ApplySides
produces a new equation or inequality that relates two invocations of a specified function, with the original left and right sides serving as arguments:
ApplySides[Exp, Log[x] == a/b]
x == E^(a/b)
Other functions return values that summarize an expression or its terms. These include Coefficient
, CoefficientList
, Variables
, and Exponent
, among others.
Simplifying expressions
The Collect
function:
Collect[expr, terms]
gathers like powers of the specified terms together:
Collect[(a x + b) + (c x + d), x]
b + d + (a + c) x
terms can specify a single term, a list of terms, or a pattern that matches the terms to be collected.
Together
joins a sum of rational expressions into a single term with a common denominator:
Together[a/b + c/d]
(b c + a d)/(b d)
Cancel
removes common factors from a rational expression.
Simplify
attempts to produce a simpler form for some expression. It performs both algebraic and trigonometric simplifications:
Simplify[2 Sin[u] Cos[u]]
Sin[2 u]
An optional second argument accepts one or more assumptions:
Simplify[expr, assum]
these being logical statements about the variables in expr that can be used to further simplify the result:
s = Sqrt[x^2];
Simplify[s, x > 0]
x
assum can also define domains in the expression:
Simplify[Cos[n Pi], n ∈ Integers]
(-1)^n
To enter the 'element' symbol, press Esc, type 'el
', and then press Esc again. The same assertion can be made with the Element
function:
Element[var, dom]
Functions like Refine
, Limit
, Series
, and Integrate
also use assumptions. These can be defined for an entire notebook by assigning to the global $Assumptions
variable:
$Assumptions = x > 0;
This works because those functions have Assumptions
options that reference $Assumptions
by default.
Simplify
considers a limited range of transformations. The FullSimplify
function is more powerful, but, if the expression has many terms, it can be very slow:
FullSimplify[expr]
FullSimplify[expr, assum]
FullSimplify
also provides the ExcludedForms
option, which uses pattern matching to specify terms that should not be simplified.
Expanding expressions
The Expand
function converts a product of sums into a sum of products:
e = Expand[(a + b)^3]
$$ a^3 + 3 \, a^2 \, b + 3 \, a \, b^2 + b^3 $$
Another variant expands only those terms that match the specified pattern:
Expand[expr, patt]
ExpandAll
includes terms that would not be modified by Expand
, like expressions passed as arguments:
ExpandAll[(f[a (x + 1)] + 1)^2]
1 + 2 f[a + a x] + f[a + a x]^2
ExpandNumerator
and ExpandDenominator
expand parts of a rational expression, while leaving other terms unchanged. Apart
can convert a rational expression of one variable into partial fractions:
Apart[1/((x + 1) (x + 2))]
$$ \frac{1}{1 + x} - \frac{1}{2 + x} $$
PowerExpand
operates on logarithms and non-constant exponents, which would be ignored by Expand
:
PowerExpand[Log[(a b)^n]]
n (Log[a] + Log[b])
If some trigonometric function has an argument that is a sum or product, TrigExpand
can replace it with a sum or product of functions that have simple arguments:
TrigExpand[Cos[2 a]]
Cos[a]^2 - Sin[a]^2
Conversely, TrigReduce
can convert a product of trigonometric functions into a linear sum, often by replacing simple arguments with more complex ones:
TrigReduce[2 Cos[a] Cos[b]]
Cos[a - b] + Cos[a + b]
Factoring expressions
The Factor
function attempts to express its argument as a simple product:
Factor[a^3 + 3 a^2 b + 3 a b^2 + b^3]
(a + b)^3
Simplify
would do the same, but possibly with other changes.
TrigFactor
attempts to factor a trigonometric expression. There can be many ways to do this, and only one of the possibilities is returned:
TrigFactor[Sin[a]^2 + Tan[a]]
1/2 (2 + Sin[2 a]) Tan[a]
Solving equations and inequalities
The Solve
function attempts to find analytic solutions for an equation or inequality, or a system of such:
Solve[stat, vars]
stat contains one more more logical statements that relate two or more expressions. vars is a variable or list of variables for which solutions will be sought. Omitting vars solves for all variables:
Solve[stat]
Note that equations are defined with the equality operator, not the assignment operator:
l = (y == m*x + b);
Solve[l, x]
{{x -> (-b + y)/m}}
Solutions are returned as a list of rule lists:
c = (x^2 + y^2 == r^2);
sc = Solve[c, x]
$$ \{\{x \rightarrow -\sqrt{r^2 - y^2}\}, \, \{x \rightarrow \sqrt{r^2 - y^2}\}\} $$
each defining one set of replacements that are consistent with stat:
c /. sc
{True, True}
An empty list is returned if no solution is possible:
Solve[x != x, x]
{}
An empty nested list, by contrast, indicates that all inputs are solutions:
Solve[x == x, x]
{{}}
Applying this inside list as a set of replacements would produce the original equation or inequality, which has been found to be unconditionally true.
Systems of equations or inequalities can be expressed by combining statements with logical operators:
Solve[l && c, {x, y}]
or by passing the statements in a list:
Solve[{l, c}, {x, y}]
{{x -> ..., y -> ...}, {x -> ..., y -> ...}}
As shown, solving for multiple variables produces rule lists with multiple replacements.
The domain can be specified when using Solve
:
Solve[stat, vars, dom]
dom can be set to Integers
, Rationals
, Reals
, or Complexes
, among others.
Some solutions:
y = (x + 2)^3 + (x + 3)^2;
Solve[(y == 0), Reals]
{{x -> Root[17 + 18 #1 + 7 #1^2 + #1^3 &, 1]}}
make use of the Root
function:
Root[func, num]
which produces one domain value, indexed by num, out of all those for which func returns zero. In output cells, the Root
function is displayed with a cartouche that contains the first digits of its numerical value.
The Reduce
function can also be used to find solutions, particularly those that cannot be represented with a finite number of replacements:
Reduce[(a > 2) && (a < 1 || a < 3)]
2 < a < 3
It does this by simplifying the logical statement, rather than listing values for which the statement is true. Its output is also a logical statement:
Reduce[x != x]
False
Specifying vars:
Reduce[stat, vars]
requests that the result be expressed as a statement about those variable:
Reduce[c]
Reduce[c, x]
$$ r = -\sqrt{x^2 + y^2} \enspace | \, | \enspace r = \sqrt{x^2 + y^2} $$
$$ x = -\sqrt{r^2 - y^2} \enspace | \, | \enspace x = \sqrt{r^2 - y^2} $$
As with Solve
, a domain can be specified:
Reduce[stat, vars, dom]
Reduce
can find solutions that Solve
cannot, but it is slower, and its output is sometimes very complex.
Instead of returning a general solution, the FindInstance
function:
FindInstance[stat, vars]
returns specific values for vars that satisfy stat:
FindInstance[(x^2 + y^2 + z^2 == 1), {x, y, z}]
{{x -> -1, y -> 0, z -> 0}}
Other forms specify the domain, or the number of instances to be returned:
FindInstance[stat, vars, dom]
FindInstance[stat, vars, dom, ct]
Calculus
Differentiation
The D
function returns the derivative of a function. The simplest form:
D[func, var]
produces the first derivative with respect to var:
D[x^2 y^2, x]
2 x y^2
If more variables are passed, the derivative is calculated with respect to all of them:
D[x^2 y^2, x, y]
4 x y
A variable can be replaced with a two-element list that gives the variable and the order of the derivative:
D[x^2 y^2, {x, 2}, y]
4 y
Derivatives can also be obtained by appending one or more 'primes' to one-variable functions:
f[x_] = x^3;
f''[t]
6 t
If a function has not been defined, its derivative cannot be evaluated. Instead of displaying one of the traditional notations, Mathematica adds a superscript to the function that gives the order of each derivative:
D[g[x, y], {x, 2}, {y, 1}]
g(2,1)[x, y]
On paper, this might be written:
$$ \frac{\partial^3 g}{\partial x^2 \partial y}$$
Integration
Integrate
returns the integral of some function. Its syntax is comparable to D
. The simplest form:
Integrate[func, var]
produces the indefinite integral with respect to var:
Integrate[x y, x]
$$ \frac{x^2 y}{2} $$
If more variables are passed, the integral is calculated with respect to all of them:
Integrate[x y, x, y]
$$ \frac{x^2 y^2}{4} $$
A variable can be replaced with a three-element list that also gives the lower and upper bounds. This produces a definite integral:
Integrate[x y, {x, 0, 3}]
$$ \frac{9 y}{2} $$
In some cases, the result is returned within a ConditionalExpression
, which lists the conditions under which the result holds:
Integrate[x^n, {x, 0, 1}]
ConditionalExpression[1/(1 + n), Re[n] > -1]
Stipulating these conditions with the Assumptions
option produces the result without ConditionalExpression
:
Integrate[x^n, {x, 0, 1}, Assumptions -> n > -1]
1/(1 + n)
NIntegrate
uses numerical techniques to evaluate a definite integral:
NIntegrate[Sqrt[2 - Cos[t]], {t, 0, Pi}]
4.36888
Differential equations
The DSolve
function:
DSolve[eqn, func, var]
attempts to solve a differential equation. func specifies the function to be solved, and var gives its independent variable:
e = (f'[x] + k f[x] == 0);
se = DSolve[e, f[x], x]
{{f[x] -> E^(-k x) C[1]}}
The same equation could be specified with D[f[x], x]
in place of f'[x]
. Higher-order derivatives can be specified with D
, or by adding primes to the function name.
Output often includes the C
function, which is rendered in output cells with the blackboard font, as though it were a constant. It can represent a constant, as it does in this case, but the term itself is a Mathematica function, and it can also represent another function. Its argument distinguishes one C
value from another, and this number is displayed in the output as a subscript.
Such constants can be avoided by specifying boundary conditions. These are passed to DSolve
in a list:
DSolve[{e, f[0] == a}, f[x], x]
{{f[x] -> a E^(-k x)}}
The equation can be solved for a specific range by replacing the variable with a three-element list that includes the minimum and maximum:
DSolve[eqn, func, {var, min, max}]
In the examples above, the equation is solved for f[x]
, so the solution replaces that term with an expression. It can also be solved for the function alone, without its argument:
sf = DSolve[e, f, x]
{{f -> Function[{x}, E^(-k x) C[1]]}}
When this is done, the solution replaces f
with a Function
expression that can be invoked with the original argument. That allows the solution to be checked with a simple replacement:
e /. sf
{True}
Applying the expression replacement would leave the derivative in the original equation unchanged.
Partial derivatives are specified with D
. The independent variables are placed in a list:
e = m x D[g[x, y], x] - n y D[g[x, y], y] == 0;
DSolve[e, g[x, y], {x, y}]
{{g[x, y] -> C[1][x^(n/m) y]}}
In this case, the C
function represents any differentiable function, the argument of which is x^(n/m)*y
.
Power series
The Series
function returns a power series that approximates a function near some point:
Series[func, {var, val, ord}]
The approximation is made with respect to var, for inputs near val, and it includes (var - val)
terms with exponents as high as ord. It can be extended to other variables by providing additional var/val/ord lists.
In the notebook, the Series
output appears as a regular polynomial, with an additional O
term representing unknown, higher-order elements:
f = Sqrt[x];
fs = Series[f, {x, 1, 2}]
$$ 1 + \frac{x-1}{2} - \frac{1}{8}\,(x-1)\,^2 + \mathrm{O}\,[x-1]\,^3 $$
However, it is actually a SeriesData
expression:
SeriesData[x, 1, {1, Rational[1, 2], Rational[-1, 8]},
0, 3, 1]
This function represents a series abstractly:
SeriesData[var, val, {coeff0, coeff1, ...}, ordMin, ordMax, denom]
It gives the original var and val, along with a list of coefficients, and the minimum and maximum exponents of the (var - val)
terms. Note that ordMax gives the order of the O
term, which is not part of the approximation. denom is a common denominator for the series as a whole.
SeriesData
cannot be evaluated directly. Normal
converts the representation to an ordinary polynomial that can be evaluated:
fsn = Normal[fs]
{f, fsn} /. x -> 1.1
1 + 1/2 (-1 + x) - 1/8 (-1 + x)^2
{1.04881, 1.04875}
Graphing
The Plot
command graphs a function in two dimensions:
Plot[func, {var, min, max}]
var specifies the independent variable, on the horizontal axis. min and max set the domain of the graph. The codomain is calculated automatically, or it can be defined with the PlotRange
option. Like other options, this is specified as a rule:
Plot[Sin[x] Cos[2 * x], {x, -2 Pi, 2 Pi},
PlotRange -> {-2, 4}]
A group of functions can be plotted together by passing them as a list:
Plot[{func1, func2, ...}, {var, min, max}]
Plot
is defined with the HoldAll
attribute, which causes functions to be evaluated somewhat like delayed assignments. In particular:
Plot[D[x^9, x], {x, -1, 1}]
causes the second D
argument to be replaced with a numeric value, which produces an error. This can be fixed by applying the Evaluate
function, which overrides HoldAll
:
Plot[Evaluate@D[x^9, x], {x, -1, 1}]
or by setting the Evaluated
option to True
:
Plot[D[x^9, x], {x, -1, 1}, Evaluated -> True]
This is necessary in some cases that seem not to require it. For instance:
g = 1 - x + x^2 + O[x]^3;
Plot[Normal[g], {x, 1, 9}]
produces an error, which is avoided with:
Plot[Normal[g], {x, 1, 9}, Evaluated -> True]
Other graph types
Plot3D
graphs in three dimensions:
Plot3D[func, {var1, min1, max1}, {var2, min2, max2}]
Parametric systems can be graphed with ParametricPlot
or ParametricPlot3D
:
x = Sqrt[t] * Cos[t];
y = Sqrt[t] * Sin[t];
ParametricPlot[{x, y}, {t, Pi, 16 * Pi}]
Mathematica can also plot graphs using polar coordinates, it can plot discrete points, or it can produce contour and density graphs, among many other things.
Interactive graphics
The Manipulate
command wraps another function in a window that contains a slider. This can be used to vary one of the arguments in real time:
f[x_, n_] = Sin[Sin[x^n]];
Manipulate[Plot[f[x, n], {x, 0, 8}], {n, 1, 2}]
It is typically used with graphing functions, but it can be applied to anything that generates output:
Manipulate[2^n, {n, 1, 16, 1}]
Other variants display a label next to the slider, or define a step size for its output, or cause it to select from a list of arbitrary values. It is also possible to vary multiple arguments with multiple sliders.
Sources
A Mathematica Primer for Physicists
Jim Napolitano
2018, CRC Press / Taylor & Francis Group
The Wolfram Language: Fast Introduction for Programmers
Retrieved April 2019
Wolfram Language System & Documentation Center:
Algebraic Manipulation,
Algebraic Transformations,
Apply,
Applying Functions to Lists and Other Expressions,
$Assumptions,
Blank,
Cases,
Condition,
DSolve,
FindInstance,
Map,
Range,
Reduce,
ReplaceAll,
Rules & Patterns,
SeriesData,
Simplify,
Simplification,
Simplifying Algebraic Expressions,
Solve,
Span,
Span,
Structural Operations on Polynomials,
Table,
Theorem Proving,
Trigonometric Expressions,
Using Assumptions
Retrieved April-June 2019
Many equations on this page were typeset with MathJax