nim-random icon indicating copy to clipboard operation
nim-random copied to clipboard

randomInt may fail for large ranges

Open ReneSac opened this issue 8 years ago • 3 comments

In randomIntImpl() there is # We're assuming 0 < max <= int64.high. An assert would be better. It might catch that randomInt(low(int), high(int)) would call randomIntImpl() with too high of a value (if it don't overflows first, I've not checked). Actually, think that ranges up to uint64.high - 2 are probably fine, but I'm not sure.

This needs to be documented at least. Related to this issue

ReneSac avatar Jun 19 '16 22:06 ReneSac

This is an internal function, and the assumption can never be violated on any system supported by Nim as far as I'm aware.

There are two calls to it: with a (converted) Positive which is ≤ int.highint64.high, and with 2^53 < 2^63-1 = int64.high

Feel free to reopen if you have information on the contrary

oprypin avatar Jun 20 '16 03:06 oprypin

Ok, there will be a overflow inside proc randomInt*(rng: var RNG; min, max: int) when max - min > int64.high. So it indeed will not reach randomIntImpl(), but the title remains true, randomInt will fail for large ranges. I can't test because I don't know how to call your library that I instaled via nimble, as "import random" imports the std lib random.

ReneSac avatar Jun 20 '16 04:06 ReneSac

I looked at this issue just now and I can tell you the implementation would be really ugly and not worth it in my opinion. It is a big hack just to extent the valid range by one bit. The far better solution if you want random bits in an int64 is to call random.next and cast the result to an int64.

krux02 avatar Nov 14 '18 20:11 krux02