I am porting an algorithm from C# to Ruby. This algorithm has one method that returns an int that overflows sometimes.
private static int NextRandom(int n)
{
return 1234567890 * n + 12345;
}
The algorithm takes advantage of the overflow to avoid that the values returned by this function get out of range. However, Ruby behaves differently and it automatically converts the values to Bignum which does not seem to have a limit... How can I achieve the same in Ruby?
If you want a number to wrap at a certain level, you may need to manually limit it:
def next_random(n)
(1234567890 * n + 12345) % 0x7FFFFFFF
end
You can pick whatever limit you want, where that example is 32-bit signed.
I don't think you're able to lock numerical calculations to an arbitrary range.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With