Iterating

For Loops


In [2]:
for i = 1:4
    print(" $i ")
end


 1  2  3  4 

In [2]:
x = [10,20,40];
for i = x
    print(" $i ")
end


 10  20  40 

In [3]:
for i in x
    print(" $i ")
end


 10  20  40 

In [4]:
for i  x
    print(" $i ")
end


 10  20  40 

Dictionaries


In [17]:
d = Dict( "foo" => 1, "bar" => 2 );
for i  d
    println("$(i[1]) - $(i[2])")
end


bar - 2
foo - 1

In [20]:
d = Dict( "foo" => 1, "bar" => 2 );
for i  keys(d)
    print(" $i ")
end


 bar  foo 

Comprehensions


In [26]:
x = [2 * i % 3 for i in 1:3]


Out[26]:
3-element Array{Int64,1}:
 2
 1
 0

In [28]:
x = [2 * i * j  for i in 2:3 , j in 1:5]


Out[28]:
2×5 Array{Int64,2}:
 4   8  12  16  20
 6  12  18  24  30

While Loops


In [2]:
i = 0;
while i < 3
    print("yay! "); i=i+1;
end


yay! yay! yay! 

Conditionals


In [3]:
x = 1;
if x > 2
    print("Great")
else
    print("Small")
end


Small

In [5]:
x = 3
x > 2 && print("Hello");
x > 4 && print("World");


Hello

In [7]:
x > 4 || print(":-)");


:-)

Excercises

Task 1

Calculate an approximation of $\pi$ using the "shotgun" approach from https://arxiv.org/abs/1404.1499 . Due to high risks involved with using actual shotguns, substitute the shotgun with the rand function. How many "shots" do you need to achieve an accuracy of 4 digits?


In [27]:
n = 10000000;
k = 1;
for i = 1:n
    x = rand(2);
    if norm(x) <= 1
        k = k + 1;
    end
end
k/n*4


Out[27]:
3.14141

Task 2

Another approach for approximating π is to evaluate the sum $$ \pi \approx \pi_n = \sqrt{12} \sum_{k=0}^n \frac{(-3)^{-k}}{2k+1} $$ Determine the smallest value for $n$ such that $|\pi - \pi_n| < 10^{-15}$.


In [35]:
x = 0;
k = 0;
while abs(x-pi) >= 1e-15
    x = x + sqrt(12)*(-3.0)^-k / (2k+1)
    k = k + 1;
end
k-1


Out[35]:
28

Task 3

Solve the first problem of project Euler, see https://projecteuler.net/problem=1 .


In [41]:
s = 0;
for i = 1:999
    if i % 3 == 0 || i % 5 == 0
        s = s + i
    end
end
s


Out[41]:
233168