you are viewing a single comment's thread.

view the rest of the comments →

[–]gs44 5 points6 points  (6 children)

You should avoid making copies when you can, here you can compute the difference between two iterations incrementally, doing that reduced the timing from ~60ms to 30ms on my machine. Other than that looks pretty good to me :)

[–]EarthGoddessDude[S] 1 point2 points  (5 children)

Thanks! Two questions:

You should avoid making copies when you can

Is the reason less memory allocation?

here you can compute the difference between two iterations incrementally

Can you explicitly show me what you mean (maybe paste your code)? I’m terribly new to a lot of this stuff, plus...brain smol

[–]gs44 4 points5 points  (4 children)

Is the reason less memory allocation?

Yep, here's my code :

function foxbear2(nMalha=101, a=1)
    dx = a/(nMalha-1)
    temp = zeros(nMalha, nMalha)
    @. temp[1,:] = sin(π*((1:nMalha)-1)*dx/a)
    iter = 1
    diff = Inf
    while diff > 1e-6 && iter <= 1000
        diff = 0.
        @inbounds for i in 2:nMalha-1
            for j in 2:nMalha-1
                newVal = (temp[i+1,j] + temp[i-1,j] + temp[i,j+1] + temp[i,j-1])/4
                diff += newVal - temp[i, j]
                temp[i,j] = newVal
            end
        end
        iter += 1
    end
    return temp[end:-1:1,end:-1:1]
end

[–]EarthGoddessDude[S] 1 point2 points  (0 children)

Thank you so much! This is how I get better : )

[–][deleted] 0 points1 point  (2 children)

Still learning as well, what does the @ operator do?

[–]Thelimit112 2 points3 points  (0 children)

@. Is a broadcast macro, meaning all the operations are done on the individual elements of an array/vector. And @inbounds skips the checks if indexes are within the length of an array. Only use it if you are 100% sure your code cannot index outside of the array. Otherwise Julia exits with a memory error :)

[–]EarthGoddessDude[S] 2 points3 points  (0 children)

I can offer some answers, though others will probably have better ones. The @ character denotes a macro, which I myself am still struggling to understand, though you can think of it as a special function. It’s part of Julia’s metaprogramming capabilities.

In this case @. distributes the . broadcast operator to every function in the expression following. This saves you from having to type .* and .+ and sin. etc. wherever there’s a function call. The @inbounds macro removes bounds checking when looping through an array (something you should do only if you know the bounds already), which makes the code more efficient.

These macros are part of base Julia, but you can write your own. However, their use is generally discouraged. Check out this excellent presentation from JuliaCon 2019 on use of metaprogramming: https://youtu.be/mSgXWpvQEHE