0

If Xm~uniform(-25,25),Ym~uniform(-25,25) and r~uniform(0,25), θ~uniform(0,2π) and Xf=rcosθ, Yf=rsinθ.

I want to use a for loop to create 5000 independent variables of point (Xm,Ym) and (Xf,Yf) then calculate the distance between the two points. i know how to calculate the distance between points but creating 5000 realisations of (Xm,Ym) and (Xf,Yf) I am finding tricky. here is my attempt:

Now for Xf,Yf I took a similar approach to Xm,Ym

for (i in 1:5000) { res=c() repeat{ Xm=runif(1,min=-25,max=25) Ym=runif(1,min=-25,max=25) if(Xm**2+Ym**2<=25**2) res=rbind(res,data.frame(Xm,Ym)) break { res=rbind(res,data.frame(Xm,Ym)) } for (i in 1:5000) { res=c() repeat{ R=runif(1,min=0,max=25) 0=runif(1,min=0,max=2*pi) Xf=Rcos(0) Yf=Rsin(0) Yf=runif(1,min=-25,max=25) if(Xf**2+Yf**2<=25**2) res=rbind(res,data.frame(Xf,Yf)) break { res=rbind(res,data.frame(Xf,Yf)) } D=sqrt((Xm-Xf)**2+(Ym-Yf)**2)) 
1
  • Do you really need it to be a loop? You can use sample() to get 5000 points of Xm or in the same runif(n=5000) Commented Mar 19, 2020 at 3:24

1 Answer 1

1

Here is an approach without loop:

# Yours data set.seed(9) # Just for reprodutibility npoints = 5000 # Vectors with 5000 points Xm=runif(n = npoints,min=-25,max=25) Ym=runif(n = npoints,min=-25,max=25) theta = runif(n = npoints, min = 0, max = 2*pi) R = runif(n = npoints,min = 0, max = 25) Xf = R*cos(theta) Yf = R*sin(theta) D = sqrt((Xm-Xf)^2+(Ym-Yf)^2) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.