Struggling_Student
Struggling_Student

Reputation: 464

How to plot Iterations in Julia

I coded a function picircle() that estimates pi.
Now I would like to plot this function for N values.

function Plotpi()
   p = 100 # precision of π
   N = 5
   for i in 1:N
       picircle(p)
   end
end
3.2238805970149254
3.044776119402985
3.1641791044776117
3.1243781094527363
3.084577114427861

Now I am not sure how to plot the function, I tried plot(PP()) but it didn't work

Here I defined picircle:

function picircle(n)
n = n
L = 2n+1

x = range(-1, 1, length=L)
y = rand(L)

center = (0,0)
radius = 1

n_in_circle = 0

for i in 1:L
    if norm((x[i], y[i]) .- center) < radius
        n_in_circle += 1
    end
end

println(4 * n_in_circle / L)
end

Upvotes: 1

Views: 139

Answers (1)

Nils Gudat
Nils Gudat

Reputation: 13800

Your problem is that your functions don't actually return anything:

julia> x = Plotpi()
3.263681592039801
3.0646766169154227
2.845771144278607
3.18407960199005
3.044776119402985

julia> x

julia> typeof(x)
Nothing

The numbers you see are just printed to the REPL, and print doesn't return any value:

julia> x = print(5)
5
julia> typeof(x)
Nothing

So you probably just want to change your function so that it returns what you want to plot:

julia> function picircle(n)
       n = n
       L = 2n+1

       x = range(-1, 1, length=L)
       y = rand(L)

       center = (0,0)
       radius = 1

       n_in_circle = 0

       for i in 1:L
           if norm((x[i], y[i]) .- center) < radius
               n_in_circle += 1
           end
       end

           4 * n_in_circle / L
       end

Then:

julia> x = picircle(100)
3.263681592039801

julia> x
3.263681592039801

So now the value of the function is actually returned (rather than just printed to the console). You don't really need a separate function if you just want to do this multiple times and plot the results, a comprehension will do. Here's an example comparing the variability of the estimate with 100 draws vs 50 draws:

julia> using Plots

julia> histogram([picircle(100) for _ ∈ 1:1_000], label = "100 draws", alpha = 0.5)

julia> histogram!([picircle(20) for _ ∈ 1:1_000], label = "20 draws", alpha = 0.5)

enter image description here

Upvotes: 4

Related Questions