I have a project making calls to random numbers, for example:
I have calls that look like this: (random)
to generate numbers between 0 and 1, also calls like this: (random n)
, to generate numbers within range.
What I want to do is put all the random numbers generated throughout the program in a file.
I have this code:
(require (rename-in racket [random random0]))
(define random-port (open-output-file "random-numbers.rktl" #:exists 'replace))
(define (random x)
(define y (random0 x))
(displayln y random-port)
y)
But this isn't working for just (random
), but rather for (random n
). Is there anyway to make it work for both?
Secondly, where can I put this code if I have multiple modules using random
?
Finally, for some reason, when I write something like this:
(for ([i (in-range 100000)]) (random 10))
The numbers are displayed without a problem in the file,
but when I write this: (random 10)
, I'll get an empty file.
Any help will be really appreciated. Thank you!
It sounds like you're running into a number of issues, and then I have some general advice.
First: you say that it isn't working for (random)
. If I understand you correctly, you'd like to be able to define a function that can be called with either one or zero arguments. There are a number of ways to do this, but the simplest might be to use an optional argument:
#lang racket
(define (my-random [limit #f])
(cond [limit (random limit)]
[else (random)]))
(my-random 13)
(random)
Next, you talk about how you get an empty file when you call (random 10)
. I strongly suspect that the problem is that you're not closing your output port, which is necessary in order to flush the output. You can call (close-output-port random-port)
(although random-port
isn't a great name for this variable...).
Next, though, I have two suggestions that you didn't ask for :).
First, I would not rename the random
function; rather, I would just define my own function with a new name, as I did above. If the issue is that you have a bunch of existing code that uses random
, then you could do the renaming on an import instead.
Second, and even bigger: The standard way of dealing with this problem (I want to see the random numbers that were generated) is not to record all of the generated numbers, but instead just to use a known seed for the random number generated. So, for instance, if you call (random-seed 277819)
, you will always get the same sequence of random numbers. Using random-seed
, you don't need to store the full list of random numbers, you just need to store the initial seed.
The only fly in this ointment is that you do need to know the arguments to random
. So, for instance, you'd need to know that you called random twice with the argument 14, and then once without any argument.