Using Julia in Jupyter

-- see the file on Using Python in Jupyter for some basics on Jupyter. This file is only about Julia.

Julia knows about integers, floating point numbers, even complex numbers like 1+2im.


In [1]:
2+2


Out[1]:
4

In [2]:
2/3


Out[2]:
0.6666666666666666

In [8]:
(1+2im)*(2+3im)


Out[8]:
-5 + 10im

Julia already knows about sines and cosines, arrays, ranges of numbers. So you can save a lot of time and do calculations quickly. For instance, we can sum the integers from 1 to 100 as follows:


In [15]:
sum(1:100)


Out[15]:
5050

We can compute the Riemann sum of the integral $\int_0^\pi \sin(x) dx$ as $$\sum_{k=1}^N \sin(x_k)\Delta_k$$ as:


In [17]:
sum(sin(0:.01:pi))*.01


Out[17]:
1.9999900283082466

In [27]:
# Here is a matrix. Notice there are no commas. The semicolon separates the rows.
m = [10 20; 30 40]


Out[27]:
2×2 Array{Int64,2}:
 10  20
 30  40

In [28]:
det(m)


Out[28]:
-200.0

In [38]:
eig(m)


Out[38]:
([-3.72281,53.7228],
[-0.824565 -0.415974; 0.565767 -0.909377])

In [40]:
eigval,eigvec = eig(m)


Out[40]:
([-3.72281,53.7228],
[-0.824565 -0.415974; 0.565767 -0.909377])

In [41]:
# Check that the product of the eignvalues is the determinant.
prod(eigval)


Out[41]:
-200.0

In [42]:
m*m


Out[42]:
2×2 Array{Int64,2}:
  700  1000
 1500  2200

In [43]:
m^2


Out[43]:
2×2 Array{Int64,2}:
  700  1000
 1500  2200

In [45]:
det(m^2)


Out[45]:
40000.00000000014

In [46]:
exp(m)


Out[46]:
2×2 Array{Float64,2}:
 22026.5         4.85165e8 
     1.06865e13  2.35385e17

In [47]:
expm(m)


Out[47]:
2×2 Array{Float64,2}:
 5.12516e22  7.46955e22
 1.12043e23  1.63295e23

Plotting in Julia

To plot, we have to load in a package. The one we will use is called PyPlot, which is the same package as we used in Python plotting. (matplotlib.pyplot)

Notice the syntax for loading a package is very different in Julia.

Warning: Also note that this is a dangerous spot for the workshop, as this beta implementation of Julia tends to choke on loading packages. Especially if everyone in class tries to do it at once.


In [32]:
using PyPlot

In [33]:
plot([1,2,3,4])


Out[33]:
1-element Array{Any,1}:
 PyObject <matplotlib.lines.Line2D object at 0x314634cd0>

In [34]:
x = linspace(-3, 3)
y = x.^3 - 3*x
plot(x,y)


Out[34]:
1-element Array{Any,1}:
 PyObject <matplotlib.lines.Line2D object at 0x314807790>

In [35]:
n = 100
x = linspace(-3, 3, n)
y = linspace(-3,3,n)

xgrid = repmat(x',n,1)
ygrid = repmat(y,1,n)

z=exp(-xgrid.^2 - ygrid.^2)

plot_surface(x,y,z)


Out[35]:
PyObject <mpl_toolkits.mplot3d.art3d.Poly3DCollection object at 0x314a7d0d0>

In [36]:
plot_surface(x,y,z,cmap="jet")


Out[36]:
PyObject <mpl_toolkits.mplot3d.art3d.Poly3DCollection object at 0x314b4c150>

In [37]:
imshow(z)


Out[37]:
PyObject <matplotlib.image.AxesImage object at 0x3153f6690>

In [ ]: