Trump's deputy press secretary tries to spin Jeff Sessions' meeting with the Russian ambassador as "a volunteer for a campaign bumping into one at a conference where there’s... dozens of other ambassadors".

The truth turns out to be, "One of the meetings was a private conversation between Sessions and [Kislyak] that took place in September in the senator’s office".

Funny how all of Trump's friends turn out to be complete liars.

After Justice Scalia died, Senate Republicans ignored their constitutional obligation to confirm a replacement, saying "Give the people a voice". But when the people of North Carolina elected a Democratic governor, Republican legislators voted at the last minute to limit his power.

Republicans used to espouse ideals you could almost believe in. Now they're nothing but hypocrites and liars.

Mathematica Notes

Math software notes — Mathematica 12

Mathematica Notes

Compiled by Jeremy Kelly
www.anthemion.org

These are my Mathematica notes, covering basic features in Mathematica 12. They are here primarily for my convenience, but you are welcome to use them, subject to the terms of the Creative Commons Attribution-ShareAlike 4.0 International License. If you find a mistake, please let me know.

This page includes a two-column print style. For best results, print in landscape, apply narrow margins, and change the Scale setting in your browser's print options to 60%. Firefox and Chrome each have their own set of printing bugs, but one of them usually works.

Contents

I just started these notes! Check back later for more.

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 %.

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 a blackboard typeface:

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 is returned. b could also 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.

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:

  1. Press Esc;
  2. Type one or more letters of the symbol name, without the LaTeX backslash;
  3. Select the desired symbol from the popup list;
  4. 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, valMin}

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 whenever the variable 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 by assigning an expression:

func[args] = expr

It can also be defined with delayed assignment. 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;

A custom function is invoked like any other:

y[10]
9

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 to ensure that the function expression is calculated after the arguments have been captured.

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 by appending square braces, like any other function:

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

Manipulating expressions

The Simplify function attempts to produce an expression that is equivalent to the one specified, but simpler:

Simplify[2 Sin[u] Cos[u]]
Sin[2 u]

The optional second argument accepts a logical statement that constrains the input:

Simplify[expr, stat]

This can be used to produce simpler results:

s = Sqrt[x^2];
Simplify[s, x > 0]
x

Simplify attempts a limited range of transformations to save time. The FullSimplify function is less limited, but, if the expression has many terms, it may take some time to execute:

FullSimplify[expr]
FullSimplify[expr, stat]

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}}

The solutions are returned as a list of rule lists:

c = (x^2 + y^2 == r^2);
sc = Solve[c, x]
{{x -> -Sqrt[r^2 - y^2]}, {x -> 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 the inside list as a set of replacements would produce the same equation or inequality, which was unconditionally true to begin with.

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.

Another variant allows the domain to be specified:

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, specified by num, out of all those for which func returns zero. Visually, in output cells, the Root function is represented 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:

Reduce[x != x]
False

As such, its output is also a logical statement. Specifying vars:

Reduce[stat, vars]

determines how the result is expressed:

Reduce[c]
Reduce[c, x]
r == -Sqrt[x^2 + y^2] || r == Sqrt[x^2 + y^2]
x == -Sqrt[r^2 - y^2] || 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 to run, 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 variants specify the domain:

FindInstance[stat, vars, dom]

or the number of instances to be returned:

FindInstance[stat, vars, dom, ct]

Graphing

The Plot command graphs a function in two dimensions:

Plot[func, {var, varMin, varMax}]

var specifies the independent variable, to be displayed on the horizontal axis. varMin and varMax determine 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, varMin, varMax}]

Plot3D graphs in three dimensions:

Plot3D[func, {var1, var1Min, var1Max}, {var2, var2Min, var2Max}]

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, and it can produce contour and density graphs.

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: Apply, Applying Functions to Lists and Other Expressions, Blank, Cases, Condition, DSolve, FindInstance, Map, Range, Reduce, ReplaceAll, Rules & Patterns, Simplify, Simplifying Algebraic Expressions, Solve, Span, Wolfram Language Syntax, Table
Retrieved April-May 2019