In [1]:
1 + 1


Out[1]:
2

In [2]:
1 + 1
2 + 2


Out[2]:
4

In [4]:
1 + 1
2 + 2;

In [5]:
?println


search: println printstyled print sprint isprint

Out[5]:
println([io::IO], xs...)

Print (using print) xs followed by a newline. If io is not supplied, prints to stdout.

Examples

jldoctest
julia> println("Hello, world")
Hello, world

julia> io = IOBuffer();

julia> println(io, "Hello, world")

julia> String(take!(io))
"Hello, world\n"

In [8]:
;pwd


/Users/byeon/temp

In [9]:
println("I'm excited to learn Julia!")


I'm excited to learn Julia!

In [10]:
my_answer = 42
typeof(my_answer)


Out[10]:
Int64

In [11]:
my_pi = 3.14159
typeof(my_pi)


Out[11]:
Float64

In [12]:
😺 = "smiley cat!"
typeof(😺)


Out[12]:
String

In [13]:
😺 = 1


Out[13]:
1

In [14]:
typeof(😺)


Out[14]:
Int64

In [15]:
😀 = 0
😞 = -1


Out[15]:
-1

In [16]:
😺 + 😞 == 😀


Out[16]:
true

In [17]:
sum = 3 + 7


Out[17]:
10

In [18]:
difference = 10 - 3


Out[18]:
7

In [19]:
product = 20 * 5


Out[19]:
100

In [20]:
quotient = 100 / 10


Out[20]:
10.0

In [21]:
power = 10^2


Out[21]:
100

In [22]:
modulus = 101%2


Out[22]:
1

In [23]:
?convert


search: convert code_native @code_native

Out[23]:
convert(T, x)

Convert x to a value of type T.

If T is an Integer type, an InexactError will be raised if x is not representable by T, for example if x is not integer-valued, or is outside the range supported by T.

Examples

jldoctest
julia> convert(Int, 3.0)
3

julia> convert(Int, 3.5)
ERROR: InexactError: Int64(3.5)
Stacktrace:
[...]

If T is a AbstractFloat or Rational type, then it will return the closest value to x representable by T.

jldoctest
julia> x = 1/3
0.3333333333333333

julia> convert(Float32, x)
0.33333334f0

julia> convert(Rational{Int32}, x)
1//3

julia> convert(Rational{Int64}, x)
6004799503160661//18014398509481984

If T is a collection type and x a collection, the result of convert(T, x) may alias all or part of x.

jldoctest
julia> x = Int[1, 2, 3];

julia> y = convert(Vector{Int}, x);

julia> y === x
true

In [27]:
days = 365
days_float = float(days)


Out[27]:
365.0

In [28]:
@assert days == 365
@assert days_float == 365.0

In [29]:
convert(Int64, "1")


MethodError: Cannot `convert` an object of type String to an object of type Int64
Closest candidates are:
  convert(::Type{T<:Number}, !Matched::T<:Number) where T<:Number at number.jl:6
  convert(::Type{T<:Number}, !Matched::Number) where T<:Number at number.jl:7
  convert(::Type{T<:Integer}, !Matched::Ptr) where T<:Integer at pointer.jl:23
  ...

Stacktrace:
 [1] top-level scope at In[29]:1

In [32]:
parse(Float64, "1")


Out[32]:
1.0

In [34]:
s1 = "I am a string."


Out[34]:
"I am a string."

In [35]:
s2 = """I am also a string. """


Out[35]:
"I am also a string. "

In [36]:
"Here, we get an "error" because it's ambiguous where this string ends "


syntax: cannot juxtapose string literal

In [37]:
"""Look, Mom, no "errors"!!! """


Out[37]:
"Look, Mom, no \"errors\"!!! "

In [38]:
typeof('a')


Out[38]:
Char

In [39]:
'We will get an error here'


syntax: invalid character literal

In [40]:
name = "Jane"
num_fingers = 10
num_toes = 10


Out[40]:
10

In [41]:
println("Hello, my name is $name.")
println("I have $num_fingers fingers and $num_toes toes.")


Hello, my name is Jane.
I have 10 fingers and 10 toes.

In [42]:
println("That is $(num_fingers + num_toes) digits in all!!")


That is 20 digits in all!!

In [43]:
s3 = "How many cats ";
s4 = "is too many cats?";
😺 = 10


Out[43]:
10

In [44]:
string(s3, s4)


Out[44]:
"How many cats is too many cats?"

In [45]:
string("I don't know, but ", 😺, " is too few.")


Out[45]:
"I don't know, but 10 is too few."

In [48]:
"hi"^100


MethodError: no method matching *(::String, ::Int64)
Closest candidates are:
  *(::Any, ::Any, !Matched::Any, !Matched::Any...) at operators.jl:502
  *(!Matched::Complex{Bool}, ::Real) at complex.jl:300
  *(!Matched::Missing, ::Number) at missing.jl:97
  ...

Stacktrace:
 [1] top-level scope at In[48]:1

In [49]:
myfavoriteanimals = ("penguins", "cats", "sugargliders")


Out[49]:
("penguins", "cats", "sugargliders")

In [50]:
myfavoriteanimals[1]


Out[50]:
"penguins"

In [51]:
myfavoriteanimals = (bird = "penguins", mammal = "cats", marsupial = "sugargliders")


Out[51]:
(bird = "penguins", mammal = "cats", marsupial = "sugargliders")

In [52]:
myfavoriteanimals[1]


Out[52]:
"penguins"

In [53]:
myfavoriteanimals.bird


Out[53]:
"penguins"

In [54]:
myphonebook = Dict("Jenny" => "867-5309", "Ghostbusters" => "555-2368")


Out[54]:
Dict{String,String} with 2 entries:
  "Jenny"        => "867-5309"
  "Ghostbusters" => "555-2368"

In [55]:
myphonebook["Jenny"]


Out[55]:
"867-5309"

In [56]:
myphonebook["Kramer"] = "555-FILK"


Out[56]:
"555-FILK"

In [57]:
myphonebook


Out[57]:
Dict{String,String} with 3 entries:
  "Jenny"        => "867-5309"
  "Kramer"       => "555-FILK"
  "Ghostbusters" => "555-2368"

In [58]:
pop!(myphonebook, "Kramer")


Out[58]:
"555-FILK"

In [59]:
myphonebook


Out[59]:
Dict{String,String} with 2 entries:
  "Jenny"        => "867-5309"
  "Ghostbusters" => "555-2368"

In [64]:
myphonebook[1]


KeyError: key 1 not found

Stacktrace:
 [1] getindex(::Dict{String,String}, ::Int64) at ./dict.jl:478
 [2] top-level scope at In[64]:1

In [65]:
myfriends = ["Ted", "Robyn", "Barney", "Lily", "Marshall"]


Out[65]:
5-element Array{String,1}:
 "Ted"     
 "Robyn"   
 "Barney"  
 "Lily"    
 "Marshall"

In [66]:
mixture = [1, 1, 2, 3, "Ted", "Robyn"]


Out[66]:
6-element Array{Any,1}:
 1       
 1       
 2       
 3       
  "Ted"  
  "Robyn"

In [67]:
fibonacci = [1, 1, 2, 3, 5, 8, 13]


Out[67]:
7-element Array{Int64,1}:
  1
  1
  2
  3
  5
  8
 13

In [68]:
push!(fibonacci, 21)


Out[68]:
8-element Array{Int64,1}:
  1
  1
  2
  3
  5
  8
 13
 21

In [69]:
pop!(fibonacci)


Out[69]:
21

In [70]:
fibonacci


Out[70]:
7-element Array{Int64,1}:
  1
  1
  2
  3
  5
  8
 13

In [71]:
favorites = [["koobideh", "chocolate", "eggs"],["penguins", "cats", "sugargliders"]]


Out[71]:
2-element Array{Array{String,1},1}:
 ["koobideh", "chocolate", "eggs"]   
 ["penguins", "cats", "sugargliders"]

In [72]:
numbers = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]


Out[72]:
3-element Array{Array{Int64,1},1}:
 [1, 2, 3]   
 [4, 5]      
 [6, 7, 8, 9]

In [73]:
rand(4, 3)


Out[73]:
4×3 Array{Float64,2}:
 0.463993  0.104175   0.418099  
 0.568473  0.0408378  0.258434  
 0.778073  0.944718   0.00460527
 0.166763  0.151499   0.697306  

In [74]:
rand(4, 3, 2)


Out[74]:
4×3×2 Array{Float64,3}:
[:, :, 1] =
 0.0584397  0.456066  0.25242 
 0.787691   0.712221  0.393644
 0.202973   0.769285  0.589937
 0.515777   0.387463  0.828897

[:, :, 2] =
 0.732792  0.849716   0.711296 
 0.507418  0.0395161  0.0852141
 0.9765    0.238069   0.928197 
 0.560407  0.759754   0.65496  

In [80]:
n = 0
while n < 10
    n += 1
                println(n)
end
n


1
2
3
4
5
6
7
8
9
10
Out[80]:
10

In [82]:
n = 0
while n < 10; n += 1 
                println(n)
end
n


1
2
3
4
5
6
7
8
9
10
Out[82]:
10

In [79]:
myfriends = ["Ted", "Robyn", "Barney", "Lily", "Marshall"]

i = 1
while i <= length(myfriends)
    friend = myfriends[i]
    println("Hi $friend, it's great to see you!")
    i += 1
end


Hi Ted, it's great to see you!
Hi Robyn, it's great to see you!
Hi Barney, it's great to see you!
Hi Lily, it's great to see you!
Hi Marshall, it's great to see you!

In [83]:
for n in 1:10
    println(n)
end


1
2
3
4
5
6
7
8
9
10

In [84]:
m, n = 5, 5
A = fill(0, (m, n))


Out[84]:
5×5 Array{Int64,2}:
 0  0  0  0  0
 0  0  0  0  0
 0  0  0  0  0
 0  0  0  0  0
 0  0  0  0  0

In [85]:
for i in 1:m
    for j in 1:n
        A[i, j] = i + j
    end
end
A


Out[85]:
5×5 Array{Int64,2}:
 2  3  4  5   6
 3  4  5  6   7
 4  5  6  7   8
 5  6  7  8   9
 6  7  8  9  10

In [86]:
B = fill(0, (m, n))


Out[86]:
5×5 Array{Int64,2}:
 0  0  0  0  0
 0  0  0  0  0
 0  0  0  0  0
 0  0  0  0  0
 0  0  0  0  0

In [87]:
for i in 1:m, j in 1:n
    B[i, j] = i + j
end
B


