This is one of the 100 recipes of the IPython Cookbook, the definitive guide to high-performance scientific computing and data science in Python.
For this recipe, you need to install Julia and IJulia. You'll find the installation instructions in the book.
println()function displays a string and adds a line break at the end.
fthat computes the expression $z*z+c$. We will notably evaluate this function on arrays, so we use elementwise operators with a dot (
f(z, c) = z.*z .+ c
fon scalar complex numbers (the imaginary number $i$ is
f(2.0 + 1.0im, 1.0)
(2, 2)matrix. Components are separated by a space, rows are separated by a semicolon (
;). The type of this
Arrayis automatically inferred from its components. The
Arraytype is a built-in data type in Julia, similar, but not identical, to NumPy's
z = [-1.0 - 1.0im 1.0 - 1.0im; -1.0 + 1.0im 1.0 + 1.0im]
. A notable difference with Python is that indexing starts from 1 instead of 0. MATLAB has the same convention. Besides, the keyword
endrefers to the last item in that dimension.
fon the matrix
zand a scalar
juliathat computes a Julia set. Optional named arguments are separated from positional arguments by a semicolon (
;). Julia's syntax for flow control is close from Python's, except that colons are dropped, indentation doesn't count, and block
endkeywords are mandatory.
function julia(z, c; maxiter=200) for n = 1:maxiter if abs2(z) > 4.0 return n-1 end z = f(z, c) end return maxiter end
PyCallpackage by using Julia's built-in package manager (
Pkg). Once the package is installed, we can use it in the interactive session with
Pkg.add("PyCall") using PyCall
@pyimportmacro (a metaprogramming feature in Julia). This macro is the equivalent of Python's
@pyimport numpy as np
npnamespace is now available in the Julia interactive session. NumPy arrays are automatically converted to Julia
z = np.linspace(-1., 1., 100)
juliaon many arguments.
m = [julia(z[i], 0.5) for i=1:100]
Pkg.add("Gadfly") using Gadfly
plot(x=1:100, y=m, Geom.point, Geom.line)
forloops instead of vectorized operations in Julia. High-performance code can be written either with vectorized operations or
@time m = [julia(complex(r, i), complex(-0.06, 0.67)) for i = 1:-.001:-1, r = -1.5:.001:1.5];
PyPlotpackage to draw matplotlib figures in Julia.
Pkg.add("PyPlot") using PyPlot
imshow(m, cmap="RdGy", extent=[-1.5, 1.5, -1, 1]);