I am trying to generate an array of uniformly distributed floating point values in single precision in MATLAB.
I want to generate all numbers in the range +/- (2-2^-23)*2^127 which represents the range of possible 32-bit floating point numbers based on the IEEE-754 standard. The problem is that only large magnitude numbers are being generated, and I want small magnitude numbers (near and including 0) to be included as well. This is seen if we take the absolute value of all numbers generated and then find the smallest (I have copied the output below the code).
So far I have this code in MATLAB:
numtogenerate = 20000;
% Preallocate for speed
generatednumber(numtogenerate) = 0;
for i = 1:numtogenerate
generatednumber(i) = rand*(2-2^-23)*2^127*2 - 2^127*(2-2^-23);
end
minimum = min(generatednumber)
smallest = min(abs(generatednumber))
maximum = max(generatednumber)
hist(generatednumber)
Here is the output:
minimum =
-3.4026e+038
smallest =
8.4046e+033
maximum =
3.4027e+038
(Why in the name of god and little green apples would you do this in a loop?)
My point is, do it using the capabilities of MATLAB. Learn to use vectors and arrays. Apply operations to an entire array of numbers. This is how a tool like MATLAB shines. Until you do, you might as well be using a lower level language, but without the speed benefits gained from using that lower level tool.
Ok, rant over, so how do we attack this problem?
Generate each number using THREE different random values.
Do it all using vector ops.
Do they cover the entire range? It seems so.
Assuming I got the ranges correct for each part, this should essentially generate every possible value in the desired range.
By the way, these are NOT uniformly distributed numbers, at least NOT in the way that term is usually applied in mathematics.