Out[87]:
5×5 Array{Int64,2}:
 2  3  4  5   6
 3  4  5  6   7
 4  5  6  7   8
 5  6  7  8   9
 6  7  8  9  10

In [88]:
C = [i + j for i in 1:m, j in 1:n]


Out[88]:
5×5 Array{Int64,2}:
 2  3  4  5   6
 3  4  5  6   7
 4  5  6  7   8
 5  6  7  8   9
 6  7  8  9  10

In [94]:
[ x+y for x in 1:10, y in 2:5]


Out[94]:
10×4 Array{Int64,2}:
  3   4   5   6
  4   5   6   7
  5   6   7   8
  6   7   8   9
  7   8   9  10
  8   9  10  11
  9  10  11  12
 10  11  12  13
 11  12  13  14
 12  13  14  15

In [97]:
N=15

if (N % 3 == 0) && (N % 5 == 0) # `&&` means "AND"; % computes the remainder after division
    println("FizzBuzz")
elseif N % 3 == 0
    println("Fizz")
elseif N % 5 == 0
    println("Buzz")
else
    println(N)
end


FizzBuzz

In [101]:
x = 10
y = 5


Out[101]:
5

In [102]:
if x > y
    x
else
    y
end


Out[102]:
10

In [103]:
(x > y) ? x : y


Out[103]:
10

In [104]:
false && (println("hi"); true)


Out[104]:
false

In [105]:
true && (println("hi"); true)


hi
Out[105]:
true

In [106]:
(x > 0) && error("x cannot be greater than 0")


x cannot be greater than 0

Stacktrace:
 [1] error(::String) at ./error.jl:33
 [2] top-level scope at In[106]:1

In [107]:
true || println("hi")


Out[107]:
true

In [108]:
false || println("hi")


hi

In [121]:
function sayhi(name)
    println("Hi $name, it's great to see you!")
end

function f(x)
    x^2
end


Out[121]:
f (generic function with 1 method)

In [110]:
sayhi("kyle")


Hi kyle, it's great to see you!

In [111]:
sayhi2(name) = println("Hi $name, it's great to see you!")


Out[111]:
sayhi2 (generic function with 1 method)

In [112]:
sayhi2("ho")


Hi ho, it's great to see you!

In [113]:
sayhi3 = name -> println("Hi $name, it's great to see you!")


Out[113]:
#15 (generic function with 1 method)

In [114]:
sayhi3("hohoo")


Hi hohoo, it's great to see you!

In [115]:
sayhi(55595472)


Hi 55595472, it's great to see you!

In [117]:
sayhi4 = (firstname, lastname) -> println("Hi $firstname $lastname, it's greate to see you!")


Out[117]:
#19 (generic function with 1 method)

In [118]:
sayhi4("hi", "ho")


Hi hi ho, it's greate to see you!

In [119]:
A = rand(3, 3)


Out[119]:
3×3 Array{Float64,2}:
 0.0775081  0.0800009  0.998591
 0.753966   0.261457   0.698373
 0.293849   0.866148   0.66559 

In [122]:
f(A)


Out[122]:
3×3 Array{Float64,2}:
 0.35976   0.892045  0.797921
 0.460784  0.733573  1.40033 
 0.871405  0.826468  1.34134 

In [123]:
f("hi")


Out[123]:
"hihi"

In [124]:
v = rand(3)


Out[124]:
3-element Array{Float64,1}:
 0.5938586778892128 
 0.08010308574059244
 0.6022367725975926 

In [125]:
f(v)


MethodError: no method matching ^(::Array{Float64,1}, ::Int64)
Closest candidates are:
  ^(!Matched::Float16, ::Integer) at math.jl:795
  ^(!Matched::Missing, ::Integer) at missing.jl:124
  ^(!Matched::Missing, ::Number) at missing.jl:97
  ...

Stacktrace:
 [1] macro expansion at ./none:0 [inlined]
 [2] literal_pow at ./none:0 [inlined]
 [3] f(::Array{Float64,1}) at ./In[121]:6
 [4] top-level scope at In[125]:1

In [126]:
v = [3, 5, 2]


Out[126]:
3-element Array{Int64,1}:
 3
 5
 2

In [127]:
sort(v)


Out[127]:
3-element Array{Int64,1}:
 2
 3
 5

In [128]:
v


Out[128]:
3-element Array{Int64,1}:
 3
 5
 2

In [130]:
sort!(v)


Out[130]:
3-element Array{Int64,1}:
 2
 3
 5

In [131]:
v


Out[131]:
3-element Array{Int64,1}:
 2
 3
 5

In [132]:
map(f, [1, 2, 3])


Out[132]:
3-element Array{Int64,1}:
 1
 4
 9

In [133]:
x -> x^3


Out[133]:
#21 (generic function with 1 method)

In [134]:
map(x -> x^3, [1, 2, 3])


Out[134]:
3-element Array{Int64,1}:
  1
  8
 27

In [135]:
broadcast(f, [1, 2, 3])


Out[135]:
3-element Array{Int64,1}:
 1
 4
 9

In [136]:
f.([1, 2, 3])


Out[136]:
3-element Array{Int64,1}:
 1
 4
 9

In [137]:
f(A)


Out[137]:
3×3 Array{Float64,2}:
 0.35976   0.892045  0.797921
 0.460784  0.733573  1.40033 
 0.871405  0.826468  1.34134 

In [139]:
f.(A)


Out[139]:
3×3 Array{Float64,2}:
 0.00600751  0.00640015  0.997184
 0.568464    0.0683598   0.487725
 0.0863471   0.750213    0.44301 

In [140]:
A = [i + 3*j for j in 0:2, i in 1:3]


Out[140]:
3×3 Array{Int64,2}:
 1  2  3
 4  5  6
 7  8  9

In [141]:
f(A)


Out[141]:
3×3 Array{Int64,2}:
  30   36   42
  66   81   96
 102  126  150

In [142]:
B = f.(A)


Out[142]:
3×3 Array{Int64,2}:
  1   4   9
 16  25  36
 49  64  81

In [143]:
A .+ 2 .* f.(A) ./ A


Out[143]:
3×3 Array{Float64,2}:
  3.0   6.0   9.0
 12.0  15.0  18.0
 21.0  24.0  27.0

In [144]:
using Pkg

In [145]:
Pkg.add("Example")


  Updating registry at `~/.julia/registries/General`
  Updating git-repo `https://github.com/JuliaRegistries/General.git`
[1mFetching: [========================================>]  99.9 %0.0 %Fetching: [=====>                                   ]  10.8 %Fetching: [=====>                                   ]  11.7 %                         ]  36.6 % [====================>                    ]  49.2 %]  61.8 %]  68.4 %Fetching: [==============================>          ]  74.6 %>       ]  81.1 %======================================>  ]  93.7 %Fetching: [=======================================> ]  96.5 %Fetching: [=======================================> ]  97.1 % Resolving package versions...
 Installed FixedPointNumbers ─ v0.7.0
 Installed DiffResults ─────── v1.0.2
 Installed Example ─────────── v0.5.3
 Installed DiffRules ───────── v1.0.0
 Installed ColorTypes ──────── v0.9.0
 Installed ForwardDiff ─────── v0.10.8
 Installed VersionParsing ──── v1.2.0
 Installed Colors ──────────── v0.11.0
  Updating `~/.julia/environments/v1.1/Project.toml`
  [7876af07] + Example v0.5.3
  Updating `~/.julia/environments/v1.1/Manifest.toml`
  [3da002f7] ↑ ColorTypes v0.8.0 ⇒ v0.9.0
  [5ae59095] ↑ Colors v0.9.6 ⇒ v0.11.0
  [163ba53b] ↑ DiffResults v0.0.4 ⇒ v1.0.2
  [b552c78f] ↑ DiffRules v0.1.0 ⇒ v1.0.0
  [7876af07] + Example v0.5.3
  [53c48c17] ↑ FixedPointNumbers v0.6.1 ⇒ v0.7.0
  [f6369f11] ↑ ForwardDiff v0.10.7 ⇒ v0.10.8
  [81def892] ↑ VersionParsing v1.1.3 ⇒ v1.2.0

In [146]:
Pkg.add("Colors")


 Resolving package versions...
  Updating `~/.julia/environments/v1.1/Project.toml`
  [5ae59095] + Colors v0.11.0
  Updating `~/.julia/environments/v1.1/Manifest.toml`
 [no changes]

In [152]:
using Colors

In [150]:
palette = distinguishable_colors(100)


Out[150]:

In [151]:
rand(palette, 3, 3)


Out[151]:

In [163]:
Pkg.add("PyPlot")
using PyPlot


 Resolving package versions...
  Updating `~/.julia/environments/v1.1/Project.toml`
 [no changes]
  Updating `~/.julia/environments/v1.1/Manifest.toml`
 [no changes]
┌ Info: Recompiling stale cache file /Users/byeon/.julia/compiled/v1.1/PyPlot/oatAj.ji for PyPlot [d330b81b-6aea-500a-939a-2ce795aea3ee]
└ @ Base loading.jl:1184

In [164]:
globaltemperatures = [14.4, 14.5, 14.8, 15.2, 15.5, 15.8]
numpirates = [45000, 20000, 15000, 5000, 400, 17];

In [176]:
gr()


UndefVarError: gr not defined

Stacktrace:
 [1] top-level scope at In[176]:1

In [178]:
plot(numpirates, globaltemperatures, label="line") 
scatter(numpirates, globaltemperatures, label="points", color="red")
xlabel("Number of Pirates [Approximate]")
ylabel("Global Temperature (C)")
title("Influence of pirate population on global warming")


Out[178]:
PyObject Text(0.5, 1, 'Influence of pirate population on global warming')

In [159]:
xflip!()


UndefVarError: xflip! not defined

Stacktrace:
 [1] top-level scope at In[159]:1

In [ ]:
Pkg.add("UnicodePlots")
unicodeplots()

In [ ]:
plot(numpirates, globaltemperatures, label="line")  
scatter!(numpirates, globaltemperatures, label="points") 
xlabel!("Number of Pirates [Approximate]")
ylabel!("Global Temperature (C)")
title!("Influence of pirate population on global warming")

In [ ]:


In [3]:
a = rand(10^7) # 1D vector of random numbers, uniform on [0,1)


