Review Request: Convenience KRandom methods
Ingo Klöcker
kloecker at kde.org
Fri Aug 13 19:41:27 BST 2010
> On 2010-08-13 11:03:31, Ivan Cukic wrote:
> > trunk/KDE/kdelibs/kdecore/util/krandom.cpp, line 55
> > <http://reviewboard.kde.org/r/4992/diff/3/?file=33701#file33701line55>
> >
> > As far as the % goes, I'd say it is ok (apart from previous comments)
>
> Ivan Cukic wrote:
> My mistake, it is not :)
>
> Imagine the following:
> random() gives from 0 to 10
> min = 0
> max = 7
>
> this function would give priority to 0 1 and 2
> 0 1 2 3 4 5 6 7 8 9 10
> ______________________
> 0 1 2 3 4 5 6 7 0 1 2
>
> Christoph Feck wrote:
> In other words, there cannot exist any mapping from a uniform random integer distribution in the range [a,b] to a different integer range [d,e] resulting in a uniform distribution.
>
> Since even floats have limited precision in a computer, you cannot solve the problem mathematically correct anyway.
You can solve this problem correctly. Here is a trivial (but terribly inefficient) solution which works for any 0 <= min <= max <= RAND_MAX:
int KRandom::random( int min, int max )
{
while ( true ) {
const int r = random();
if ( min <= r && r <= max )
return r;
}
}
Making this method work for any ints with max <= min + RAND_MAX (e.g. for min = -1 and max = 1) and more efficiently by throwing away at most max - min values in the range [0,RAND_MAX] is left as an exercise for the reader.
- Ingo
-----------------------------------------------------------
This is an automatically generated e-mail. To reply, visit:
http://reviewboard.kde.org/r/4992/#review7029
-----------------------------------------------------------
On 2010-08-12 13:40:52, Sebastian Trueg wrote:
>
> -----------------------------------------------------------
> This is an automatically generated e-mail. To reply, visit:
> http://reviewboard.kde.org/r/4992/
> -----------------------------------------------------------
>
> (Updated 2010-08-12 13:40:52)
>
>
> Review request for kdelibs.
>
>
> Summary
> -------
>
> The KRandom namespace is quite useful. However, applications need to be full of code snippets that calculate a random number in a range. IMHO it makes perfect sense to do this once in the library. Thus, I am proposing this patch to introduce two methods providing random numbers from a range.
> Feel free to improve the implementation. :)
>
>
> Diffs
> -----
>
> trunk/KDE/kdelibs/kdecore/util/krandom.h 1162164
> trunk/KDE/kdelibs/kdecore/util/krandom.cpp 1162164
>
> Diff: http://reviewboard.kde.org/r/4992/diff
>
>
> Testing
> -------
>
>
> Thanks,
>
> Sebastian
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.kde.org/pipermail/kde-core-devel/attachments/20100813/dc90d6f7/attachment.htm>
More information about the kde-core-devel
mailing list