From: brabuhr@... Date: 2010-06-22T11:19:17+09:00 Subject: Re: [QUIZ] Random Points within a Circle (#234) On Mon, Jun 21, 2010 at 9:12 PM, wrote: > On Mon, Jun 21, 2010 at 7:12 PM, Dave Howell > wrote: >> On Jun 21, 2010, at 15:45 , Caleb Clausen wrote: >>> On 6/19/10, Daniel Moore wrote: >>>> The quiz this week >>>> is to generate random points uniformly distributed within a circle of >>>> a given radius and position. >>> >>> def random_point_in_a_circle(x,y,r) >>>  angle=rand*2*Math::PI >>>  r*=rand >>>  x+=r*Math.sin(angle) >>>  y+=r*Math.cos(angle) >>> >>>  return x,y >>> end >>> >>> 7 lines, 5 minutes, 0 tests or visualizations. Super-easy. >> >> And wrong, unfortunately. You're selecting a random angle, and then a random distance from the center. This will result in way too many points at the center of the circle. > > I whipped up a quick little visualization: Quick hack to animate the above method side by side with an alternate method: require 'java' JFrame = javax.swing.JFrame JPanel = javax.swing.JPanel frame = JFrame.new("Random Points within a Circle") frame.default_close_operation = JFrame::EXIT_ON_CLOSE frame.set_size(700, 400) frame.show class RPwiaC < JPanel def initialize times, *procs super() @times = times @procs = procs end def paintComponent(graphics) super(graphics) @times.times do @procs.each_with_index do |proc, i| x,y = proc.call(200 + (300 * i),200,150) graphics.draw_line(x-1,y-1,x+1,y+1) graphics.draw_line(x-1,y+1,x+1,y-1) end end end end panel = RPwiaC.new( 5000, lambda{|x,y,r| angle=rand*2*Math::PI r*=rand x+=r*Math.sin(angle) y+=r*Math.cos(angle) return x,y }, lambda{|x,y,r| loop { a = x + rand(2*r) - r b = y + rand(2*r) - r d = Math.sqrt((x - a) ** 2 + (y - b) ** 2) return a,b if d < r } } ) frame.add(panel) panel.revalidate loop { panel.repaint }