In [2]:
for i = 1:4
print(" $i ")
end
In [2]:
x = [10,20,40];
for i = x
print(" $i ")
end
In [3]:
for i in x
print(" $i ")
end
In [4]:
for i ∈ x
print(" $i ")
end
In [17]:
d = Dict( "foo" => 1, "bar" => 2 );
for i ∈ d
println("$(i[1]) - $(i[2])")
end
In [20]:
d = Dict( "foo" => 1, "bar" => 2 );
for i ∈ keys(d)
print(" $i ")
end
In [26]:
x = [2 * i % 3 for i in 1:3]
Out[26]:
In [28]:
x = [2 * i * j for i in 2:3 , j in 1:5]
Out[28]:
In [2]:
i = 0;
while i < 3
print("yay! "); i=i+1;
end
In [3]:
x = 1;
if x > 2
print("Great")
else
print("Small")
end
In [5]:
x = 3
x > 2 && print("Hello");
x > 4 && print("World");
In [7]:
x > 4 || print(":-)");
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]:
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]:
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]: