4
votes

I want to generate a large number of random numbers (uniformly distributed on the interval [0,1]). Currently the generation of these random numbers is causing my program to run quite slowly, however the program only needs them to be calculated to around 5 decimal places.

I'm not entirely sure of how MATLAB generates random numbers, but if there is a way of only calculating them to 5 decimal places then it will (hopefully greatly) speed up my program.

Is there a way of doing such a thing?

Thanks very much.

3
You should show the code where you are generating the numbers in a loop, and/or details about how you know it is the RNG slowing your program down. - Jonathon Reinhart
I sincerely doubt that lower-precision random number will speed up anything. However, calculating an array of random numbers once outside of the loop may speed up the code. - Jonas
I agree with @Jonas. Random numbers are not generated by iterative processes where better precision is achieved by doing more rounds (like eg sin and cos). They are based on crazy algorithms devised by cryptographs and the like. One thing that might help, is to change method for the rand seed generator. Don't remember how exactly it's done but search the rand documentation and profile the different types. - KlausCPH
BTW: Have you run the profiler and identified that it is the random number generation that is slow? - Jonas

3 Answers

2
votes

To answer your question, yes, you can generate single precision random numbers, like this:

r = rand(..., 'single');  %Reference: http://www.mathworks.com/help/matlab/ref/rand.html

Single precision numbers have 7 (ish) significant figures when printed as decimal.

To echo some comments above, I don't think this will buy you much performance. The first thing to do if rand is really your slow operation is to batch the calls. That is, instead of:

for ix 1:1000
    y = rand(1,1,'single);
end

use:

yVector = rand(1000,1,'single');
2
votes

As already mentioned, you can instruct RAND to generate numbers directly as single precision, and it's definitely best to generate the numbers in a decent sized chunk. If you still need more performance, and you have Parallel Computing Toolbox and a supported NVIDIA GPU, the gpuArray.rand function can be even faster, especially if you select the philox generator like so:

parallel.gpu.RandStream('Philox4x32-10')
0
votes

Assuming you actually have a proper code layout where you generate a lot of numbers in an array, this can be a solution for low precision. Note that I have not tested but it is mentioned to be fast:

R = randi([0 100000],500,300)/100000

This will generate 150000 low precision random numbers between 0 and 1