def usually_one
rand < 0.80 ? 1 : 2
end
Yes, much better. I suppose it is the old programmer in me
instinctively avoiding floating point to save on processor time. A
bit silly when everything has hardware floating point.
Although I prefer Rob’s suggestion as a better example of self
documented code; this is another alternative…
def usually_one
[1,2,2,2,2][rand(5)]
end
Ha! Vindicated
ruby-1.8.7-p302 > begin
ruby-1.8.7-p302 > t=Time.now
ruby-1.8.7-p302 ?> 1000000.times{(rand(100) + 120)/100}
ruby-1.8.7-p302 ?> puts Time.now-t
ruby-1.8.7-p302 ?> end
0.905431
ruby-1.8.7-p302 > begin
ruby-1.8.7-p302 > t=Time.now
ruby-1.8.7-p302 ?> 1000000.times{rand < 0.80 ? 1 : 2}
ruby-1.8.7-p302 ?> puts Time.now-t
ruby-1.8.7-p302 ?> end
1.712769
ruby-1.8.7-p302 > begin
ruby-1.8.7-p302 > t=Time.now
ruby-1.8.7-p302 ?> 1000000.times{ [1,2,2,2,2][rand(5)] }
ruby-1.8.7-p302 ?> puts Time.now-t
ruby-1.8.7-p302 ?> end
1.150481
Here’s my number from within and outside IRB from Mac OS 10.6.6:
ruby-1.9.2-head :001 > begin
ruby-1.9.2-head :002 > t=Time.now
ruby-1.9.2-head :003?> 1000000.times{(rand(100) + 120)/100}
ruby-1.9.2-head :004?> puts Time.now-t
ruby-1.9.2-head :005?> end
from-irb: 0.16657 from-ruby-script: 0.159452
ruby-1.9.2-head :006 > begin
ruby-1.9.2-head :007 > t=Time.now
ruby-1.9.2-head :008?> 1000000.times{rand < 0.80 ? 1 : 2}
ruby-1.9.2-head :009?> puts Time.now-t
ruby-1.9.2-head :010?> end
from-irb: 0.280634 from-ruby-script: 0.150247
ruby-1.9.2-head :011 > begin
ruby-1.9.2-head :012 > t=Time.now
ruby-1.9.2-head :013?> 1000000.times{[1,2,2,2,2][rand(5)]}
ruby-1.9.2-head :014?> puts Time.now-t
ruby-1.9.2-head :015?> end
from-irb: 0.521992 from-ruby-script: 0.35944
-Conrad