Here is some italic text. Even equations $\int_0^1 \frac{1}{1+x^2} dx$.
I can use Julia as a calculator:
3 + 4
7
3 * 4
12
3^4
81
sin(3)
0.1411200080598672
1 / (1 + sin(7))
0.6035051827052901
x = 17
17
y = sin(x)
-0.9613974918795568
α = 3.74 # Unicode variable names — type it by "\alpha<tab>"
3.74
α̂₂ = 3
3
A complex number $3 + 5i$:
z = 3 + 5im
3 + 5im
z^3
-198 + 10im
exp(z) # compute eᶻ
5.697507299833739 - 19.26050892528742im
sin(z)
10.472508533940392 - 73.46062169567367im
Online help:
?sin
search: sin sinh sind sinc sinpi sincos sincosd asin using isinf asinh asind
sin(x)
Compute sine of x
, where x
is in radians.
sin(A::AbstractMatrix)
Compute the matrix sine of a square matrix A
.
If A
is symmetric or Hermitian, its eigendecomposition (eigen
) is used to compute the sine. Otherwise, the sine is determined by calling exp
.
jldoctest
julia> sin(fill(1.0, (2,2)))
2×2 Array{Float64,2}:
0.454649 0.454649
0.454649 0.454649
?α̂₂
x = [1, 17, 32, 15] # elements separated by commas
4-element Array{Int64,1}: 1 17 32 15
Array{Int64,1}
is a 1-dimensional array (a "vector") of 64-bit integers (Int64
).
y = [15, 2, 6, -9]
4-element Array{Int64,1}: 15 2 6 -9
x + y
4-element Array{Int64,1}: 16 19 38 6
x * y # not allowed: vector * vector is not a linear-algebra operation
MethodError: no method matching *(::Array{Int64,1}, ::Array{Int64,1}) Closest candidates are: *(::Any, ::Any, !Matched::Any, !Matched::Any...) at operators.jl:538 *(!Matched::LinearAlgebra.Adjoint{var"#s826",var"#s8261"} where var"#s8261"<:(AbstractArray{T,1} where T) where var"#s826"<:Number, ::AbstractArray{var"#s825",1} where var"#s825"<:Number) at /Users/julia/buildbot/worker/package_macos64/build/usr/share/julia/stdlib/v1.5/LinearAlgebra/src/adjtrans.jl:283 *(!Matched::LinearAlgebra.Transpose{T,var"#s826"} where var"#s826"<:(AbstractArray{T,1} where T), ::AbstractArray{T,1}) where T<:Real at /Users/julia/buildbot/worker/package_macos64/build/usr/share/julia/stdlib/v1.5/LinearAlgebra/src/adjtrans.jl:284 ... Stacktrace: [1] top-level scope at In[14]:1 [2] include_string(::Function, ::Module, ::String, ::String) at ./loading.jl:1091 [3] execute_code(::String, ::String) at /Users/stevenj/.julia/dev/IJulia/src/execute_request.jl:27 [4] execute_request(::ZMQ.Socket, ::IJulia.Msg) at /Users/stevenj/.julia/dev/IJulia/src/execute_request.jl:86 [5] #invokelatest#1 at ./essentials.jl:710 [inlined] [6] invokelatest at ./essentials.jl:709 [inlined] [7] eventloop(::ZMQ.Socket) at /Users/stevenj/.julia/dev/IJulia/src/eventloop.jl:8 [8] (::IJulia.var"#15#18")() at ./task.jl:356
transpose(x)
1×4 LinearAlgebra.Transpose{Int64,Array{Int64,1}}: 1 17 32 15
transpose(x) * y # allowed = a dot product
106
x .* y # elementwise product
4-element Array{Int64,1}: 15 34 192 -135
float(y) .^ x
4-element Array{Float64,1}: 15.0 131072.0 7.958661109946401e24 -2.05891132094649e14
float(y)
4-element Array{Float64,1}: 15.0 2.0 6.0 -9.0
z = [3.7, 4.2, 6.1]
3-element Array{Float64,1}: 3.7 4.2 6.1
z .^ [0,1,2]
3-element Array{Float64,1}: 1.0 4.2 37.209999999999994
z .^ transpose([0,1,2]) # a Vandermonde matrix
3×3 Array{Float64,2}: 1.0 3.7 13.69 1.0 4.2 17.64 1.0 6.1 37.21
z .^ [0 1 2]
3×3 Array{Float64,2}: 1.0 3.7 13.69 1.0 4.2 17.64 1.0 6.1 37.21
[0 1 2] # another row vector
1×3 Array{Int64,2}: 0 1 2
@show x
x[2] # second element
x = [1, 17, 32, 15]
17
x[2:3] # elements 2 to 3 — "slicing"
2-element Array{Int64,1}: 17 32
x[2:4] # elements 2,3,4
3-element Array{Int64,1}: 17 32 15
2:4
2:4
0:4 # analogous to range(5) in Python
0:4
collect(0:4)
5-element Array{Int64,1}: 0 1 2 3 4
y .^ 3 # elementwise cube
4-element Array{Int64,1}: 3375 8 216 -729
sin.(y) # elementwise sin
4-element Array{Float64,1}: 0.6502878401571168 0.9092974268256817 -0.27941549819892586 -0.4121184852417566
rand(7) # 7 random numbers in [0,1)
7-element Array{Float64,1}: 0.9895925568529049 0.43720897273586745 0.18692127626397315 0.5248400288925346 0.7725784322036084 0.2755926598616645 0.046487055457531845
randn(7) # 7 normally-distributed random numbers (mean 0, std. dev. 1)
7-element Array{Float64,1}: -0.7766970200438933 0.8375893322814147 -1.0161992755239175 -1.4656970471375195 -0.2380323626857652 0.3324373560431813 -0.2545786106508578
collect(0:2:7) # 0 to 7 in steps of 2
4-element Array{Int64,1}: 0 2 4 6
collect(0:0.1:7) # 0 to 7 in steps of 0.1
71-element Array{Float64,1}: 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 1.1 1.2 ⋮ 5.9 6.0 6.1 6.2 6.3 6.4 6.5 6.6 6.7 6.8 6.9 7.0
r = range(0, 2π, length=50) # 50 numbers from 0 to 2π, equally spaced
0.0:0.1282282715750936:6.283185307179586
collect(r)
50-element Array{Float64,1}: 0.0 0.1282282715750936 0.2564565431501872 0.38468481472528077 0.5129130863003744 0.641141357875468 0.7693696294505615 0.8975979010256552 1.0258261726007487 1.1540544441758425 1.282282715750936 1.4105109873260295 1.538739258901123 ⋮ 4.872674319853557 5.00090259142865 5.129130863003744 5.257359134578837 5.385587406153931 5.513815677729025 5.642043949304118 5.770272220879212 5.898500492454305 6.026728764029399 6.154957035604492 6.283185307179586
r = range(0, 2π, length=10^8) # not computed explicitly
0.0:6.28318537001144e-8:6.283185307179586
collect(r[1:10])
10-element Array{Float64,1}: 0.0 6.28318537001144e-8 1.256637074002288e-7 1.884955611003432e-7 2.513274148004576e-7 3.14159268500572e-7 3.769911222006864e-7 4.398229759008008e-7 5.026548296009151e-7 5.654866833010296e-7
A = [1 3 7
4 7 2
0 1 1]
3×3 Array{Int64,2}: 1 3 7 4 7 2 0 1 1
Notice that the type is Array{Int64,2}
— the 2 here is for a 2d array, a "matrix"
b = [3, 2, 1] # a vector
3-element Array{Int64,1}: 3 2 1
A * b # matrix-vector product
3-element Array{Int64,1}: 16 28 3
inv(A)
3×3 Array{Float64,2}: 0.238095 0.190476 -2.04762 -0.190476 0.047619 1.2381 0.190476 -0.047619 -0.238095
Let's solve a linear system: $$ Ax = b $$ for $x = A^{-1} b$:
x = inv(A) * b
3-element Array{Float64,1}: -0.9523809523809521 0.761904761904762 0.23809523809523808
A * x
3-element Array{Float64,1}: 3.0000000000000004 2.0000000000000018 1.0
A * x - b # not zero due to roundoff errors — more about this in 18.330 or 18.335 in spring
3-element Array{Float64,1}: 4.440892098500626e-16 1.7763568394002505e-15 0.0
Alternatively:
x = A \ b # effectively equivalent to inv(A) * b, but faster and better
3-element Array{Float64,1}: -0.9523809523809528 0.7619047619047621 0.23809523809523808
A * x - b # slightly different (smaller in this case)
3-element Array{Float64,1}: 0.0 0.0 2.220446049250313e-16
sin.(A) # elementwise sine
3×3 Array{Float64,2}: 0.841471 0.14112 0.656987 -0.756802 0.656987 0.909297 0.0 0.841471 0.841471
sin(A) # is this meaningful????
3×3 Array{Float64,2}: -0.888487 -0.296349 6.91956 0.962251 0.264022 -3.59102 -0.581735 0.240563 0.565852
In 18.06 (or maybe 18.S096), you'll eventually learn that $\sin(A)$ is perfectly meaningful for a square matrix. It's defined by the Taylor series: $$ \sin(A) = A - \frac{A^3}{3!} + \frac{A^5}{5!} - \frac{A^7}{7!} + \cdots $$
function f(x)
return 3x^3 - 5x^2 + sin(x) - x
end
f (generic function with 1 method)
f(3)
34.141120008059865
f(A)
3×3 Array{Float64,2}: 344.112 669.704 418.92 688.962 1421.26 956.409 87.4183 172.241 125.566
f.(x) # applied elementwise
3-element Array{Float64,1}: -6.989077393122971 -1.6472437070737587 -0.24519753391390525
f.(A)
3×3 Array{Float64,2}: -2.15853 33.1411 777.657 107.243 777.657 2.9093 0.0 -2.15853 -2.15853
g(x) = 4x^3 - 5x^2 + 6x + 2 # one-line function definition
g (generic function with 1 method)
g.(A)
3×3 Array{Int64,2}: 7 83 1171 202 1171 26 2 7 7
Most linear-algebra routines are in the LinearAlgebra
standard library:
using LinearAlgebra # similar to "from LinearAlgebra import *" in Python
eigvals(A) # eigenvalues
3-element Array{Complex{Float64},1}: -0.07094370057923445 - 1.5139635518670342im -0.07094370057923445 + 1.5139635518670342im 9.141887401158474 + 0.0im
F = eigen(A) # eigenvectors and eigenvalues
Eigen{Complex{Float64},Complex{Float64},Array{Complex{Float64},2},Array{Complex{Float64},1}} values: 3-element Array{Complex{Float64},1}: -0.07094370057923445 - 1.5139635518670342im -0.07094370057923445 + 1.5139635518670342im 9.141887401158474 + 0.0im vectors: 3×3 Array{Complex{Float64},2}: 0.834342-0.0im 0.834342+0.0im 0.42575+0.0im -0.454852+0.168903im -0.454852-0.168903im 0.898092+0.0im 0.0672889-0.252839im 0.0672889+0.252839im 0.110305+0.0im
F.values # the eigenvalues
3-element Array{Complex{Float64},1}: -0.07094370057923445 - 1.5139635518670342im -0.07094370057923445 + 1.5139635518670342im 9.141887401158474 + 0.0im
F.vectors # the eigenvectors
3×3 Array{Complex{Float64},2}: 0.834342-0.0im 0.834342+0.0im 0.42575+0.0im -0.454852+0.168903im -0.454852-0.168903im 0.898092+0.0im 0.0672889-0.252839im 0.0672889+0.252839im 0.110305+0.0im
qr(A) # QR factorization = Gram-Schmidt orthogonalization
LinearAlgebra.QRCompactWY{Float64,Array{Float64,2}} Q factor: 3×3 LinearAlgebra.QRCompactWYQ{Float64,Array{Float64,2}}: -0.242536 0.748481 -0.617213 -0.970143 -0.18712 0.154303 0.0 0.636209 0.771517 R factor: 3×3 Array{Float64,2}: -4.12311 -7.5186 -3.63803 0.0 1.57181 5.50134 0.0 0.0 -3.24037
lu(A) # Gaussian elimination = LU factorization
LU{Float64,Array{Float64,2}} L factor: 3×3 Array{Float64,2}: 1.0 0.0 0.0 0.25 1.0 0.0 0.0 0.8 1.0 U factor: 3×3 Array{Float64,2}: 4.0 7.0 2.0 0.0 1.25 6.5 0.0 0.0 -4.2
svd(A)
SVD{Float64,Float64,Array{Float64,2}} U factor: 3×3 Array{Float64,2}: -0.657006 0.742232 -0.132041 -0.742831 -0.667249 -0.0545987 -0.128629 0.0622125 0.989739 singular values: 3-element Array{Float64,1}: 10.249509228237182 4.9777646539733755 0.4116061587661843 Vt factor: 3×3 Array{Float64,2}: -0.354 -0.712177 -0.606208 -0.387074 -0.478494 0.788173 -0.851386 0.513661 -0.106278
You must load a plotting library, similar to Python.
There are lots to choose from. If you are used to Python, you've probably used Matplotlib, and you can call Matplotlib in Julia via PyPlot:
using PyPlot
plot(x, "bo-")
1-element Array{PyCall.PyObject,1}: PyObject <matplotlib.lines.Line2D object at 0x7ffd3f6b1fd0>
x = range(0, 2π, length=1000)
y = sin.(3x + 4cos.(2x))
plot(x / 2π, y, "r-")
plot(x / 2π, y.^2, "b-")
plot(x / 2π, 1 ./ sqrt.(1 .+ y.^2), "b-")
xlabel("x / 2π")
ylabel("our funny function")
title("our second plot")
legend([L"y", L"y^2", L"\frac{1}{\sqrt{1+y^2}}"])
PyObject <matplotlib.legend.Legend object at 0x7ffd472bf790>
?plot
search: plot plot3D plotfile plot_date plot_trisurf plot_surface plot_wireframe
Plot y versus x as lines and/or markers. Call signatures:: plot([x], y, [fmt], *, data=None, **kwargs) plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs) The coordinates of the points or line nodes are given by *x*, *y*. The optional parameter *fmt* is a convenient way for defining basic formatting like color, marker and linestyle. It's a shortcut string notation described in the *Notes* section below. >>> plot(x, y) # plot x and y using default line style and color >>> plot(x, y, 'bo') # plot x and y using blue circle markers >>> plot(y) # plot y using x as index array 0..N-1 >>> plot(y, 'r+') # ditto, but with red plusses You can use `.Line2D` properties as keyword arguments for more control on the appearance. Line properties and *fmt* can be mixed. The following two calls yield identical results: >>> plot(x, y, 'go--', linewidth=2, markersize=12) >>> plot(x, y, color='green', marker='o', linestyle='dashed', ... linewidth=2, markersize=12) When conflicting with *fmt*, keyword arguments take precedence. **Plotting labelled data** There's a convenient way for plotting objects with labelled data (i.e. data that can be accessed by index ``obj['y']``). Instead of giving the data in *x* and *y*, you can provide the object in the *data* parameter and just give the labels for *x* and *y*:: >>> plot('xlabel', 'ylabel', data=obj) All indexable objects are supported. This could e.g. be a `dict`, a `pandas.DataFame` or a structured numpy array. **Plotting multiple sets of data** There are various ways to plot multiple sets of data. - The most straight forward way is just to call `plot` multiple times. Example: >>> plot(x1, y1, 'bo') >>> plot(x2, y2, 'go') - Alternatively, if your data is already a 2d array, you can pass it directly to *x*, *y*. A separate data set will be drawn for every column. Example: an array ``a`` where the first column represents the *x* values and the other columns are the *y* columns:: >>> plot(a[0], a[1:]) - The third way is to specify multiple sets of *[x]*, *y*, *[fmt]* groups:: >>> plot(x1, y1, 'g^', x2, y2, 'g-') In this case, any additional keyword argument applies to all datasets. Also this syntax cannot be combined with the *data* parameter. By default, each line is assigned a different style specified by a 'style cycle'. The *fmt* and line property parameters are only necessary if you want explicit deviations from these defaults. Alternatively, you can also change the style cycle using the 'axes.prop_cycle' rcParam. Parameters ---------- x, y : array-like or scalar The horizontal / vertical coordinates of the data points. *x* values are optional and default to `range(len(y))`. Commonly, these parameters are 1D arrays. They can also be scalars, or two-dimensional (in that case, the columns represent separate data sets). These arguments cannot be passed as keywords. fmt : str, optional A format string, e.g. 'ro' for red circles. See the *Notes* section for a full description of the format strings. Format strings are just an abbreviation for quickly setting basic line properties. All of these and more can also be controlled by keyword arguments. This argument cannot be passed as keyword. data : indexable object, optional An object with labelled data. If given, provide the label names to plot in *x* and *y*. .. note:: Technically there's a slight ambiguity in calls where the second label is a valid *fmt*. `plot('n', 'o', data=obj)` could be `plt(x, y)` or `plt(y, fmt)`. In such cases, the former interpretation is chosen, but a warning is issued. You may suppress the warning by adding an empty format string `plot('n', 'o', '', data=obj)`. Other Parameters ---------------- scalex, scaley : bool, optional, default: True These parameters determined if the view limits are adapted to the data limits. The values are passed on to `autoscale_view`. **kwargs : `.Line2D` properties, optional *kwargs* are used to specify properties like a line label (for auto legends), linewidth, antialiasing, marker face color. Example:: >>> plot([1,2,3], [1,2,3], 'go-', label='line 1', linewidth=2) >>> plot([1,2,3], [1,4,9], 'rs', label='line 2') If you make multiple lines with one plot command, the kwargs apply to all those lines. Here is a list of available `.Line2D` properties: agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array alpha: float animated: bool antialiased or aa: bool clip_box: `.Bbox` clip_on: bool clip_path: [(`~matplotlib.path.Path`, `.Transform`) | `.Patch` | None] color or c: color contains: callable dash_capstyle: {'butt', 'round', 'projecting'} dash_joinstyle: {'miter', 'round', 'bevel'} dashes: sequence of floats (on/off ink in points) or (None, None) drawstyle or ds: {'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default' figure: `.Figure` fillstyle: {'full', 'left', 'right', 'bottom', 'top', 'none'} gid: str in_layout: bool label: object linestyle or ls: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...} linewidth or lw: float marker: marker style markeredgecolor or mec: color markeredgewidth or mew: float markerfacecolor or mfc: color markerfacecoloralt or mfcalt: color markersize or ms: float markevery: None or int or (int, int) or slice or List[int] or float or (float, float) path_effects: `.AbstractPathEffect` picker: float or callable[[Artist, Event], Tuple[bool, dict]] pickradius: float rasterized: bool or None sketch_params: (scale: float, length: float, randomness: float) snap: bool or None solid_capstyle: {'butt', 'round', 'projecting'} solid_joinstyle: {'miter', 'round', 'bevel'} transform: `matplotlib.transforms.Transform` url: str visible: bool xdata: 1D array ydata: 1D array zorder: float Returns ------- lines A list of `.Line2D` objects representing the plotted data. See Also -------- scatter : XY scatter plot with markers of varying size and/or color ( sometimes also called bubble chart). Notes ----- **Format Strings** A format string consists of a part for color, marker and line:: fmt = '[marker][line][color]' Each of them is optional. If not provided, the value from the style cycle is used. Exception: If ``line`` is given, but no ``marker``, the data will be a line without markers. Other combinations such as ``[color][marker][line]`` are also supported, but note that their parsing may be ambiguous. **Markers** ============= =============================== character description ============= =============================== ``'.'`` point marker ``','`` pixel marker ``'o'`` circle marker ``'v'`` triangle_down marker ``'^'`` triangle_up marker ``'<'`` triangle_left marker ``'>'`` triangle_right marker ``'1'`` tri_down marker ``'2'`` tri_up marker ``'3'`` tri_left marker ``'4'`` tri_right marker ``'s'`` square marker ``'p'`` pentagon marker ``'*'`` star marker ``'h'`` hexagon1 marker ``'H'`` hexagon2 marker ``'+'`` plus marker ``'x'`` x marker ``'D'`` diamond marker ``'d'`` thin_diamond marker ``'|'`` vline marker ``'_'`` hline marker ============= =============================== **Line Styles** ============= =============================== character description ============= =============================== ``'-'`` solid line style ``'--'`` dashed line style ``'-.'`` dash-dot line style ``':'`` dotted line style ============= =============================== Example format strings:: 'b' # blue markers with default shape 'or' # red circles '-g' # green solid line '--' # dashed line with default color '^k:' # black triangle_up markers connected by a dotted line **Colors** The supported color abbreviations are the single letter codes ============= =============================== character color ============= =============================== ``'b'`` blue ``'g'`` green ``'r'`` red ``'c'`` cyan ``'m'`` magenta ``'y'`` yellow ``'k'`` black ``'w'`` white ============= =============================== and the ``'CN'`` colors that index into the default property cycle. If the color is the only part of the format string, you can additionally use any `matplotlib.colors` spec, e.g. full names (``'green'``) or hex strings (``'#008000'``).
In an OOP language like Python or C++, given an object o
, you would type o.method(x,y)
to call a method, and it would choose the correct method
based on the runtime ("dynamic") type of o
(for a "virtual" method).
In Julia, the analogous code would call method(o, x, y)
— o
is just one of the arguments. But Julia looks at the runtime ("dynamic") types of all the arguments to decide on the method
to call.
In this sense it is a strict superset of multiple dispatch. It is not equivalent to C++ overloading, because that is static overloading. There was a nice talk about the differences between OOP, static overloading, and dynamic multiple dispatch at JuliaCon 2019 that I strongly encourage you to go watch.
foo(x, y) = x + y
foo (generic function with 1 method)
foo(3, 4)
7
foo(A, 4)
MethodError: no method matching +(::Array{Int64,2}, ::Int64) For element-wise addition, use broadcasting with dot syntax: array .+ scalar Closest candidates are: +(::Any, ::Any, !Matched::Any, !Matched::Any...) at operators.jl:538 +(!Matched::Missing, ::Number) at missing.jl:115 +(!Matched::BigFloat, ::Union{Int16, Int32, Int64, Int8}) at mpfr.jl:378 ... Stacktrace: [1] foo(::Array{Int64,2}, ::Int64) at ./In[130]:1 [2] top-level scope at In[132]:1 [3] include_string(::Function, ::Module, ::String, ::String) at ./loading.jl:1091 [4] execute_code(::String, ::String) at /Users/stevenj/.julia/dev/IJulia/src/execute_request.jl:27 [5] execute_request(::ZMQ.Socket, ::IJulia.Msg) at /Users/stevenj/.julia/dev/IJulia/src/execute_request.jl:86 [6] #invokelatest#1 at ./essentials.jl:710 [inlined] [7] invokelatest at ./essentials.jl:709 [inlined] [8] eventloop(::ZMQ.Socket) at /Users/stevenj/.julia/dev/IJulia/src/eventloop.jl:8 [9] (::IJulia.var"#15#18")() at ./task.jl:356
foo(A::Matrix, y::Number) = A + y*I
foo (generic function with 2 methods)
foo(A, 100)
3×3 Array{Int64,2}: 101 3 7 4 107 2 0 1 101
foo(A, A)
3×3 Array{Int64,2}: 2 6 14 8 14 4 0 2 2