How to create random number between (0....1]?
313 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Could someone suggest me how to create random numbers between (0....1]?
0 comentarios
Respuestas (2)
KSSV
el 17 de Ag. de 2021
Read about rand.
iwant = rand(1,10)
5 comentarios
KSSV
el 19 de Ag. de 2021
You put a condition that 1 should be included, so 1 is added...later the number are made random using randsample. You can give a try generating 6 random numbers with 1, you will not get it.
Walter Roberson
el 19 de Ag. de 2021
The user wants to generate from uniform random distribution of floating point numbers in which the source distribution excludes 0 but includes 1, with the possibility of 1 to have equal probability with any other possible output.
The user did not actually state how dense they need the distribution to be. If they would be happy with 2^52 or fewer numbers in the source set, then the calculations can be done fairly easily making use of randi.
If the user wants more 2^53*values in the source set, then it would be necessary to switch to a different representation, not ieee 754 double precision.
If the user wants 2^53 values in the source set, that is possible with a small bit of indirection.
The most commonly used uniform random number generator in MATLAB generates from a source set that is 2^53 - 1 values, one value fewer than is ideal for their needs .
Walter Roberson
el 19 de Ag. de 2021
This takes work to get right.
format long g
N = 6;
temp = typecast(reshape([randi([0 (2^8-1)], 6, N, 'uint8'); randi([0 (2^5-1)], 1, N); zeros(1, N,'uint8')],[],1),'uint64')
iwant = double(temp) / flintmax;
iwant(iwant == 0) = 1
You cannot use rand() because rand() excludes 0 and 1.
You cannot [directly] use randi() because randi has a maximum span of 2^53 - 2
So... what we do is generate a 53 bit binary number and pack it together into a uint64. A 53 bit binary number has 2^53 different possible values, from 0 to 2^53 - 1. We can double() the value because all integers 0 to 2^53 are directly representable in double precision. Then we divide by 2^53 to scale to 0 to (2^53-1)/2^53 . We then check for 0 and if we see it we substitute 1. So now we have a range of 2^53 different numbers that excludes 0 and includes 1.
0 comentarios
Ver también
Categorías
Más información sobre Random Number Generation en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!