Group Abstract Group Abstract

Message Boards Message Boards

0
|
5.5K Views
|
8 Replies
|
1 Total Like
View groups...
Share
Share this post:

Use a random number generator in Select?

Posted 9 years ago

Dear Community,

I tried to use, for example, RandomInteger, in Select as follows:

Block[{x = Range[0, 9], r},
 r = RandomInteger[9];
 {x, Select[x, # == RandomInteger[9] &], r, Select[x, # == r &]}
 ]

But the following is the output I obtained in one run:

{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 7, 9}, 3, {3}}

Also, the output in the first Select could be a list of length 1, 2, or 3, different from one run to another. The second Select, however, always gives correct result. Similar problem was found for RandomReal.

Is a random number generator not allowed as part of the criterion? If not, what are the reasons?

Many thanks,

Chi-Hsiang

POSTED BY: Chi-Hsiang Wang
8 Replies

-- incorrect information removed --

POSTED BY: Szabolcs Horvát

Hi Szabolcs, not sure whether I'm wrong, but according to the Documentation Center, RandomInteger[k] generates integer in the range {0,...,k}. A simulation run of Table[RandomInteger@9, 100] does generate some zero's, but please let me know if this is not the case.

Best,

Chi-Hsiang

POSTED BY: Chi-Hsiang Wang

You are correct, thanks! I removed my post so it won't confuse people.

POSTED BY: Szabolcs Horvát

Thanks, very kind of you!

POSTED BY: Chi-Hsiang Wang

That's it! Many thanks Szabolcs... :-)

I now understand that it's because for comparison to each of the list elements, RandomInteger generates a random number to make the comparison. So for each execution of

Select[Range[0, 9], # == RandomInteger[9] &]

Ten pairs of numbers are compared, with the first number in sequential order and the second randomly generated.

Thanks again, Szabolcs!

POSTED BY: Chi-Hsiang Wang
POSTED BY: Chi-Hsiang Wang

However, I still don't understand why it generates a list of more than one element, and the number of elements can be different from one run to another.

Each time you run RandomInteger[9], you get a different result, right?

If you evaluate 5 == RandomInteger[9] many times, usually you get False, but 1/10 of the time you get True.

Select will evaluate # == RandomInteger[9] for each element of the list. Each time you are comparing with a different and random number.

Try this to see what is happening during the evaluation of this Select:

Select[Range[9], Echo[#, "List element: "] == Echo[RandomInteger[9], "Random number: "] &]
POSTED BY: Szabolcs Horvát
POSTED BY: Gianluca Gorni
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard