On Wed, Feb 29, 2012 at 3:05 AM, Robert Walker <[email protected]> wrote:
> Robert Walker wrote in post #1049376:
> > #!/usr/bin/env ruby
> > require 'set'
> >
> > def random_numbers(n = 500)
> > my_set = Set.new
> > while my_set.size < 500
> > value = Integer((rand * 1) * 1000) / Float(1000)
> > my_set << value
> > end
> > my_set.to_a
> > end
> >
> > puts random_numbers.size
>
> One caveat with this technique: Make sure you build in some "circuit
> breaker" protection code. The more numbers you ask this to generate the
> more rounds it will take to produce the result. Generating 500 unique
> numbers is averaging about 700 rounds. The closer to 1000 you get the
> more rounds it will take. Over 1000 and it will never finish.
>
Another caveat is that the Array contains "Float" objects, while the
original question was "500 unique decimals". Two issues here:
1) if "decimals" are asked in the problem statement, why then do
we serve Floats in the result?
2) The problem is that for uniqueness, we need the '==' operator and
on Floats that represent fractional numbers in the decimal system,
equality is not a stable function (as was discussed many times before ...).
So, in all proposed solutions, I would exchange this line:
> value = Integer((rand * 1) * 1000) / Float(1000)
with this one:
value = rand(1000) / BigDecimal.new(1000)
HTH,
Peter
--
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en.