Out[3]:
10000000-element Array{Float64,1}:
 0.9768957314297495  
 0.1806148572947881  
 0.033595662943644244
 0.8976730367249619  
 0.28412903701447756 
 0.3197387559142524  
 0.21939491660081534 
 0.5695207918395557  
 0.8425569023510497  
 0.8797042767197885  
 0.757084828842655   
 0.37435853614162307 
 0.39212868797984535 
 ⋮                   
 0.41066965335992256 
 0.22385448873884184 
 0.31935475998439444 
 0.6326116084559534  
 0.22430738147532336 
 0.5691882948553524  
 0.22922607147254626 
 0.05422741818100252 
 0.5779451796430073  
 0.21620352855394676 
 0.9257437341191477  
 0.7621289881459283  

In [2]:
sum(a)


Out[2]:
5.000136622024098e6

In [3]:
@time sum(a)


  0.005217 seconds (5 allocations: 176 bytes)
Out[3]:
5.000136622024098e6

In [4]:
@time sum(a)


  0.005565 seconds (5 allocations: 176 bytes)
Out[4]:
5.000136622024098e6

In [5]:
@time sum(a)


  0.005058 seconds (5 allocations: 176 bytes)
Out[5]:
5.000136622024098e6

In [4]:
# using Pkg
# Pkg.add("BenchmarkTools")
using BenchmarkTools

In [5]:
using Libdl
C_code = """
#include <stddef.h>
double c_sum(size_t n, double *X) {
    double s = 0.0;
    for (size_t i = 0; i < n; ++i) {
        s += X[i];
    }
    return s;
}
"""

const Clib = tempname()   # make a temporary file


# compile to a shared library by piping C_code to gcc
# (works only if you have gcc installed):

open(`gcc -fPIC -O3 -msse3 -xc -shared -o $(Clib * "." * Libdl.dlext) -`, "w") do f
    print(f, C_code) 
end

# define a Julia function that calls the C function:
c_sum(X::Array{Float64}) = ccall(("c_sum", Clib), Float64, (Csize_t, Ptr{Float64}), length(X), X)


Out[5]:
c_sum (generic function with 1 method)

In [6]:
c_sum(a)


Out[6]:
5.000436132733203e6

In [9]:
c_sum(a)  sum(a) # type \approx and then <TAB> to get the ≈ symbolb


Out[9]:
true

In [10]:
c_sum(a) - sum(a)


Out[10]:
-5.876645445823669e-7

In [11]:
?isapprox


search: isapprox

Out[11]:
isapprox(x, y; rtol::Real=atol>0 ? 0 : √eps, atol::Real=0, nans::Bool=false, norm::Function)

Inexact equality comparison: true if norm(x-y) <= max(atol, rtol*max(norm(x), norm(y))). The default atol is zero and the default rtol depends on the types of x and y. The keyword argument nans determines whether or not NaN values are considered equal (defaults to false).

For real or complex floating-point values, if an atol > 0 is not specified, rtol defaults to the square root of eps of the type of x or y, whichever is bigger (least precise). This corresponds to requiring equality of about half of the significand digits. Otherwise, e.g. for integer arguments or if an atol > 0 is supplied, rtol defaults to zero.

x and y may also be arrays of numbers, in which case norm defaults to the usual norm function in LinearAlgebra, but may be changed by passing a norm::Function keyword argument. (For numbers, norm is the same thing as abs.) When x and y are arrays, if norm(x-y) is not finite (i.e. ±Inf or NaN), the comparison falls back to checking whether all elements of x and y are approximately equal component-wise.

The binary operator is equivalent to isapprox with the default arguments, and x ≉ y is equivalent to !isapprox(x,y).

Note that x ≈ 0 (i.e., comparing to zero with the default tolerances) is equivalent to x == 0 since the default atol is 0. In such cases, you should either supply an appropriate atol (or use norm(x) ≤ atol) or rearrange your code (e.g. use x ≈ y rather than x - y ≈ 0). It is not possible to pick a nonzero atol automatically because it depends on the overall scaling (the "units") of your problem: for example, in x - y ≈ 0, atol=1e-9 is an absurdly small tolerance if x is the radius of the Earth in meters, but an absurdly large tolerance if x is the radius of a Hydrogen atom in meters.

Examples

jldoctest
julia> 0.1 ≈ (0.1 - 1e-10)
true

julia> isapprox(10, 11; atol = 2)
true

julia> isapprox([10.0^9, 1.0], [10.0^9, 2.0])
true

julia> 1e-10 ≈ 0
false

julia> isapprox(1e-10, 0, atol=1e-8)
true

isapprox(x::FixedPoint, y::FixedPoint; rtol=0, atol=max(eps(x), eps(y)))

For FixedPoint numbers, the default criterion is that x and y differ by no more than eps, the separation between adjacent fixed-point numbers.


In [7]:
c_bench = @benchmark c_sum($a)


Out[7]:
BenchmarkTools.Trial: 
  memory estimate:  0 bytes
  allocs estimate:  0
  --------------
  minimum time:     11.468 ms (0.00% GC)
  median time:      11.902 ms (0.00% GC)
  mean time:        12.001 ms (0.00% GC)
  maximum time:     14.057 ms (0.00% GC)
  --------------
  samples:          417
  evals/sample:     1

In [8]:
println("C: Fastest time was $(minimum(c_bench.times) / 1e6) msec")


C: Fastest time was 11.467787 msec

In [9]:
d = Dict()  # a "dictionary", i.e. an associative array
d["C"] = minimum(c_bench.times) / 1e6  # in milliseconds
d


Out[9]:
Dict{Any,Any} with 1 entry:
  "C" => 11.4678

