Computer Algebra Software: Mathematica, SymPy, GAP, Singular

a side-by-side reference sheet

grammar and invocation | variables and expressions | arithmetic and logic | strings | arrays | arithmetic sequences | dictionaries | functions | execution control | files | libraries and namespaces | reflection

vectors | matrices | symbolic expressions | equations and unknowns | optimization | number theory | polynomials | rings | permutations | groups

univariate charts | bivariate charts | trivariate charts

mathematica sympy gap singular
version used
 
10.0 Python 2.7; SymPy 0.7 4.6 4.0
show version
 
select About Mathematica in Mathematica menu sympy.__version__ $ gap -h $ Singular -vb
implicit prologue import sympy

sympy.init_printing()
grammar and invocation
mathematica sympy gap singular
interpreter
 
if foo.py imports sympy:
$ python foo.py
$ Singular -b foo.sing
repl
 
$ MathKernel $ python
>>> import sympy
$ gap $ Singular
block delimiters
 
( stmt; ) : and offside rule function( ) end
if then elif then else fi
while do od
for do od
{ }
statement separator ; or sometimes newline

; before a newline suppresses output
newline or ;

newlines not separators inside (), [], {}, triple quote literals, or after backslash: \
;

use two semicolons to suppress output:
;;
;
end-of-line comment
 
none 1 + 1 # addition 1 + 1; # addition // comment
multiple line comment
 
1 + (* addition *) 1 none none /* comment line
another comment
*/
variables and expressions
mathematica sympy gap singular
assignment a = 3
Set[a, 3]

(* delayed assignment: *)
a := x + 3
SetDelayed[a, x + 3]
a = 3 a := 3; int a;
a = 3;
parallel assignment {a, b} = {3, 4}
Set[{a, b}, {3, 4}]
a, b = 3, 4 none int a, b;
a, b = 3, 4;
compound assignment += -= *= /=
corresponding functions:
AddTo SubtractFrom TimeBy DivideBy
+= -= *= /= //= %= **= none none
increment and decrement ++x --x
PreIncrement[x] PreDecrement[x]
x++ x--
Increment[x] Decrement[x]
none none x++ x--
non-referential identifier any unassigned identifier is non-referential x, y, z, w = sympy.symbols('x y z w') none none
global variable variables are global by default g1, g2 = 7, 8

def swap_globals():
  global g1, g2
  g1, g2 = g2, g1
local variable Module[{x = 3, y = 4}, Print[x + y]]

(* makes x and y read-only: *)
With[{x = 3, y = 4}, Print[x + y]]
assignments inside functions are to local variables by default
null
 
Null None
null test
 
x == Null x is None
undefined variable access
 
treated as an unknown number raises NameError error
remove variable binding Clear[x]
Remove[x]
del x
conditional expression
 
If[x > 0, x, -x] x if x > 0 else -x
arithmetic and logic
mathematica sympy gap singular
true and false
 
True False True False true false 1 0
falsehoods
 
False False 0 0.0 false 0
logical operators ! True || (True && False)
Or[Not[True], And[True, False]]
sympy.Or(sympy.Not(True), sympy.And(True, False))

# when arguments are symbols:
~ x | (y & z)
not true or (true and false) ! 1 || (1 && 0)
relational operators == != > < >= <=
corresponding functions:
Equal Unequal Greater Less GreaterEqual LessEqual
sympy.Eq sympy.Ne sympy.Gt sympy.Lt sympy.Ge sympy.Le

# when arguments are symbols:
== != > < >= <=
= <> < > <= >= == != < > <= >=
arithmetic operators + - * / Quotient Mod
adjacent terms are multiplied, so * is not necessary. Quotient and Mod are functions, not binary infix operators. These functions are also available:
Plus Subtract Times Divide
+ - * / ?? %

if an expression contains a symbol, then the above operators are rewritten using the following classes:
sympy.Add sympy.Mul sympy.Pow sympy.Mod
+ - * / mod

the operators + - * / are overloaded for integers, rationals, and floats; other arithmetic functions aren't and there are no implicit conversions; use constructors to convert:
Rat(3.1)
Float(3)
Float(31/10)
Operators are for integers only unless
base ring with coefficient field is declared.

+ - * / %

mod is synonym for %
integer division
 
Quotient[a, b] QuoInt(a, b); int a, b = 7, 3;
a div b;

// a / b also performs integer division when
// no base ring is declared.
integer division by zero dividend is zero:
Indeterminate
otherwise:
ComplexInfinity
error error
float division exact division:
a / b
depending upon the types of a and b, the value can be an exact rational, a machine float, or an arbitrary precision float:
a / b
ring r = real,(x,y,z),(dp);

3.1 / 7.2;
float division by zero dividend is zero:
Indeterminate
otherwise:
ComplexInfinity
error error
power 2 ^ 16
Power[2, 16]
2 ** 16
sympy.Pow(2, 16)
2 ^ 16 2 ^ 16
2 ** 16
sqrt returns symbolic expression:
Sqrt[2]
sympy.sqrt(2) 2.0 ^ 0.5 none
sqrt -1
 
I sympy.I -1.0 ^ 0.5 evaluates to -1. none
transcendental functions Exp Log
Sin Cos Tan
ArcSin ArcCos ArcTan
ArcTan
ArcTan accepts 1 or 2 arguments
symp.exp sympy.log
sympy.sin sympy.cos sympy.tan
sympy.asin sympy.acos sympy.atan
sympy.atan2
arguments must be floats; no implicit conversion of integers to floats:
Exp Log
Sin Cos Tan
Asin Acos Atan
Atan2(y, x)
none
transcendental constants
pi and the euler constant
Pi E sympy.pi sympy.E FLOAT.PI FLOAT.E LIB "general.lib";

// print specified number of digits:
number_pi(100);
number_e(100);
float truncation
round towards zero, round to nearest integer, round down, round up
IntegerPart Round Floor Ceiling sympy.floor
sympy.ceiling
Trunc Round Floor Ceil
absolute value
and signum
Abs Sign sympy.Abs sympy.sign AbsInt
no absolute value for floats?
SignInt
SignFloat
LIB "general.lib";

absValue(-7);

ring r = real,(x,y,z),(dp);
absValue(-7.1);
integer overflow
 
none, has arbitrary length integer type none, has arbitrary length integer type none, has arbitrary length integer type modular arithmetic with warning
float overflow
 
none # prints as inf:
FLOAT.INFINTY
rational construction 2 / 7 sympy.Mul(2, sympy.Pow(7, -1)) 2 / 7
rational decomposition
 
Numerator[x/y]
Denominator[x/y]
numer, denom = sympy.fraction(x, y) x := 2 / 7;
NumeratorRat(x);
DenominatorRat(x);
complex construction
 
1 + 3I 1 + 3 * sympy.I none
complex decomposition
real and imaginary part, argument and modulus, conjugate
Re Im
Arg Abs
Conjugate
sympy.re sympy.im
sympy.Abs sympy.arg
sympy.conjugate
none
numerical approximation N[Exp[1]]
Exp[1] + 0.
N[Exp[1], 10]
sympy.N(sympy.E)
sympy.N(sympy.E, 100)
random number
uniform integer, uniform float
RandomInteger[{0, 99}]
RandomReal[]
rs := RandomSource(IsMersenneTwister);
Random(rs, 0, 99);
??
random seed
set, get
SeedRandom[17]
??
rs := RandomSource(IsMersenneTwister, 17);
State(rs);
bit operators BitAnd[5, 1]
BitOr[5, 1]
BitXor[5, 1]
BitNot[5]
BitShiftLeft[5, 1]
BitShiftRight[5, 1]
none
binary, octal, and hex literals 2^^101010
8^^52
16^^2a
none
radix BaseForm[42, 7]
BaseForm[7^^60, 10]
none
strings
mathematica sympy gap singular
string literals "don't say \"no\"" use Python strings "don't say \"no\"" string s = "don't say \"no\"";
newline in literal yes no yes; runaway strings are possible; there is a predefined string variable newline which contains a single newline character
string literal escapes \\ \" \b \f \n \r \t \ooo \b \c \n \r \" \' \\ \ooo

when writing to a buffered output stream, encountering a \c causes a flush of output.
character access Characters["hello"][[1]] s := "hello";
# the character 'h':
s[1];

# cannot use index notation on string literal
// the character h:
"hello"[1]
length StringLength["hello"] Length("hello"); size("hello");
concatenate "one " <> "two " <> "three" Concatenation("one", "two", "three"); string s = "one" + "two" + "three";
index of substring StringPosition["hello", "el"][[1]][[1]]
StringPosition returns an array of pairs, one for each occurrence of the substring. Each pair contains the index of the first and last character of the occurrence.
// evaluates to 2:
find("hello", "el");
extract substring StringTake["hello", {1, 4}] s := "hello";
s{[2..3]};
// start index and substring length:
"hello"[2, 2]
split StringSplit["foo,bar,baz", ","] SplitString("foo,bar,baz", ",");
join StringJoin[Riffle[{"foo", "bar", "baz"}, ","]] a := ["foo", "bar", "baz"];
JoinStringsWithSeparator(a, ",");
substitution s = "do re mi mi"
re = RegularExpression["mi"]

(* replace first occurrence: *)
StringReplace[s, re -> "ma", 1]
(* replace all occurrences: *)
StringReplace[s, re -> "ma"]
# replace all occurrences:
ReplacedString("do re mi mi", "mi", "ma");
trim StringTrim[" foo "] none
number to string "value: " <> ToString[8] Concatenation("value: ", String(8)); "value: " + string(8)
string to number 7 + ToExpression["12"]
73.9 + ToExpression[".037"]
7 + Int("12");
73.9 + Float(".037");
case manipulation ToUpperCase["foo"]
ToLowerCase["FOO"]
UppercaseString("foo");
LowercaseString("FOO");
character literals 'h'
chr and ord FromCharacterCode[{65}]
ToCharacterCode["A"][[1]]
CharInt(65)
IntChar('A')
delete characters s := "disemvowel me";
# no retval; modifies s in place:
RemoveCharacters(s, "aeiou");
arrays
mathematica sympy gap singular
literal {1, 2, 3}

List[1, 2, 3]
use Python lists [1, 2, 3];

# creates array with gap at fourth index;
# reading a[4] causes an error:

a := [1, 2, 3, , 5];
size
 
Length[{1, 2, 3}] Length([1, 2, 3]);
lookup (* access time is O(1) *)
(* indices start at one: *)
{1, 2, 3}[[1]]

Part[{1, 2, 3}, 1]
# indices start at one:
a := [1, 2, 3];
a[1];
update
 
a[[1]] = 7 a[1] := 7;
out-of-bounds behavior left as unevaluated Part[] expression Lookups result in errors; arrays can have gaps which also cause lookup errors.

