When I try to define range in a for loop when the range is less than 1 I get errors.
For example the following code:
i = linspace(0, 3, 200)
graph = zeros(length(i), 1)
for j in 0:0.015:3
graph[j] = j*cos(j^2)
end
Reports the following error: ERROR: BoundsError()
Why is that?
As in other languages, Julia supports two basic constructs for repeated evaluation: while and for loops. Loops are useful to repeat the same computation multiple times with different values. A typical example is performing operations on array elements.
For loops are used to iterate over a set of values and perform a set of operations that are given in the body of the loop. For loops are used for sequential traversal. In Julia, there is no C style for loop, i.e., for (i = 0; i < n; i++). There is a "for in" loop which is similar to for each loop in other languages.
Loops are just as fast in Julia as they are in Fortran, and a well-written loop is often the single fastest way to implement an algorithm.
'break' keyword in Julia is used to exit from a loop immediately. Whenever the break keyword is executed, the compiler immediately stops iterating over further values and sends the execution pointer out of the loop.
Like StefanKarpinski noted, it is not the for loop (variable) that only takes integers, but the array index. You cannot access the 0.15th element of an array.
How about this:
x = range(0, stop=3, length=200)
y = zeros(length(x))
for i = 1:length(x)
j = x[i]
y[i] = j*cos(j^2)
end
Or even:
x = range(0, stop=3, length=200)
y = zeros(length(x))
for (i, j) in enumerate(x)
y[i] = j * cos(j * j)
end
IMHO, the for loop takes more space without being clearer. Note sure what is considered "julianic", but in the python world I think most people would go for a list comprehension:
tic()
x = linspace(0, 3, 200)
y = [j*cos(j*j) for j in x]
toc()
elapsed time: 0.014455408 seconds
Even nicer to my eyes and faster is:
tic()
x = linspace(0, 3, 200)
y = x.*cos(x.^2)
toc()
elapsed time: 0.000600354 seconds
where the .
in .*
or .^
indicates you're applying the method/function element by element.
Not sure why this is a faster. A Julia expert may want to help us in that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With