Welcome! Please see the About page for a little more info on how this works.

0 votes
in Clojure by

The current source code for rand-int is (abridged):

(defn rand-int [n] (int (rand n)))

but this means it can take an arg >Integer/MAX_VALUE and randomly throw overflow exceptions:

(rand-int (* Integer/MAX_VALUE 2.0))
;; => Execution error (ArithmeticException) at java.lang.Math/toIntExact (Math.java:1135).
;;    integer overflow

(rand-int (* Integer/MAX_VALUE 2.0))
;; => 1536421981

etc.
I can see that being able pass a float or double could be useful for "weighting" the range:

(/ (reduce + 0 (map (fn [_] (rand-int 2.5)) (range 1e8)))
   1e8)
;; => 0.79993543

(/ (reduce + 0 (map (fn [_] (rand-int 2)) (range 1e8)))
   1e8)
;; => 0.49998904

but to be honest I think this is probably not immediately apparent to a lot of users.

So, if you want that to allow that behaviour, source code could look something like this:

(defn rand-int [n] (int n) (int (rand n)))

And if you didn't it could look something like this:

(defn rand-int [n] (int (rand (int n))))

But as it currently stands, we don't coerce to an integer, or even check that the input is within Integer range, leading to random overflow exceptions. And random exceptions seem like a bad thing, even for a function called rand-int.

1 Answer

0 votes
by
selected by
 
Best answer

Jira ticket https://clojure.atlassian.net/browse/CLJ-2812 has been created to track this issue.

by
Thanks Jarrod. I'm looking forward to seeing what the core team decides.
...