Search code examples
geometryjulialinear-algebrascatter-plot

How to count scattered points in Julia


I would like to count the scattered red points inside the circle.
my code is:

using PyPlot # Here I define the circle

    k = 100
    ϕ = range(0,stop=2*π,length=k)
    c =  cos.(ϕ)
    d =  sin.(ϕ)

# Here I defined the scattered points with the circle

function scatterpoints(x,y)
    n = 1000
    x = -n:n
    x = x /  n
    y = rand(2*n+1)

    scatter(-x, -y;c="red",s=1)
    scatter(x, y;c="red", s=1)
    plot(c,d)
end

scatterpoints(x,y)

enter image description here

My approach (pseudocode) would be something like this:

using LinearAlgebra
if norm < radius of circle then
amount of points in circle = amount of points in circle + 1
end

Unfortunately I am not sure how to implement this in Julia.


Solution

  • your pretty much here with your pseudocode

    using LinearAlgebra
    
    n = 1000
    N = 2n+1
    
    x = range(-1, 1, length=N)
    y = rand(N)
    
    center = (0,0)
    radius = 1
    
    n_in_circle = 0
    
    for i in 1:N
        if norm((x[i], y[i]) .- center) < radius
            n_in_circle += 1
        end
    end
    
    println(n_in_circle) # 1565
    println(pi*N/4)      # 1571.581724958294