go ahead... be a heretic PerlMonks

### Re: Random generator fail

by BillKSmith (Vicar)
 on Dec 06, 2012 at 04:34 UTC ( #1007460=note: print w/replies, xml ) Need Help??

in reply to Random generator fail

Do you want real numbers in the range (1 <= number < 99) on a windows system?

perl -e"print 1 + rand 98, qq(\n) for 1..100"
Bill

Replies are listed 'Best First'.
Re^2: Random generator fail
by Anonymous Monk on Dec 06, 2012 at 13:38 UTC

Ok I have better understanding now, Bill your solutions works great!

@MidLifeXis What is rational for rand to ignore \$_. Appearently you pointing out that, solves my problem by using

```perl -wle "use 5.10.0;  foreach (1..100) { say rand(\$_);};"

1.94992065429688
56.7288208007813
52.1597290039063
18.6995849609375
6.6961669921875
68.6776733398438
65.6177978515625
62.72314453125
52.1324157714844
...

But I think using additional line  { say rand(\$_); is completely un-neccessary. Thank you.

Let's step through this:

```foreach (1..100) {
say rand(\$_);
}
When \$_ is equal to ...
• ... 1, rand(\$_) cannot be larger than 1.
• ... 2, rand(\$_) cannot be larger than 2.
• ... 3, rand(\$_) cannot be larger than 3.
• ... 4, rand(\$_) cannot be larger than 4.
• ... 5, rand(\$_) cannot be larger than 5.
• ... 6, rand(\$_) cannot be larger than 6.

Look at one of my earlier posts on this thread. The documentation for rand states that 0 <= rand(\$x) < \$x if \$x > 0. To accomplish what you are trying to do would require that you do this:

```say 1 + rand(99 - 1) for (1..100)
In my previous node, MAX = 99 and MIN = 1. The 1..100 is the number of iterations you wish to use. If you use rand(\$_), your results will be biased toward the lower end of the counter range.

--MidLifeXis

I agree with bias at lower end. Great, that is pretty much what I was looking for.

Thank you

My rand 98 generates random numbers in the range (0<= number < 98). Adding one to every random number changes the range to (1<=number<99). Using rand \$_ would generate a very different sequence of numbers. In fact, the sample output that you show cannot be the first few numbers as your dots suggest. It is possible that they are the last few numbers.
Bill

```perl -wle "use 5.10.0;   say int foreach (1..100) ;"

Works as rand() should have.

Works as rand() should have.
Either your assumptions are wrong, or the documentation for rand does not match the implementation. Which do you think it is?

--MidLifeXis

This one is better

```perl -wle "use 5.10.0;   say abs foreach (-5..5) ;"
5
4
3
2
1
0
1
2
3
4
5

Create A New User
Node Status?
node history
Node Type: note [id://1007460]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2018-04-26 01:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My travels bear the most uncanny semblance to ...

Results (94 votes). Check out past polls.

Notices?