In [10]:
using Plots
gr()


Out[10]:
Plots.GRBackend()

In [ ]:
using Statistics # bring in statistical support for standard deviations
t = c_bench.times / 1e6 # times in milliseconds
m, σ = minimum(t), std(t)

histogram(t, bins=500,
    xlim=(m - 0.01, m + σ),
    xlabel="milliseconds", ylabel="count", label="")

In [1]:
f(x) = x^2


Out[1]:
f (generic function with 1 method)

In [2]:
f(10)


Out[2]:
100

In [3]:
f([1,2,3])


MethodError: no method matching ^(::Array{Int64,1}, ::Int64)
Closest candidates are:
  ^(!Matched::Float16, ::Integer) at math.jl:795
  ^(!Matched::Missing, ::Integer) at missing.jl:124
  ^(!Matched::Missing, ::Number) at missing.jl:97
  ...

Stacktrace:
 [1] macro expansion at ./none:0 [inlined]
 [2] literal_pow at ./none:0 [inlined]
 [3] f(::Array{Int64,1}) at ./In[1]:1
 [4] top-level scope at In[3]:1

In [4]:
f.([1,2,3])


Out[4]:
3-element Array{Int64,1}:
 1
 4
 9

In [5]:
foo(x::String, y::String) = println("My inputs x and y are both strings!")


Out[5]:
foo (generic function with 1 method)

In [6]:
foo("hello", "hi!")


My inputs x and y are both strings!

In [7]:
foo(3, 4)


MethodError: no method matching foo(::Int64, ::Int64)

Stacktrace:
 [1] top-level scope at In[7]:1

In [8]:
foo(x::Int, y::Int) = println("My inputs x and y are both integers!")


Out[8]:
foo (generic function with 2 methods)

In [9]:
foo(3, 4)


My inputs x and y are both integers!

In [10]:
foo("hello", "hi!")


My inputs x and y are both strings!

In [11]:
methods(foo)


Out[11]:
2 methods for generic function foo:
  • foo(x::Int64, y::Int64) in Main at In[8]:1
  • foo(x::String, y::String) in Main at In[5]:1

In [12]:
methods(+)


Out[12]:
163 methods for generic function +:

In [13]:
@which foo(3, 4)


Out[13]:
foo(x::Int64, y::Int64) in Main at In[8]:1

In [14]:
@which 3.0 + 3.0


Out[14]:
+(x::Float64, y::Float64) in Base at float.jl:395

In [15]:
foo(x::Number, y::Number) = println("My inputs x and y are both numbers!")


Out[15]:
foo (generic function with 3 methods)

In [16]:
foo(3.0, 4.0)


My inputs x and y are both numbers!

In [17]:
foo(x, y) = println("I accept inputs of any type!")


Out[17]:
foo (generic function with 4 methods)

In [18]:
v = rand(3)
foo(v, v)


I accept inputs of any type!

In [19]:
struct OrderedPair
   x::Real
   y::Real
   OrderedPair(x,y) = x > y ? error("out of order") : new(x,y)
end

In [20]:
OrderedPair(1, 2)


Out[20]:
OrderedPair(1, 2)

In [21]:
OrderedPair(2, 1)


out of order

Stacktrace:
 [1] error(::String) at ./error.jl:33
 [2] OrderedPair(::Int64, ::Int64) at ./In[19]:4
 [3] top-level scope at In[21]:1

In [25]:
import Pkg; Pkg.add("DataFrames")
using DataFrames


 Resolving package versions...
  Updating `~/.julia/environments/v1.1/Project.toml`
 [no changes]
  Updating `~/.julia/environments/v1.1/Manifest.toml`
 [no changes]
┌ Info: Precompiling DataFrames [a93c6f00-e57d-5684-b7b6-d8193f3e46c0]
└ @ Base loading.jl:1186

In [26]:
df = DataFrame(A = 1:4, B = ["M", "F", "F", "M"])


Out[26]:

4 rows × 2 columns

AB
Int64String
11M
22F
33F
44M

In [27]:
df.A


Out[27]:
4-element Array{Int64,1}:
 1
 2
 3
 4

In [31]:
df.A === df[!, 1]


Out[31]:
true

In [32]:
names(df)


Out[32]:
2-element Array{Symbol,1}:
 :A
 :B

In [33]:
df = DataFrame()


Out[33]:

0 rows × 0 columns


In [34]:
df.A = 1:8


Out[34]:
1:8

In [35]:
df.B = ["M", "F", "F", "M", "F", "M", "M", "F"]


Out[35]:
8-element Array{String,1}:
 "M"
 "F"
 "F"
 "M"
 "F"
 "M"
 "M"
 "F"

In [36]:
df


Out[36]:

8 rows × 2 columns

AB
Int64String
11M
22F
33F
44M
55F
66M
77M
88F

In [37]:
df = DataFrame(A = Int[], B = String[])


Out[37]:

0 rows × 2 columns

AB
Int64String

In [38]:
push!(df, (1, "M"))


Out[38]:

1 rows × 2 columns

AB
Int64String
11M

In [39]:
push!(df, [2, "N"])


Out[39]:

2 rows × 2 columns

AB
Int64String
11M
22N

In [40]:
push!(df, Dict(:B => "F", :A => 3))


Out[40]:

3 rows × 2 columns

AB
Int64String
11M
22N
33F