An update will expand the array, possibly creating gaps.
element index (* Position returns list of all positions: *)
First /@ Position[{7, 8, 9, 9}, 9]
slice
 
{1, 2, 3}[[1 ;; 2]]
array of integers as index (* evaluates to {7, 9, 9} *)
{7, 8, 9}[[{1, 3, 3}]]
manipulate back a = {6,7,8}
AppendTo[a, 9]
elem = a[[Length[a]]]
a = Delete[a, Length[a]]
elem
a = [6, 7, 8];
Add(a, 9);
elem := Remove(a);
manipulate front a = {6,7,8}
PrependTo[a, 5]
elem = a[[1]]
a = Delete[a, 1]
elem
head
 
First[{1, 2, 3}]
tail
 
Rest[{1, 2, 3}]
cons (* first arg must be an array *)
Prepend[{2, 3}, 1]
concatenate
 
Join[{1, 2, 3}, {4, 5, 6}]
replicate
 
ten_zeros = Table[0, {i, 0, 9}]
copy
 
a2 = a
iterate
 
Function[x, Print[x]] /@ {1, 2, 3}
reverse
 
Reverse[{1, 2, 3}]
sort Sort[{3, 1, 4, 2}]
dedupe
 
DeleteDuplicates[{1, 2, 2, 3}] Set([1, 2, 2, 3]);
membership
 
MemberQ[{1, 2, 3}, 2]
intersection Intersect[{1, 2}, {2, 3, 4}] Intersection(Set([1, 2]), Set([2, 3, 4]));
union
 
Union[{1, 2}, {2, 3, 4}] Union(Set([1, 2]), Set([2, 3, 4]));
relative complement, symmetric difference Complement[{1, 2, 3}, {2}]
none
map Map[Function[x, x x], {1, 2, 3}]

Function[x, x x] /@ {1, 2, 3}

(* if function has Listable attribute, Map is unnecessary: *)
sqr[x_] := x * x
SetAttributes[sqr, Listable]
sqr[{1, 2, 3, 4}]
filter
 
