a side-by-side reference sheet
arithmetic and logic | random numbers | strings | arrays | other containers | functions | execution control
environment and i/o | libraries and modules | reflection
algebra | calculus | number theory | vectors | matrices | distributions | univariate charts | bivariate charts | trivariate charts
contact
maxima | pari/gp | mathematica | sage | |
---|---|---|---|---|
version used | 5.21 | 2.3 | 8.0 | 4.5 |
get version | $ maxima --version | $ gp --version | select About Mathematica in Mathematica menu | $ sage --version |
command line repl | $ maxima | $ gp | $ math | $ sage |
interpreter | $ gp -q foo.gp | |||
list function documentation | ?? | ? | ||
get function documentation | ? tan describe(tan) |
? tan | ?Tan Information[Tan] |
tan? |
grep documentation | ?? tan | |||
statement separator | ; | newline or ; | ; or sometimes newline | ; or sometimes newline |
block delimiters | { } | none | offside rule | |
assignment | a: 3 | a = 3 | a = 3 Set[a, 3] |
a = 3 |
parallel assignment | [a,b]: [3,4] [a: 3, b: 4] |
none | {a, b} = {3, 4} Set[{a,b}, {3,4}] |
a, b = 3, 4 |
compound assignment operators: arithmetic, string, logical | += -= *= /= %= | += -= *= /= corresponding functions: AddTo SubtractFrom TimeBy DivideBy |
+= -= *= /= //= %= **= += *= &= |= ^= |
|
increment, decrement | return value after increment or decrement: x++ x-- |
++x --x PreIncrement[x] PreDecrement[x] x++ x-- Increment[x] Decrement[x] |
none | |
to-end-of-line comment | 1 + 1 \\ addition | none | 1 + 1 # addition | |
delimited comment | 1 + /* addition */ 1 | 1 + /* addition */ 1 | 1 + (* addition *) 1 | |
null | Null | None | ||
null test | a == None a is None |
|||
undefined variable access | treated as an unknown number | treated as an unknown number | raises NameError | |
undefine a variable | kill(x) | Clear[x] | ||
arithmetic and logic | ||||
maxima | pari/gp | mathematica | sage | |
true and false | true false | 1 0 | True False | True False |
falsehoods | false | 0 | False | False None 0 0.0 '' [] {} |
logical operators | is(not true or ( true and false)) | ! 1 || ( 1 && 0) | ! True || ( True && False) Or[Not[True], And[True, False]] |
not True or ( True and False) |
conditional expression | if is(x>0) then x else -x | if(x > 0, x, -x) | If[x > 0, x, -x] | x if x > 0 else -x |
convert from string, to string | 7 + parse_string("12") 73.9 + parse_string(".037") |
7 + ToExpression["12"] 73.9 + ToExpression[".037"] "value: " <> ToString[8] |
7 + int('12') 73.9 + float('.037') 'value: ' + str(8) |
|
comparison operators | = # > < >= <= | == != > < >= <= | == != > < >= <= corresponding functions: Equal Unequal Greater Less GreaterEqual LessEqual |
== != > < >= <= |
arithmetic operators | + - * / quotient mod ^ quotient and mod are functions, not binary infix operators |
+ - * / none % ^ | + - * / 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 Power |
+ - * / // % ** |
integer division | quotient(a, b) | divrem(a, b)[1] | Quotient[a,b] | a // b |
float division | float(a) / b | exact division: a / b |
exact division: a / b |
float(a) / b |
arithmetic constants | Pi | Pi | ||
arithmetic functions | sqrt exp log sin cos tan asin acos atan atan2 | sqrt exp log sin cos tan asin acos atan none | Sqrt Exp Log Sin Cos Tan ArcSin ArcCos ArcTan ArcTan ArcTan accepts 1 or 2 arguments |
sqrt exp log sin cos tan asin acos atan atan2 |
arithmetic truncation | truncate round ceiling floor | truncate round ceil floor | IntegerPart Round Ceiling Floor | int round ceil floor |
arithmetic decomposition | abs sign ratnumer ratdenom realpart imagpart | abs sign numerator denominator real imag | Abs Sign Numerator Denominator Re Im Arg | abs sign numerator denominator real imag arg |
closure of integers under division | rationals | rationals | rationals | rationals |
integer overflow | none, has arbitrary length integer type | none, has arbitrary length integer type | none, has arbitrary length integer type | none, has arbitrary length integer type |
float overflow | none | Infnity | ||
float limits | none | none | ||
1/0 | Error: Division by 0 | error: division by zero | ComplexInfinity | ZeroDivisionError exception |
sqrt(-2) | $\sqrt{2}$ %i | 1.414213*I | I Sqrt[2] | n(sqrt(-2),digits=5) -9.0475e-7 + 1.4142*I |
complex numbers | %i 2 * %i 3 * %i |
I 2*I 3*I |
I 2I 3I |
I 2*I 3*I |
random numbers | ||||
maxima | pari/gp | mathematica | sage | |
setting and getting seed | set_random_state(make_random_state(17)); ?? |
setrand(17) getrand() |
SeedRandom[17] ?? |
|
result of not seeding | uses fixed seed | uses fixed seed | seeded at start up using current time? | |
integer | random(100) | random(100) | RandomInteger[{0, 99}] | randint(0,99) |
uniform | random(1.0) | RandomReal[] | random() | |
normal | load(distrib); random_normal(0,1); |
nd = NormalDistribution[0,1] RandomVariate[nd] |
gauss(0,1) | |
exponential | load(distrib); random_exp(1); |
ed = ExponentialDistribution[1] RandomVariate[ed] |
expovariate(1) | |
poisson | load(distrib); random_poisson(1); |
pd = PoissonDistribution[1] RandomVariate[pd] |
||
sample w/o replacement | x = {3,7,5,12,19,8,4} RandomSample[x, 3] |
x = [3,7,5,12,19,8,4] sample(x,3) |
||
strings | ||||
maxima | pari/gp | mathematica | sage | |
string literals | "don\'t say \"no\"" | "don't say \"no\"" | "don't say \"no\"" | "don't say \"no\"" 'don\'t say "no"' |
newline in literal | no; use \n escape | yes | no; use \n or triple-quoted string literal | |
string literal escapes | \n \t \" \\ | \\ \" \b \f \n \r \t \ooo | \newline \\ \' \" \a \b \f \n \r \t \v \ooo \xhh | |
character access | charat("hello", 1) | Characters["hello"][[1]] | "hello"[0] | |
chr and ord | FromCharacterCode[{65}] ToCharacterCode["A"][[1]] |
chr(65) ord("A") |
||
length | slength("hello") | length("hello") | StringLength["hello"] | len("hello") |
concatenate | Str("one", "two", "three") | "one " <> "two " <> "three" | "one " + "two " + "three" | |
index of substring | ssearch("el", "hello") counts from one, returns false if not found |
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. |
counts from zero, raises ValueError if not found 'hello'.index('el') |
|
extract substring | substring("hello", 1, 5) | StringTake["hello", {1, 4}] | 'hello'[0:4] | |
split | split("foo,bar,baz",",") | StringSplit["foo,bar,baz", ","] | 'foo,bar,baz'.split(',') | |
join | simplode(["foo","bar","baz"],",") | StringJoin[Riffle[{"foo", "bar", "baz"}, ","]] | ','.join(['foo','bar','baz']) | |
trim | strim(" ", " foo ") striml(" ", " foo") strimr(" ", "foo ") |
StringTrim[" foo "] | " foo ".strip() " foo".lstrip() "foo ".rstrip() |
|
case manipulation | supcase("foo") sdowncase("FOO")sdowncase("FOO") |
ToUpperCase["foo"] ToLowerCase["FOO"] |
"foo".upper() "FOO".lower() "foo".capitalize() |
|
sprintf | none | "%s: %.3f %d" % ( "foo", 2.2, 7) | ||
regex test | re = RegularExpression["[a-z]+"] sc = StringCases["hello", re] Length[sc] > 0 |
import re re.match('^[a-z]+$', 'hello') re.match('^\S+$', 'hello') |
||
regex substitution | s = "foo bar bar" re = RegularExpression["bar"] StringReplace[s, re -> "baz", 1] StringReplace[s, re -> "baz"] |
import re s = 'foo bar bar' re.compile('bar').sub('baz', s, 1) re.compile('bar').sub('baz', s) |
||
arrays | ||||
maxima | pari/gp | mathematica | sage | |
array literal | [1,2,3] | [1,2,3] | {1, 2, 3} List[1,2,3] |
[1,2,3] |
must arrays be homogeneous | no | no | no | no |
array element access | indices start at one: [1,2,3][1] |
{1, 2, 3}[[1]] | indices start at zero: [1,2,3][0] |
|
index of array element | First[First[Position[{7, 8, 9}, 9]]] | |||
array slice | {1, 2, 3}[[1 ;; 2]] | [1,2,3][0:2] | ||
integer array as index | {1, 2, 3}[[{1, 3, 3}]] | v = [1,2,3] [v[i] for i in [0,2,2]] |
||
logical array as index | none | |||
array length | length([1,2,3]) | length([1,2,3]) | Length[{1, 2, 3}] | len([1,2,3]) |
manipulate back of array | a = {6,7,8} AppendTo[a, 9] elem = a[[Length[a]]] a = Delete[a, Length[a]] elem |
a = [6,7,8] a.append(9) a.pop() |
||
manipulate front of array | a = {6,7,8} PrependTo[a, 5] elem = a[[1]] a = Delete[a, 1] elem |
a = [6,7,8] a.insert(0,5) a.pop(0) |
||
array concatenation | Join[{1, 2, 3}, {4, 5, 6}] | [1,2,3] + [4,5,6] a = [1,2,3] a.concat([4,5,6]) |
||
sort | Sort[{3, 1, 4, 2}] | sorted([3,1,4,2]) | ||
map | Function[x, x x] /@ {1, 2, 3} Map[Function[x, x x], {1, 2, 3}] |
map(lambda x: x*x, [1,2,3]) | ||
filter | Select[{1, 2, 3}, # > 2 &] | filter(lambda x: x > 2,[1,2,3]) | ||
reduce | Fold[Plus, 0, {1, 2, 3}] | reduce(lambda x,y:x+y,[1,2,3],0) | ||
other containers | ||||
maxima | pari/gp | mathematica | sage | |
tuple literal | same as array: t = {1.7, "hello", {1,2,3}} |
t = (1.7,"hello",[1,2,3]) | ||
tuple element access | t[[1]] | t[0] | ||
tuple length | Length[t] | len(t) | ||
record literal | r = { n -> 10, avg -> 3.7, sd -> 0.4} | r = {'n':10,'avg':3.7,'sd':0.4} | ||
record member access | n /. r | r['n'] | ||
range | Range[1, 100] | range(1,101) | ||
arithmetic sequence of integers with difference 10 | Range[1, 100, 10] | range(0,101,10) | ||
arithmetic sequence of floats with difference 0.1 | Range[1, 100, .1] | [0.1 * x for x in range(0,101)] | ||
functions | ||||
maxima | pari/gp | mathematica | sage | |
definition | add(x, y) = x + y | add[a_, b_] := a + b | def add(a, b): return a+b |
|
invocation | add(3, 7) | add[3, 7] | add(3, 7) | |
return value | return argument or None | |||
function value | add | |||
anonymous function | Function[{a,b},a+b] (#1+#2) & |
body must be single expression: lambda a,b: a+b |
||
missing argument | raises TypeError | |||
extra argument | raises TypeError | |||
default argument | def mylog(x, base=10): return log(x) / log(base) |
|||
variable number of arguments | def add(*a): if len(a) == 0: return 0 return a[0] + add(*a[1:]) |
|||
execution control | ||||
maxima | pari/gp | mathematica | sage | |
if | if (is(x > 0)) then print("positive") elseif (is(x < 0)) then print("negative") else print("zero") | if(x > 0, \ print("positive"), \ if(x < 0, \ print("negative"), \ print("zero"))) |
If[x > 0, Print["positive"], If[x < 0, Print["negative"], Print["zero"]]] |
if x > 0: print('positive') elif x < 0: print('negative') else: print('zero') |
while | i = 0 while(i < 10, print(i); i++) |
i = 0 While[i < 10, Print[i]; i++] |
i = 0 while i < 10: i += 1 print(i) |
|
for | for(i=0, 9, print(i)) | For[i = 0, i < 10, i++, Print[i]] | for i in range(1,11): print(i) |
|
break/continue | break continue | Break[] Continue[] | break continue | |
raise exception | error("failed") | Throw["failed"] | raise Exception('failed') | |
handle exception | Print[Catch[Throw["failed"]]] | try: raise Exception('failed') except e: print(e) |
||
finally block | none | try: if random() > 0.5: error('failed') finally: print('cleanup') |
||
environment and i/o | ||||
maxima | pari/gp | mathematica | sage | |
write to stdout | print("hello") | print("hello") | Print["hello"] | print('hello') |
read entire file into string or array | s = Import["/etc/hosts"] a = StringSplit[s, "\n"] |
|||
redirect to file | ||||
libraries and modules | ||||
maxima | pari/gp | mathematica | sage | |
load | ||||
reflection | ||||
maxima | pari/gp | mathematica | sage | |
query data type | type(x) | type(x) | ||
list variables in scope | ? 0 | |||
undefine variable | kill(v) | Remove[v] | ||
algebra | ||||
maxima | pari/gp | mathematica | sage | |
solution to an equation | solve(x^3+x+3,x) | Solve[x^3 + x + 3 == 0, x] | solve(x^3+x+3,x) | |
solution to two equations | solve([x+y=3, x=2*y], [x, y]) | Solve[x + y == 3 && x == 2y, {x, y}] |
||
numerical approximation | float(exp(1)) | 1/7 + 0. | N[Exp[1]] N[Exp[1], 10] |
n(exp(1)) n(exp(1), digits=10) |
expand polynomial | expand((1+x)^5) | Expand[(1 + x)^5] | expand((1+x)^5) | |
factor polynomial | factor(3 + 10*x + 9*x^2 + 2*x^3) | Factor[3 + 10 x + 9 x^2 + 2 x^3] | factor(3 + 10*x + 9*x^2 + 2*x^3) | |
add fractions | ratsimp(a/b + c/d) | Together[a/b + c/d] | ||
decompose fraction | Apart[(b c + a d)/(b d)] | |||
calculus | ||||
maxima | pari/gp | mathematica | sage | |
differentation | diff(x^3+x+3,x) | P = x^3 + x + 3 P' sin(x)' |
D[x^3 + x + 3, x] | x = var('x') diff(x^3+x+3,x) |
integration | Integrate[x^3 + x + 3, x] Integrate[x^3 + x + 3, {x, 0, 1}] |
x = var('x') integral(x^3+x+3,x) integral(x^3+x+3,x,0,1) |
||
find minimal value | Minimize[Sqrt[a^2 + x^2] + Sqrt[(b - x)^2 + c^2], x] | |||
number theory | ||||
maxima | pari/gp | mathematica | sage | |
number tests | integerp(7) primep(7) |
IntegerQ[7] PrimeQ[7] rational test? real test? |
||
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] |
|||
factorial | 10! | 10! | 10! | factorial(10) |
binomial coefficient | binomial(10,3) | Binomial[10,3] | binomial(10,3) | |
greatest common divisor | gcd(14, 21) | gcd(14, 21) | GCD[14, 21] | gcd(14, 21) |
prime factors | factor(84) | returns [2,2; 3,1; 7,1] factor(84) |
returns {{2, 2}, {3, 1}, {7, 1}} FactorInteger[84] |
returns 2^2 * 3 * 7 factor(84) |
Euler totient | totient(256) | EulerPhi[256] | euler_phi(256) | |
vectors | ||||
maxima | pari/gp | mathematica | sage | |
vector literal | same as array | same as array | vector([1,2,3]) | |
element-wise arithmetic operators | + - | + - * / adjacent lists are multiplied element-wise |
+ - ?? ?? | |
result of vector length mismatch | error | error | raises TypeError | |
scalar multiplication | 3 * [1,2,3] [1,2,3] * 3 |
3 {1,2,3} {1,2,3} 3 * may also be used |
3 * vector([1,2,3]) vector([1,2,3]) * 3 |
|
dot product | {1, 1, 1} . {2, 2, 2} Dot[{1, 1, 1}, {2, 2, 2}] |
vector([1,1,1]) * vector([2,2,2]) | ||
cross product | Cross[{1, 0, 0}, {0, 1, 0}] | |||
norms | Norm[{1, 2, 3}, 1] Norm[{1, 2, 3}] Norm[{1, 2, 3}, Infinity] |
|||
matrices | ||||
maxima | pari/gp | mathematica | sage | |
literal or constructor | A = [1, 2; 3, 4] B = [4, 3; 2, 1] |
A = {{1, 2}, {3, 4}} B = {{4, 3}, {2, 1}} |
A = matrix([[1,2],[3,4]]) B = matrix([[4,3],[2,1]]) |
|
zero, identity, ones, diagonal matrix | ConstantArray[0, {3, 3}] IdentityMatrix[3] ConstantArray[1, {3, 3}] DiagonalMatrix[{1, 2, 3}] |
matrix(3,3,0) matrix(3,3,1) ?? ?? |
||
dimensions | Length[A] Length[A[[1]]] |
len(A.rows()) len(A.columns()) |
||
element access | A[1, 1] | A[[1, 1]] | A[0,0] | |
row access | A[[1]] | A[0,:] | ||
column access | A[[1]] | A[:,0] | ||
submatrix access | # [[1]] & /@ A | c = [[1,2,3],[4,5,6],[7,8,9]] C = matrix(c) C[0:2,0:2] |
||
scalar multiplication | 3 A A 3 * can also be used |
3 * A A * 3 |
||
element-wise operators | + - * / adjacent matrices are multiplied element-wise |
+ - none none | ||
multiplication | A . B | A * B | ||
kronecker product | KroneckerProduct[A, B] | from numpy import kron kron(A,B) |
||
comparison | A == B A != B |
A == B A != B |
||
norms | Norm[A, 1] Norm[A] Norm[A, Infinity] Norm[A, "Frobenius"] |
A.norm(1) A.norm(2) A.norm(Infinity) A.norm('frob') |
||
transpose | Transpose[A] | A.transpose() | ||
conjugate transpose | A = {{I, 2 I}, {3 I, 4 I}} ConjugateTranspose[A] |
A = matrix([[1*I,2*I],[3*I,4*I]]) A.conjugate().transpose() |
||
inverse | Inverse[A] | A.inverse() | ||
determinant | matdet(A) | Det[A] | A.determinant() | |
trace | trace(A) | Tr[A] | A.trace() | |
eigenvalues | Eigenvalues[A] | A.eigenvalues() | ||
eigenvectors | Eigenvectors[A] | A.eigenvectors_right() | ||
system of equations | Solve[A. {x, y} == { 2, 3}, {x, y}] | A.solve_right(vector([2,3])) | ||
distributions | ||||
maxima | pari/gp | mathematica | sage | |
univariate charts | ||||
maxima | pari/gp | mathematica | sage | |
vertical bar chart | BarChart[{7, 3, 8, 5, 5}, ChartLegends-> {"a","b","c","d","e"}] |
bar_chart([7,3,8,5,5]) | ||
horizontal bar chart |
BarChart[{7, 3, 8, 5, 5}, BarOrigin -> Left] | |||
pie chart | PieChart[{7, 3, 8, 5, 5}] | |||
stem-and-leaf plot |
Needs["StatisticalPlots`"] nd = NormalDistribution[0, 1] n100 = RandomVariate[nd, 100] StemLeafPlot[20 * n100] |
|||
histogram | nd = NormalDistribution[0, 1] Histogram[RandomReal[nd, 100], 10] |
|||
box-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 | ||||
maxima | pari/gp | mathematica | sage | |
stacked bar chart |
d = {{7, 1}, {3, 2}, {8, 1}, {5, 3}, {5, 1}} BarChart[d, ChartLayout -> "Stacked"] |
|||
scatter plot | nd = NormalDistribution[0, 1] rn = Function[RandomReal[nd]] d = {rn[],rn[]} & /@ Range[1,50] ListPlot[d] |
d = [(gauss(0,1),gauss(0,1)) for i in range(0,50)] scatter_plot(d) |
||
linear 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}]] |
|||
polygonal line plot | f = Function[i, {i, rn[]}] d = f /@ Range[1, 20] ListLinePlot[d] |
|||
area 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}}] |
|||
cubic spline | d = Table[{i, RandomReal[nd]}, {i, 0, 20}] f = Interpolation[d, InterpolationOrder -> 3] Show[ListPlot[d], Plot[f[x], {x, 0, 20}]] |
|||
function plot | plot2d(sin(x),[x,-4,4]); | ploth(x=-4, 4, sin(x)) | Plot[Sin[x], {x, -4, 4}] | plot(sin(x), (x,-4,4)) |
quantile-quantile plot | nd = NormalDistribution[0, 1] d1 = RandomReal[1, 50] d2 = RandomReal[nd, 50] QuantilePlot[d1, d2] |
|||
axis label | plot2d(sin(x), [x,-4,4], [ylabel,"sine function"]); | 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 | ||||
maxima | pari/gp | mathematica | sage | |
3d scatter plot | nd = NormalDistribution[0,1] d = RandomReal[nd, {50, 3}] ListPointPlot3D[d] |
|||
additional 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 | sinc(x) := sin(%pi*x)/(%pi*x);sinc(x) := sin(%pi*x)/(%pi*x); plot3d(sinc(sqrt(x^2+y^2)),[x,-25,25],[y,-25,25]); |
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.
get version
How to determine the version of an installation.
command line repl
How to launch a command line read-eval-print loop for the language.
mathematica:
To create a command line REPL called math on Mac OS X, do the following:
cd /usr/local/bin
sudo ln -s /Applications/Mathematica\ Home\ Edition.app/Contents/MacOS/MathKernel math
sage:
Within the REPL, type notebook() to launch a web server which implements a GUI at http://localhost:8000.
interpreter
How to execute a script.
pari/gp
The shebang style notation doesn't work because GP doesn't recognize the hash tag # as the start of a comment.
The -q option suppresses the GP startup message.
After the script finishes it will drop the user into the REPL unless there is a quit statement in the script:
print("Hello, World!")
quit
documentation
How to get the documentation for a function.
statement separator
How statements are separated.
block delimiters
assignment
compound assignment operators
The compound assignment operators.
to-end-of-line comment
Character used to start a comment that goes to the end of the line.
null
null test
How to test if a value is null.
undefined variable access
Arithmetic and Logic
true and false
The boolean literals.
falsehoods
Values which evaluate to false in a conditional test.
logical operators
The boolean operators.
conditional expression
A conditional expression.
convert from string, to string
How to convert strings to numbers and vice versa.
comparison operators
The comparison operators.
arithmetic operators
The arithmetic operators.
sage:
^ is a synonym for **: both perform exponentiation.
integer division
How to compute the quotient of two integers.
float division
How to perform float division, even if the arguments are integers.
arithmetic functions
Some standard arithmetic functions.
sage:
In Python the arithmetic functions must be imported from the math module, but in Sage they are automatically available.
arithmetic truncation
Ways of converting a float to a nearby integer.
arithmetic decomposition
Ways of decomposing numbers into a simpler type of number.
Random Numbers
Strings
string literals
newline in literal
character access
chr and ord
length
concatenate
index of substring
extract substring
split
join
trim
case manipulation
sprintf
regex test
regex substitution
Arrays
array literal
mathematica:
The mathematica List data type provides indexed access and thus serves as an array data type.
must arrays be homogeneous
Can an array be created with elements of different type?
array data types
What data types are permitted in arrays.
array element access
index of array element
array length
array concatenation
sage:
Concatenation is only defined for arrays, not vectors. The vector type redefines the + operator to vector addition, and the vector type does not have a concat method.
map
filter
reduce
Other Containers
tuple literal
How to create a tuple, which we define as a fixed length, inhomogeneous list.
mathematica
Mathematica does not have a fixed length list, so the standard List data type is used for tuples as well.
tuple element access
How to access an element of a tuple.
tuple length
record literal
record member access
range
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.
Environment and I/O
Libraries and Modules
Reflection
Algebra
Calculus
Number Theory
Vectors
vector literal
sage:
If the list provided to the vector constructor is not homogeneous, a TypeError exception will be raised.
element-wise arithmetic operators
scalar multiplication
dot product
cross product
norms
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.
sage:
Matrices are created by passing a vector of row vectors to the matrix constructor.
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.
sage:
Element-wise multiplication or division can be achieved by converting the matrices to arrays:
from numpy import array
matrix(array(A) * array(B))
matrix(array(A) / array(B))
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.
sage:
A.norm() is the same as A.norm(2).
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
Maxima
Pari/GP
A Tutorial for Pari/GP (pdf)
Pari/GP Functions by Category
Mathematica
Mathematica Documentation Center
WolframAlpha
Sage
Sage Tutorial
Numpy and Scipy Documentation
ECL
Maxima Documentation
matplotlib Documentation
Sage is a suite of mathematical software which uses Python as its programming language. It is a free, open source alternative to Mathematica and Maple.
Sage is implemented with Python and pre-existing open source components. Some of these components are implemented in Python, others are implemented in C, C++, or Fortran and accessed via Cython, and others are implemented in Lisp or R and require an embedded interpreter.
The Sage distribution includes the Python libraries Numpy and Scipy. The functions in these libraries can be used from the Sage command-line or the Sage notebook if they are imported:
sage: import numpy
sage: numpy.zeros((3,3))
array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])
Sage uses Maxima for symbolic mathematics. Maxima is implemented in Common Lisp and Sage embeds an ECL interpreter. Both Common Lisp and Maxima can be invoked directly from the Sage command-line or the Sage notebook:
When performing symbolic mathematics, unknown variables must be declared as symbolic variables with var to avoid raising a NameError. The variable x is declared a symbolic variable by default.
var('y)
expand((1+y)^5)
sage: maxima(" integrate(x^2,x) ")
x^3/3
sage: lisp(" (+ 1 1) ")
2
Sage also embeds an R interpreter which can be invoked directly:
sage: r(" pnorm(3.0) ")
[1] 0.9986501
The sage function plot, which creates 2-D plots, uses matplotlib, a Python implementation of the MATLAB plot function. matplotlib can generate PNG, PostScript, or SVG output.
History
One of the earliest computer algebra systems was Macsyma, developed at MIT from 1968 to 1982. Macsyma was written in Maclisp and ran on the PDP-10. A version which uses Common Lisp called Maxima was started in 1982, and became open source in 1998.
By 1988 the commercial computer algebra systems Mathematica and Maple were available.