In [41]:
df = DataFrame(A = 1:2:1000, B = repeat(1:10, inner=50), C = 1:500)


Out[41]:

500 rows × 3 columns

ABC
Int64Int64Int64
1111
2312
3513
4714
5915
61116
71317
81518
91719
1019110
1121111
1223112
1325113
1427114
1529115
1631116
1733117
1835118
1937119
2039120
2141121
2243122
2345123
2447124
2549125
2651126
2753127
2855128
2957129
3059130
&vellip&vellip&vellip&vellip

In [42]:
df[df.A .> 500, :]


Out[42]:

250 rows × 3 columns

ABC
Int64Int64Int64
15016251
25036252
35056253
45076254
55096255
65116256
75136257
85156258
95176259
105196260
115216261
125236262
135256263
145276264
155296265
165316266
175336267
185356268
195376269
205396270
215416271
225436272
235456273
245476274
255496275
265516276
275536277
285556278
295576279
305596280
&vellip&vellip&vellip&vellip

In [43]:
df[in.(df.A, Ref([1, 5, 601])), :]


Out[43]:

3 rows × 3 columns

ABC
Int64Int64Int64
1111
2513
36017301

In [44]:
df = DataFrame(A = 1:4, B = ["M", "F", "F", "M"])


Out[44]:

4 rows × 2 columns

AB
Int64String
11M
22F
33F
44M

In [45]:
describe(df)


Out[45]:

2 rows × 8 columns

variablemeanminmedianmaxnuniquenmissingeltype
SymbolUnion…AnyUnion…AnyUnion…NothingDataType
1A2.512.54Int64
2BFM2String

In [46]:
df = DataFrame(A = 1:4, B = 4.0:-1.0:1.0)


Out[46]:

4 rows × 2 columns

AB
Int64Float64
114.0
223.0
332.0
441.0

In [47]:
aggregate(df, sum)


Out[47]:

1 rows × 2 columns

A_sumB_sum
Int64Float64
11010.0

In [48]:
aggregate(df, [sum, prod])


Out[48]:

1 rows × 4 columns

A_sumB_sumA_prodB_prod
Int64Float64Int64Float64
11010.02424.0

In [51]:
df.A[1] = 10


Out[51]:
10

In [52]:
df


Out[52]:

4 rows × 2 columns

AB
Int64Float64
1104.0
223.0
332.0
441.0

In [53]:
people = DataFrame(ID = [20, 40], Name = ["John Doe", "Jane Doe"])


Out[53]:

2 rows × 2 columns

IDName
Int64String
120John Doe
240Jane Doe

In [54]:
jobs = DataFrame(ID = [20, 40], Job = ["Lawyer", "Doctor"])


Out[54]:

2 rows × 2 columns

IDJob
Int64String
120Lawyer
240Doctor

In [55]:
join(people, jobs, on = :ID)


Out[55]:

2 rows × 3 columns

IDNameJob
Int64StringString
120John DoeLawyer
240Jane DoeDoctor

In [56]:
Pkg.add("JuMP")
Pkg.add("GLPK")
Pkg.add("Test")


 Resolving package versions...
  Updating `~/.julia/environments/v1.1/Project.toml`
 [no changes]
  Updating `~/.julia/environments/v1.1/Manifest.toml`
 [no changes]
 Resolving package versions...
  Updating `~/.julia/environments/v1.1/Project.toml`
 [no changes]
  Updating `~/.julia/environments/v1.1/Manifest.toml`
 [no changes]
 Resolving package versions...
  Updating `~/.julia/environments/v1.1/Project.toml`
  [8dfed614] + Test 
  Updating `~/.julia/environments/v1.1/Manifest.toml`
 [no changes]

In [1]:
using JuMP, GLPK, Test
const MOI = JuMP.MathOptInterface

"""
example_transp()
Allocation of passenger cars to trains to minimize cars required or car-miles
run. Based on:  Fourer, D.M. Gay and Brian W. Kernighan, A Modeling Language for
Mathematical Programming, http://www.ampl.com/REFS/amplmod.ps.gz Appendix D.
Author: Louis Luangkesorn
Date: Jan 30, 2015
"""
function example_transp()
    ORIG = ["GARY", "CLEV", "PITT"]
    DEST = ["FRA", "DET", "LAN", "WIN", "STL", "FRE", "LAF"]

    supply = [1_400, 2_600, 2_900]
    demand = [900, 1_200, 600, 400, 1_700, 1_100, 1_000]

    @assert sum(supply) == sum(demand)

    cost = [
        39   14   11   14   16   82    8;
        27    9   12    9   26   95   17;
        24   14   17   13   28   99   20
    ]

    model = Model(with_optimizer(GLPK.Optimizer))

    @variable(model, trans[1:length(ORIG), 1:length(DEST)] >= 0)
    @objective(model, Min, sum(cost[i, j] * trans[i, j] for i in 1:length(ORIG), j in 1:length(DEST)))

    @constraint(model, [i in 1:length(ORIG)],
        sum(trans[i, j] for j in 1:length(DEST)) == supply[i])
    @constraint(model, [j in 1:length(DEST)],
        sum(trans[i, j] for i in 1:length(ORIG)) == demand[j])

    JuMP.optimize!(model)

    @test JuMP.termination_status(model) == MOI.OPTIMAL
    @test JuMP.primal_status(model) == MOI.FEASIBLE_POINT
    @test JuMP.objective_value(model) == 196200.0