Select[{1, 2, 3}, # > 2 &]
reduce Fold[Plus, 0, {1, 2, 3}]
universal and existential tests none
min and max element Min[{1, 2, 3}]
Max[{1, 2, 3}]
shuffle and sample x = {3, 7, 5, 12, 19, 8, 4}

RandomSample[x]
RandomSample[x, 3]
flatten
one level, completely
Flatten[{1, {2, {3, 4}}}, 1]
Flatten[{1, {2, {3, 4}}}]
zip (* list of six elements: *)
Riffle[{1, 2, 3}, {"a", "b", "c"}]

(* list of lists with two elements: *)
Inner[List, {1, 2, 3}, {"a", "b", "c"}, List]

(* same as Dot[{1, 2, 3}, {2, 3, 4}]: *)
Inner[Times, {1, 2, 3}, {2, 3, 4}, Plus]
cartesian product Outer[List, {1, 2, 3}, {"a", "b", "c"}]
arithmetic sequences
mathematica sympy gap singular
range Range[1, 100] range(1, 101) [1 .. 100]
arithmetic sequence of integers with difference 10 Range[1, 100, 10] range(1, 100, 10) [1,11 .. 91]
arithmetic sequence of floats with difference 0.1 Range[1, 100, .1] none
dictionaries
mathematica sympy gap singular
record literal r = { n -> 10, avg -> 3.7, sd -> 0.4}
record member access n /. r
functions
mathematica sympy gap singular
define function Add[a_, b_] := a + b

(* alternate syntax: *)
Add = Function[{a, b}, a + b]
add := function(x, y)
  return x + y;
end;
proc add(int x, int y) {
  return(x + y);
}
invoke function Add[3, 7]

Add @@ {3, 7}

(* syntax for unary functions: *)
2 // Log
add(3, 7); add(3, 7);
attributes
list, set, clear
Attributes[add]
SetAttributes[add, {Orderless, Flat, Listable}]
ClearAtttibutes[add, Listable]
undefine function Clear[Add]
redefine function Add[a_, b_] := b + a
overload function
missing function behavior The expression is left unevaluated. The head is the function name as a symbol, and the parts are the arguments.
missing argument behavior The expression is left unevaluated. The head is the function name as a symbol, and the parts are the arguments.
extra argument behavior The expression is left unevaluated. The head is the function name as a symbol, and the parts are the arguments.
default argument Options[myLog] = {base -> 10}
myLog[x_, OptionsPattern[]] :=
  N[Log[x]/Log[OptionValue[base]]]

(* call using default: *)
myLog[100]

(* override default: *)
myLog[100, base -> E]
return value last expression evaluated, or argument of Return[]
anonymous function Function[{a, b}, a + b]

(#1 + #2) &
# unary functions only?
f := x -> x * x;
variable number of arguments (* one or more arguments: *)
add[a__] := Plus[a]

(* zero or more arguments: *)
add[a___] := Plus[a]
pass array elements as separate arguments Apply[f, {a, b, c}]

f @@ {x, y, z}
a = [x, y, z]
f(*a)
execution control
mathematica sympy gap singular
if If[x > 0,
  Print["positive"],
  If[x < 0,
    Print["negative"],
    Print["zero"]]]
use Python execution control if x > 0 then
  Print("positive\n");
elif x < 0 then
  Print("negative\n");
else
  Print("zero\n");
fi;
int x = -3;
if (x > 0) {
  print("positive");
} else { if (x < 0) {
    print("negative");
  } else {
    print("zero");
  }
};
while i = 0
While[i < 10, Print[i]; i++]
i := 0;
while i < 10 do
  Print(i, "\n");
  i := i + 1;
od;
int i = 0;
while (i < 10) {
  print(i);
  i++;
};
for For[i = 0, i < 10, i++, Print[i]] for i in [0..9] do
  Print(i, "\n");
od;
int i;
for (i = 0; i < 10; i++) {
  print(i);
};
break/continue Break[] Continue[] break continue break continue
raise exception Throw["failed"]
handle exception Print[Catch[Throw["failed"]]]
files
mathematica sympy gap singular
write to stdout Print["hello"] Print("hello"); print("hello");
read entire file into string or array s = Import["/etc/hosts"]
a = StringSplit[s, "\n"]
libraries and namespaces
mathematica sympy gap singular
load Read('foo.g'); LIB "add.sing";
define library $ cat add.sing
version="1.0"
category="misc"
info="an add function"

proc add(int x, int y) {
  return(x + y);
}
library path searches current directory; additional directories can be added to the search path by adding them separated by colons to the SINGULARPATH environment variable
reflection
mathematica sympy gap singular
list function documentation
get function documentation ?Tan
Information[Tan]
print(sympy.solve.__doc__)

# in IPython:
sympy.solve?
help(sympy.solve)
help killall;
list function options Options[Solve]
Options[Plot]
query data type Head[x] typeof(x);
list variables in scope listvar();
vectors
mathematica sympy gap singular
vector literal (* row vector is same as array: *)
{1, 2, 3}
# column vector:
sympy.Matrix([1, 2, 3])
# row vector is same as array:
[1, 2, 3]
vector coordinate indices start at one:
{1,v2, 3}[[1]]
vec := [1, 2, 3];
# indices start at one:
v[1];
vector dimension
 
Length[{1, 2, 3}] Length([1, 2, 3])
element-wise arithmetic operators + - * /
adjacent lists are multiplied element-wise
+ - * /
vector length mismatch
 
error shorter vector is zero-padded
scalar multiplication 3 {1, 2, 3}
{1, 2, 3} 3
* may also be used
3 * [1, 2, 3];
[1, 2, 3] * 3;
dot product {1, 1, 1} . {2, 2, 2}
Dot[{1, 1, 1}, {2, 2, 2}]
v1 = sympy.Matrix([1, 1, 1])
v2 = sympy.Matrix([2, 2, 2])
v1.dot(v2)
[1, 1, 1] * [2, 2, 2]
cross product Cross[{1, 0, 0}, {0, 1, 0}] e1 = sympy.Matrix([1, 0, 0])
e2 = sympy.Matrix([0, 1, 0])
e1.cross(e2)
norms Norm[{1, 2, 3}, 1]
Norm[{1, 2, 3}]
Norm[{1, 2, 3}, Infinity]
vec = sympy.Matrix([1, 2, 3])

vec.norm(1)
vec.norm()
vec.norm(inf)
matrices
mathematica sympy gap singular
literal (* used a nested array for each row: *)
{{1, 2}, {3, 4}}

(* display as grid with aligned columns: *)
MatrixForm[{{1, 2}, {3, 4}}]
sympy.Matrix([[1, 2], [3, 4]])
construct from sequence ArrayReshape[{1, 2, 3, 4, 5, 6}, {2, 3}] sympy.Matrix(2, 3, [1, 2, 3, 4, 5, 6])
constant matrices Table[0, {i, 3}, {j, 3}]
Table[1, {i, 3}, {j, 3}]
sympy.zeros(3, 3)
sympy.ones(3, 3)
diagonal matrices
and identity
DiagonalMatrix[{1, 2, 3}]
IdentityMatrix[3]
sympy.diag(*[1, 2, 3])
sympy.eye(3)
dimensions (* returns {3, 2}: *)
Dimensions[{{1, 2}, {3, 4}, {5, 6}}]
A = sympy.matrix([[1, 2], [3, 4], [5, 6]])

# returns (3, 2):
A.shape
element access (* top left corner: *)
{{1, 2}, {3, 4}}[[1, 1]]
A = sympy.Matrix([[1, 2], [3, 4]])

# top left corner:
A[0, 0]
row access (* first row: *)
{{1, 2}, {3, 4}}[[1]]
# first row:
A[0, :]
column access (* first column as array: *)
{{1, 2}, {3, 4}}[[All, 1]]
# first column as 1x2 matrix:
A[:, 0]
submatrix access A = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
A[[1;;2, 1;;2]]
rows = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
A = sympy.Matrix(rows)
A[0:2, 0:2]
element-wise operators + - * /
adjacent matrices are multiplied element-wise
+ -

# for Hadamard product:
A.multiply_elementwise(B)
product A = {{1, 2}, {3, 4}}
B = {{4, 3}, {2, 1}}
Dot[A, B]
(* or use period: *)
A . B
A = sympy.matrix([[1, 2], [3, 4]])
B = sympy.matrix([[4, 3], [2, 1]])
A * b
power {{1, 2}, {3, 4}} ^ 3 A ** 3
kronecker product A = {{1, 2}, {3, 4}}
B = {{4, 3}, {2, 1}}
KroneckerProduct[A, B]
norms A = {{1, 2}, {3, 4}}

Norm[A, 1]
Norm[A, 2]
Norm[A, Infinity]
Norm[A, "Frobenius"]
transpose Transpose[{{1, 2}, {3, 4}}]

(* or ESC tr ESC for T exponent notation *)
A.T
conjugate transpose A = {{1, I}, {2, -I}}
ConjugateTranspose[A]

(* or ESC ct ESC for dagger exponent notation *)
M = sympy.Matrix([[1, sympy.I], [2, -sympy.I]])
M.adjoint()
inverse Inverse[{{1, 2}, {3, 4}}] A.inv()
pseudoinverse PseudoInverse[{{1, 0}, {3, 0}}]
determinant Det[{{1, 2}, {3, 4}}] A.det()
trace Tr[{{1, 2}, {3, 4}}]
rank
nullspace
range
eigenvalues Eigenvalues[{{1, 2}, {3, 4}}] A.eigenvals()
eigenvectors Eigenvectors[{{1, 2}, {3, 4}}] A.eigenvects()
singular value decomposition
symbolic expressions
mathematica sympy gap singular
replace head Apply[Times, Plus[x, 3]]
Times @@ Plus[x, 3]
Times @@ (x + 3)
prevent simplification HoldForm[1 + 2]
1 + 2 // HoldForm
list evaluation steps Trace[Apply[And, Map[EvenQ, {2, 3, 4}]]]
expand polynomial Expand[(1 + x)^5] sympy.expand((1+x)**5)
factor polynomial Factor[3 + 10 x + 9 x^2 + 2 x^3] sympy.factor(3 + 10*x + 9*x**2 + 2*x**3)
collect terms (* write as polynomial in x: *)
Collect[(1 + x + y)^3, x]
sympy.collect(sympy.expand((x+y+1)3), x)
add fractions Together[a/b + c/d] sympy.together(x/y + z/w)
partial fraction decomposition Apart[(b c + a d)/(b d)] # only one symbol allowed in denominator:
sympy.apart((3*x+2) / (x*(x+1)))
eliminate sums and multiples inside trig functions TrigExpand[Sin[2 x + y]]
eliminate powers of trig functions TrigReduce[Sin[x]^2]
trig to complex exponential
complex exponential to trig
differentiation D[x^3 + x + 3, x] sympy.diff(x**3 + x + 3, x)
higher order differentiation D[Log[x], {x, 3}] sympy.diff(sympy.log(x), x, 3)
unevaluated derivative Hold[D[x^2, x]] sympy.Derivative(x2, x)
mixed partial derivative
power series Series[Cos[x], {x, 0, 10}]
antiderivative Integrate[x^3 + x + 3, x] sympy.integrate(x**3 + x + 3, x)
definite integral Integrate[x^3 + x + 3, {x, 0, 1}] sympy.integrate(x**3 + x + 3, [x, 0, 1])
improper integral sympy.integrate(sympy.exp(-x), (x, 0, sympy.oo))
quick simplify
slow simplify
simplify with assumption Assuming and Refine[]
equations and unknowns
mathematica sympy gap singular
solution to an equation Solve[x^3 + x + 3 == 0, x] solve(x**3 + x + 3, x)
solution to two equations Solve[x + y == 3 && x == 2y,
  {x, y}]
solve([x + y - 3, 3*x - 2*y], [x, y])
solve diophantine equation Solve[a^2 + b^2 == c^2 &&
a > 0 && a < 10 &&
b > 0 && b < 10 &&
c > 0 && c < 10,
{a, b, c}, Integers]
optimization
mathematica sympy gap singular
find minimal value Minimize[Sqrt[a^2 + x^2] + Sqrt[(b - x)^2 + c^2], x]
number theory
mathematica sympy gap singular
number tests IntegerQ[7]
PrimeQ[7]
rational test?
real test?
IsInt(7);
IsPrimeInt(7);
IsRat(7);
factorial 10! factorial(10)
binomial coefficient Binomial[10,3] binomial(10, 3)
greatest common divisor GCD[14, 21] gcd(14, 21)
prime factors returns {{2, 2}, {3, 1}, {7, 1}}
FactorInteger[84]
factorint(84)
Euler totient EulerPhi[256] Phi(256);
polynomials
mathematica sympy gap singular
declare
specify coefficient field
declare indeterminates
specify ordering
degree
operations
division and remainder
factor
resultant
symmetric polynomial
cyclotomic polynomial
hermite polynomial
bernoulli polynomial
interpolation polynomial
rational function
rings
mathematica sympy gap singular
over finite field
localization
tensor production
permutations
mathematica sympy gap singular
create permutation from disjoint cycles p = Cycles[{{1, 2}, {3, 4}}] import sympy.combinatorics as combinatorics

p = combinatorics.Permutation(0, 1)(2, 3)
p := (1, 2)(3, 4);
create permutation from list p = PermutationCycles[{2, 1, 4, 3}] import sympy.combinatorics as combinatorics

p = combinatorics.Permutation([1, 0, 3, 2])
p2 := PermList([2, 1, 4, 3]);
permutation which transforms one list to another FindPermutation[{a, b, c}, {b, c, a}] # must be positive integers:
p := MappingPermListList([6, 8, 4, 2], [2, 4, 6, 8])
action of permutation on list element p = Cycles[{{1, 2}, {3, 4}}]

PermutationReplace[1, p]
p(0) 1 ^ p;

# preimage of 1 under p:
1 / p;
action of permutation on list (* if list is too big, extra elements retain
their positions; if list is too small,
expression is left unevaluated. *)

Permute[{a, b, c, d}, p12n34]
a, b, c, d = sympy.symbols('a b c d')

p = combinatorics.Permutation(0, 1)(2, 3)
p([a, b, c, d])
compose permutations PermutationProduct[p13 = Cycles[{{1, 3}}]
Cycles[p12n34, p13]
p1 = combinatorics.Permutation(0, 1)(2, 3)
p2 = combinatorics.Permutation(0, 2)

p1 * p2
(1, 2)(3, 4) * (1, 3);
invert permutation InversePermutation[Cycles[1, 2, 3]] p = combinatorics.Permutation(0, 1, 2)

p ** -1
(1, 2, 3) ^ -1;
power of a permutation PermutationPower[Cycles[1, 2, 3, 4, 5], 3] p = combinatorics.Permutation(0, 1, 2, 3, 4)

p ** 3
(1, 2, 3, 4, 5) ^ 3;
order of a permutation PermutationOrder[Cycles[1, 2, 3, 4, 5]] combinatorics.Permutation(0, 1, 2, 3, 4).order()
support of a permutation PermutationSupport[Cycles[1, 3, 5}, {7, 8]] p = combinatorics.Permutation(0, 2, 4)(6, 7)

p.support()
MovedPoints((1, 3, 5)(7, 8));
number of inversions and parity
to inversion vector
from inversion vector
iterate over permutations
random permutation
groups
mathematica sympy gap singular
univariate charts
mathematica sympy gap singular
5039793334_f76edece33_m.jpgvertical bar chart BarChart[{7, 3, 8, 5, 5},
  ChartLegends->
    {"a","b","c","d","e"}]
5039776078_cc38a4ff5f_m.jpg
horizontal bar chart
BarChart[{7, 3, 8, 5, 5}, BarOrigin -> Left]
5037819710_d932767cd5_m.jpgpie chart PieChart[{7, 3, 8, 5, 5}]
5037399669_13c8e585e0_m.jpg
stem-and-leaf plot
Needs["StatisticalPlots`"]
nd = NormalDistribution[0, 1]
n100 = RandomVariate[nd, 100]
StemLeafPlot[20 * n100]
5037415497_4c6fbfcab2_m.jpghistogram nd = NormalDistribution[0, 1]
Histogram[RandomReal[nd, 100], 10]
5037525393_7ac86e81c3_m.jpgbox-and-whisker plot nd = NormalDistribution[0, 1]
n100 = RandomVariate[nd, 100]
BoxWhiskerChart[d]

ed = ExponentialDistribution[1]
e100 = RandomVariate[ed, 100]
u100 = RandomReal[1, 100]
d = {n100, e100, u100}
BoxWhiskerChart[d]
set chart title BoxWhiskerChart[data,
  PlotLabel -> "chart example"]
chart options PlotLabel -> "an example"

AxisLabel -> {"time", "distance"}
bivariate charts
mathematica sympy gap singular
5039126187_e340b3f4aa_m.jpg
stacked bar chart
d = {{7, 1}, {3, 2}, {8, 1},
  {5, 3}, {5, 1}}
BarChart[d, ChartLayout ->
  "Stacked"]
5267212089_a7749bbe3e_s.jpgscatter plot nd = NormalDistribution[0, 1]
rn = Function[RandomReal[nd]]
d = {rn[],rn[]} & /@ Range[1,50]
ListPlot[d]
5267975488_2216ae147e_s.jpglinear regression line d = Table[{i,
  2 i + RandomReal[{-5, 5}]},
  {i, 0, 20}]
model = LinearModelFit[d, x, x]
Show[ListPlot[d],
  Plot[model["BestFit"],
    {x, 0, 20}]]
5267434941_f8537c9d26_s.jpgpolygonal line plot f = Function[i, {i, rn[]}]
d = f /@ Range[1, 20]
ListLinePlot[d]
5268071368_75c3aee42e_t.jpgarea chart d = {{7, 1, 3, 2, 8},
  {1, 5, 3, 5, 1}}
sd = {d[[1]], d[[1]] + d[[2]]}
ListLinePlot[sd, Filling ->
  {1 -> {Axis, LightBlue},
   2 -> {{1}, LightRed}}]
5268229340_0b96b5e223_s.jpgcubic spline d = Table[{i, RandomReal[nd]},
  {i, 0, 20}]
f = Interpolation[d,
  InterpolationOrder -> 3]
Show[ListPlot[d],
  Plot[f[x], {x, 0, 20}]]
5268208606_b745646ea6_s.jpgfunction plot Plot[Sin[x], {x, -4, 4}]
5267567389_27a19429e4_s.jpgquantile-quantile plot nd = NormalDistribution[0, 1]
d1 = RandomReal[1, 50]
d2 = RandomReal[nd, 50]
QuantilePlot[d1, d2]
axis label d = Table[{i, i^2}, {i, 1, 20}]
ListLinePlot[d,
  AxesLabel -> {x, x^2}]
logarithmic y-axis LogPlot[{x^2, x^3, x^4, x^5},
  {x, 0, 20}]
trivariate charts
mathematica sympy gap singular
3d scatter plot nd = NormalDistribution[0,1]
d = RandomReal[nd, {50, 3}]
ListPointPlot3D[d]
5268191292_a75a367c39_s.jpgadditional data set nd = NormalDistribution[0, 1]
x1 = RandomReal[nd, 20]
x2 = RandomReal[nd, 20]
ListLinePlot[{x1, x2}]
bubble chart nd = NormalDistribution[0,1]
d = RandomReal[nd, {50, 3}]
BubbleChart[d]
surface plot Plot3D[Sinc[Sqrt[x^2 + y^2]],
  {x, -25, 25},
  {y, -25, 25}]
_______________________________________________________ _______________________________________________________ _______________________________________________________ _______________________________________________________

version used

The version of software used to check the examples in the reference sheet.

show version

How to determine the version of an installation.

implicit prologue

Code assumed to have been executed by the examples in the sheet.

sympy:

Grammar and Invocation

interpreter

How to execute a script.

repl

How to launch a command line read-eval-print loop for the language.

mathematica:

The full path to MathKernel on Mac OS X:

/Applications/Mathematica.app/Contents/MacOS/MathKernel

block delimiters

How blocks are delimited.

statement separator

How statements are separated.

end-of-line comment

Character used to start a comment that goes to the end of the line.

multiple line comment

Variables and Expressions

assignment

How to perform assignment.

In all three languages an assignment is an expression that evaluates to the right side of the expression. Assignments can be chained to assign the same value to multiple variables.

mathematica:

The Set function behaves identically to assignment and can be nested:

Set[a, Set[b, 3]]

delayed assignment

How to assign an expression to a variable name. The expression is re-evaluated each time the variable is used.

mathematica:

GNU make also supports assignment and delayed assignment, but = is used for delayed assignment and := is used for immediate assignment. This is the opposite of how Mathematica uses the symbols.

The POSIX standard for make only has = for delayed assignment.

parallel assignment

How to assign values in parallel.

Parallel assignment can be used to swap the values held in two variables.

compound assignment

The compound assignment operators.

increment and decrement

null

null test

How to test if a value is null.

undefined variable access

remove variable binding

How to remove a variable. Subsequent references to the variable will be treated as if the variable were undefined.

conditional expression

A conditional expression.

Arithmetic and Logic

true and false

The boolean literals.

falsehoods

Values which evaluate to false in a conditional test.

sympy:

Note that the logical operators Not, And and Or do not treat empty collections or None as false. This is different from the Python logical operators not, and, and or.

logical operators

The Boolean operators.

sympy:

In Python, &, |, and & are bit operators. SymPy has defined __and__, __or__, and __invert__ methods to make them Boolean operators for symbols, however.

relational operators

The relational operators.

sympy:

The full SymPy names for the relational operators are:

sympy.Equality             # ==
sympy.Unequality           # !=
sympy.GreaterThan          # >=
sympy.LessThan             # <=
sympy.StrictGreaterThan    # >
sympy.StrictLessThan       # <

The SymPy functions are attatched to the relational operators ==, !=, for symbols … using the methods __eq__, __ne__, __ge__, __le__, __gt__, __lt__. The behavior they provide is similar to the default Python behavior, but when one of the arguments is a SymPy expression, a simplification will be attempted before the comparison is made.

arithmetic operators

The arithmetic operators.

integer division

How to compute the quotient of two integers.

integer division by zero

The result of dividing an integer by zero.

float division

How to perform float division, even if the arguments are integers.

float division by zero

The result of dividing a float by zero.

power

How to compute exponentiation.

Note that zero to a negative power is equivalent to division by zero, and negative numbers to a fractional power may have multiple complex solutions.

sqrt

The square root function.

For positive arguments the positive square root is returned.

sqrt -1

How the square root function handles negative arguments.

mathematica:

An uppercase I is used to enter the imaginary unit, but Mathematica displays it as a lowercase i.

transcendental functions

The standard transcendental functions such as one might find on a scientific calculator.

The functions are the exponential (not to be confused with exponentiation), natural logarithm, sine, cosine, tangent, arcsine, arccosine, arctangent, and the two argument arctangent.

transcendental constants

The transcendental constants pi and e.

The transcendental functions can used to computed to compute the transcendental constants:

pi = acos(-1)
pi = 4 * atan(1)
e = exp(1)

float truncation

Ways to convert a float to a nearby integer.

absolute value

How to get the absolute value and signum of a number.

integer overflow

What happens when the value of an integer expression cannot be stored in an integer.

The languages in this sheet all support arbitrary length integers so the situation does not happen.

float overflow

What happens when the value of a floating point expression cannot be stored in a float.

rational construction

How to construct a rational number.

rational decomposition

How to extract the numerator and denominator from a rational number.

complex construction

How to construct a complex number.

complex decomposition

How to extract the real and imaginary part from a complex number; how to extract the argument and modulus; how to get the complex conjugate.

random number

How to generate a random integer or a random float.

random seed

How to set or get the random seed.

mathematica:

The seed is not set to the same value at start up.

bit operators

binary, octal, and hex literals

Binary, octal, and hex integer literals.

mathematica:

The notation works for any base from 2 to 36.

Strings

string literals

newline in literal

character access

chr and ord

length

concatenate

index of substring

extract substring

split

convert from string, to string

How to convert strings to numbers and vice versa.

join

trim

case manipulation

sprintf

Arrays

literal

The notation for an array literal.

size

The number of elements in the array.

lookup

How to access an array element by its index.

update

How to change the value stored at an array index.

out-of-bounds behavior

What happens when an attempt is made to access an element at an out-of-bounds index.

element index

How to get the index of an element in an array.

slice

How to extract a subset of the elements. The indices for the elements must be contiguous.

array of integers as index

manipulate back

manipulate front

head

tail

cons

concatenate

replicate

copy

How to copy an array. Updating the copy will not alter the original.

iterate

reverse

sort

dedupe

membership

How to test whether a value is an element of a list.

intersection

How to to find the intersection of two lists.

union

How to find the union of two lists.

relative complement, symmetric difference

How to find all elements in one list which are not in another; how to find all elements which are in one of two lists but not both.

map

filter

reduce

universal and existential tests

min and max element

shuffle and sample

How to shuffle an array. How to extract a random sample from an array without replacement.

zip

How to interleave two arrays.

Arithmetic Sequences

Dictionaries

record literal

record member access

Functions

definition

invocation

function value

Execution Control

if

How to write a branch statement.

mathematica:

The 3rd argument (the else clause) of an If expression is optional.

while

How to write a conditional loop.

mathematica:

Do can be used for a finite unconditional loop:

Do[Print[foo], {10}]

for

How to write a C-style for statement.

break/continue

How to break out of a loop. How to jump to the next iteration of a loop.

raise exception

How to raise an exception.

handle exception

How to handle an exception.

finally block

How to write code that executes even if an exception is raised.

Files

Libraries and Namespaces

Reflection

function documentation

How to get the documentation for a function.

Symbolic Expressions

Equations and Unknowns

Optimization

Number Theory

Permutations

Groups

Vectors

vector literal

The notation for a vector literal.

vector coordinate

How to get one of the coordinates of a vector.

vector dimension

How to get the number of coordinates of a vector.

element-wise arithmetic operators

How to perform an element-wise arithmetic operation on vectors.

vector length mismatch

What happens when an element-wise arithmetic operation is performed on vectors of different dimension.

scalar multiplication

How to multiply a scalar with a vector.

dot product

How to compute the dot product of two vectors.

cross product

How to compute the cross product of two three-dimensional vectors.

norms

How to compute the norm of a vector.

Matrices

literal or constructor

Literal syntax or constructor for creating a matrix.

mathematica:

Matrices are represented as lists of lists. No error is generated if one of the rows contains too many or two few elements. The MatrixQ predicate can be used to test whether a list of lists is matrix: i.e. all of the sublists contain numbers and are of the same length.

Matrices are displayed by Mathematica using list notation. To see a matrix as it would be displayed in mathematical notation, use the MatrixForm function.

dimensions

How to get the dimensions of a matrix.

element access

How to access an element of a matrix. All languages described here follow the convention from mathematics of specifying the row index before the column index.

row access

How to access a row.

column access

How to access a column.

submatrix access

How to access a submatrix.

scalar multiplication

How to multiply a matrix by a scalar.

element-wise operators

Operators which act on two identically sized matrices element by element. Note that element-wise multiplication of two matrices is used less frequently in mathematics than matrix multiplication.

multiplication

How to multiply matrices. Matrix multiplication should not be confused with element-wise multiplication of matrices. Matrix multiplication in non-commutative and only requires that the number of columns of the matrix on the left match the number of rows of the matrix. Element-wise multiplication, by contrast, is commutative and requires that the dimensions of the two matrices be equal.

kronecker product

The Kronecker product is a non-commutative operation defined on any two matrices. If A is m x n and B is p x q, then the Kronecker product is a matrix with dimensions mp x nq.

comparison

How to test two matrices for equality.

norms

How to compute the 1-norm, the 2-norm, the infinity norm, and the frobenius norm.

Distributions

univariate-charts Univariate Charts

A univariate chart can be used to display a list or array of numerical values. Univariate data can be displayed in a table with a single column or two columns if each numerical value is given a name. A multivariate chart, by contrast, is used to display a list or array of tuples of numerical values.

In order for a list of numerical values to be meaningfully displayed in a univariate chart, it must be meaningful to perform comparisons (<, >, =) on the values. Hence the values should have the same unit of measurement.

vertical bar chart

A chart which represents values with rectangular bars which line up on the bottom. It is a deceptive practice for the bottom not to represent zero, even if a y-axis with labelled tick marks or grid lines is provided. A cut in the vertical axis and one of the bars may be desirable if the cut value is a large outlier. Putting such a cut all of the bars near the bottom is a deceptive practice similar not taking to the base of the bars to be zero, however.

Another bad practice is the 3D bar chart. In such a chart heights are represented by the height of what appear to be three dimensional blocks. Such charts impress an undiscriminating audience but make it more difficult to make a visual comparison of the charted quantities.

mathematica

horizontal bar chart

A bar chart in which zero is the y-axis and the bars extend to the right.

pie chart

A bar chart displays values using the areas of circular sectors or equivalently, the lengths of the arcs of those sectors. A pie chart implies that the values are percentages of a whole. The viewer is likely to make an assumption about what the whole circle represents. Thus, using a pie chart to show the revenue of some companies in a line of business could be regarded as deceptive if there are other companies in the same line of business which are left out. The viewer may mistakenly assume the whole circle represents the total market.

If two values are close in value, people cannot determine visually which of the corresponding sectors in a pie chart is larger without the aid of a protractor. For this reason many consider bar charts superior to pie charts.

Many software packages make 3D versions of pie charts which communicate no additional information and in fact make it harder to interpret the data.

stem-and-leaf plot

histogram

box-and-whisker plot

set chart title

Bivariate Charts

stacked bar chart

Trivariate Charts

Mathematica

Mathematica Documentation Center
WolframAlpha

SymPy

Welcome to SymPy’s documentation!

GAP

GAP - Reference Manual

Singular

Singular Manual

issue tracker | content of this page licensed under creative commons attribution-sharealike 3.0