With Clojure, how do I generate a random long number? I know Clojure has a rand-int
function but it only works for integer. If a given number is long, I got this repl error:
IllegalArgumentException Value out of range for int: 528029243649 clojure.lang.RT.intCast (RT.java:1205)
We can generate random long values with the nextLong method of the RandomUtils class. nextLong is a static method that can generate random long values. There are two variations of the method: One takes the range as parameters and generates random long values within the specified range.
Thus using the two functions, rand () and srand () we can generate random numbers in C++. The function srand () is used to provide seed for generating random numbers while rand () function generates the next random number in the sequence. => Look For The Entire C++ Training Series Here.
In order to generate Random long type numbers in Java, we use the nextLong() method of the java. util. Random class. This returns the next random long value from the random generator sequence.
The srand(x) function sets the seed of the random number generator algorithm used by the function rand( ). A seed value of 1 is the default setting yielding the same sequence of values as if srand(x) were not used. Any other value for the seed produces a different sequence. srand(time(NULL));
If you take a look at the source of rand-int
(defn rand-int
"Returns a random integer between 0 (inclusive) and n (exclusive)."
[n] (int (rand n)))
You can do a similar thing
(long (rand n)))
Clojure's rand
and rand-int
use java.util.Random
as the underlying random number generator. If your application depends heavily on random numbers, you might want to consider using a higher-quality random number generator written in Java, such as MersenneTwisterFast. This has a nextLong()
method, and it's very easy to use from Clojure. Java's standard class SecureRandom
might be worth considering, too; it's designed for different purposes than the Mersenne Twister. There are other good Java random number generators available. Depends on what you're using the random numbers for. For occasional use of random numbers, java.util.Random
might be just fine. There are additional options mentioned in comments by others.
I'll describe use of MersenneTwisterFast
. Using the other classes I mentioned would be essentially the same, but without the initial steps.
With Leiningen, add something like this to project.clj:
:java-source-paths ["src/java"]
and then put the Java source for MersenneTwisterFast.java in src/java/ec/util. Then you can do this:
(ns my.namespace
(:import [ec.util MersenneTwisterFast]))
(def rng (MersenneTwisterFast. 42)) ; Specify a different seed, e.g. from system time.
(defn next-long [] (.nextLong rng))
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