end

example_transp()


InitError: UndefVarError: libglpk not defined
during initialization of module GLPK

Stacktrace:
 [1] version at /Users/byeon/.julia/packages/GLPK/J1b5G/src/GLPK.jl:224 [inlined]
 [2] __init__() at /Users/byeon/.julia/packages/GLPK/J1b5G/src/GLPK.jl:244
 [3] _include_from_serialized(::String, ::Array{Any,1}) at ./loading.jl:633
 [4] _require_search_from_serialized(::Base.PkgId, ::String) at ./loading.jl:713
 [5] _require(::Base.PkgId) at ./loading.jl:937
 [6] require(::Base.PkgId) at ./loading.jl:858
 [7] require(::Module, ::Symbol) at ./loading.jl:853
 [8] top-level scope at In[1]:1

In [58]:
using JuMP, GLPK

# Preparing an optimization model
m = Model(with_optimizer(GLPK.Optimizer))

# Declaring variables
@variable(m, 0<= x1 <=10)
@variable(m, x2 >=0)
@variable(m, x3 >=0)

# Setting the objective
@objective(m, Max, x1 + 2x2 + 5x3)

# Adding constraints
@constraint(m, constraint1, -x1 +  x2 + 3x3 <= -5)
@constraint(m, constraint2,  x1 + 3x2 - 7x3 <= 10)

# Printing the prepared optimization model
print(m)

# Solving the optimization problem
JuMP.optimize!(m)

# Printing the optimal solutions obtained
println("Optimal Solutions:")
println("x1 = ", JuMP.value(x1))
println("x2 = ", JuMP.value(x2))
println("x3 = ", JuMP.value(x3))

# Printing the optimal dual variables
println("Dual Variables:")
println("dual1 = ", JuMP.shadow_price(constraint1))
println("dual2 = ", JuMP.shadow_price(constraint2))


UndefVarError: libglpk not defined

Stacktrace:
 [1] Prob(::Ptr{Nothing}) at /Users/byeon/.julia/packages/GLPK/J1b5G/src/GLPK.jl:224
 [2] Type at /Users/byeon/.julia/packages/GLPK/J1b5G/src/GLPK.jl:357 [inlined]
 [3] (::getfield(GLPK, Symbol("##Optimizer#15#16")))(::Bool, ::GLPK.MethodEnum, ::Base.Iterators.Pairs{Union{},Union{},Tuple{},NamedTuple{(),Tuple{}}}, ::Type) at /Users/byeon/.julia/packages/GLPK/J1b5G/src/MOI_wrapper.jl:125
 [4] GLPK.Optimizer() at /Users/byeon/.julia/packages/GLPK/J1b5G/src/MOI_wrapper.jl:124
 [5] (::OptimizerFactory)() at /Users/byeon/.julia/packages/JuMP/MsUSY/src/JuMP.jl:99
 [6] #set_optimizer#77(::Bool, ::Function, ::Model, ::OptimizerFactory) at /Users/byeon/.julia/packages/JuMP/MsUSY/src/optimizer_interface.jl:38
 [7] #Model#7 at ./none:0 [inlined]
 [8] Model(::OptimizerFactory) at /Users/byeon/.julia/packages/JuMP/MsUSY/src/JuMP.jl:193
 [9] top-level scope at In[58]:2

In [ ]:
using Pkg; Pkg.add("GLPK")

In [2]:
using JuMP, GLPK
m = Model(with_optimizer(GLPK.Optimizer))

@variable(m, 0 <= x <= 2 )
@variable(m, 0 <= y <= 30 )

@objective(m, Max, 5x + 3*y )

@constraint(m, 1x + 5y <= 3.0 )

JuMP.optimize!(m)
println("Objective value: ", JuMP.objective_value(m))
println("x = ", JuMP.value(x))
println("y = ", JuMP.value(y))


UndefVarError: libglpk not defined

Stacktrace:
 [1] Prob(::Ptr{Nothing}) at /Users/byeon/.julia/packages/GLPK/J1b5G/src/GLPK.jl:224
 [2] Type at /Users/byeon/.julia/packages/GLPK/J1b5G/src/GLPK.jl:357 [inlined]
 [3] (::getfield(GLPK, Symbol("##Optimizer#15#16")))(::Bool, ::GLPK.MethodEnum, ::Base.Iterators.Pairs{Union{},Union{},Tuple{},NamedTuple{(),Tuple{}}}, ::Type) at /Users/byeon/.julia/packages/GLPK/J1b5G/src/MOI_wrapper.jl:125
 [4] GLPK.Optimizer() at /Users/byeon/.julia/packages/GLPK/J1b5G/src/MOI_wrapper.jl:124
 [5] (::OptimizerFactory)() at /Users/byeon/.julia/packages/JuMP/MsUSY/src/JuMP.jl:99
 [6] #set_optimizer#77(::Bool, ::Function, ::Model, ::OptimizerFactory) at /Users/byeon/.julia/packages/JuMP/MsUSY/src/optimizer_interface.jl:38
 [7] #Model#7 at ./none:0 [inlined]
 [8] Model(::OptimizerFactory) at /Users/byeon/.julia/packages/JuMP/MsUSY/src/JuMP.jl:193
 [9] top-level scope at In[2]:2

In [ ]: