How do I reuse randomly generated numbers?
    2 views (last 30 days)
  
       Show older comments
    
    Dominique Eseinune
 on 15 Aug 2021
  
    
    
    
    
    Edited: Walter Roberson
      
      
 on 15 Aug 2021
            below is the question i have to answer but i dont now how to replicate the results from part 3 to use in part 4. i would also like a different way of genarating the numbers for part 2 than the code provided
1. plots the needle at a random position on the floor considering that the point A of the needle can only be located in the square domain represented in Fig 1. This domain is a square of 20- cm centered at the origin of coordinates (𝑥𝑥 , 𝑦𝑦 ), as shown. The plot should be between -10 and 10 cm in the abscissas and in the ordinates. Use a solid black line to represent the needle and do not try to colour the background. Include a black horizontal line at y = 0. To represent the joint.
(10 marks)
2. uses a FOR loop to create a new plot with 50 needles distributed randomly on the floor. Use the same style and limits of the plot as in the previous section.
 (10 marks)
 3. counts how many of the 50 needles intersected (crossed) the joint of the floor in the previous plot and displays in the Command Window the proportion of the intersecting needles with respect to the total number of needles on the floor.
 (20 marks)
 4. creates a third plot that is the same as the second one but that represents the needles that intersect the joint in red colour and with a linewidth of 2 units, whilst the rest are plotted in black colour and with a linewidth of 1 unit. Use the same limits for the plot as in the previous sections.
for i=1:50
xb=20; yb=20
while (abs(xb)>10)||(abs(yb)>10)
xa=-10+rand()*20;
ya=-10+rand()*20;
theta=rand()*2*pi;
xb=xa+3*cos(theta);
yb=ya+3*sin(theta);
end
if(ya*yb<0)
count=count+1;
end
line([xa, xb], [ya, yb], 'color', 'k')
end
proportion=count/50            
Accepted Answer
  Walter Roberson
      
      
 on 15 Aug 2021
        The question does not require that you "re-use" random numbers. Just store the random numbers in an array when you generate them.
The question does not strictly require that plotting be done within a for loop: if you generated the points within a for loop and did the plotting afterwards then the for loop requirement of question 2 would be satisfied. Questions 3 and 4 do not require that you use for loops: program them however is convenient for you.
8 Comments
  Walter Roberson
      
      
 on 15 Aug 2021
				
      Edited: Walter Roberson
      
      
 on 15 Aug 2021
  
			Change
xb=20; yb=20
to
xb=20; yb=20;
The context is that you then have
while (abs(xb)>10)||(abs(yb)>10)
and when you set xb=20 and yb=20 you are forcing the abs() tests to be true, so you are forcing the loop to execute at least once.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

