php random float between
Generating random results by weight in PHP?
I know how to generate a random number in PHP but lets say I want a random number between 1-10 but I want more 3,4,5’s then 8,9,10’s. How is this possible? I would post what I have tried but honestly, I don’t even know where to start.
13 Answers 13
Based on @Allain’s answer/link, I worked up this quick function in PHP. You will have to modify it if you want to use non-integer weighting.
For an efficient random number skewed consistently towards one end of the scale:
eg. in PHP (untested):
This tutorial walks you through it, in PHP, with multiple cut and paste solutions. Note that this routine is slightly modified from what you’ll find on that page, as a result of the comment below.
A function taken from the post:
Plain and fair. Just copy/paste and test it.
Edit: Added missing bracket at the end.
You can use weightedChoice from Non-standard PHP library. It accepts a list of pairs (item, weight) to have the possibility to work with items that can’t be array keys. You can use pairs function to convert array(item => weight) to the needed format.
In this example, 2-5 will appear 3 times more often than 7-10.
Since I used IainMH’s solution, I may as well share my PHP code:
It’s based on the same algorithm mentioned in Brad’s and Allain’s answers, and is optimized for speed, unit-tested for uniform distribution, and supports elements of any PHP type.
Using it is simple. Instantiate it:
Then add elements as an array of weighted values (only if your elements are strings or integers):
Then get a random element:
The probability of getting one of the elements depends on its associated weight. The only restriction is that weights must be integers.
Many of the answers on this page seem to use array bloating, excessive iteration, a library, or a hard-to-read process. Of course, everyone thinks their own baby is the cutest, but I honestly think my approach is lean, simple and easy to read/modify.
Per the OP, I will create an array of values (declared as keys) from 1 to 10, with 3, 4, and 5 having double the weight of the other values (declared as values).
If you are only going to make one random selection and/or your array is relatively small* (do your own benchmarking to be sure), this is probably your best bet:
This approach involves no array modification and probably won’t need to iterate the entire array (but may).
On the other hand, if you are going to make more than one random selection on the array and/or your array is sufficiently large* (do your own benchmarking to be sure), restructuring the array may be better.
The cost in memory for generating a new array will be increasingly justified as:
The new array requires the replacement of «weight» with a «limit» for each value by adding the previous element’s weight to the current element’s weight.
Creates this array:
This approach is brilliant because isset() is very fast and the maximum number of isset() calls in the while loop can only be as many as the largest weight (not to be confused with limit) in the array. For this case, maximum iterations = 2!
THIS APPROACH NEVER NEEDS TO ITERATE THE ENTIRE ARRAY
Random Float between 0 and 1 in PHP
How does one generate a random float between 0 and 1 in PHP?
13 Answers 13
You may use the standard function: lcg_value().
Here’s another function given on the rand() docs:
Example from documentation :
or use a bigger number if you want more digits after decimal point
example:
This question asks for a value from 0 to 1. For most mathematical purposes this is usually invalid albeit to the smallest possible degree. The standard distribution by convention is 0 >= N (int)(random_float() * 10) would return a value from 0 to 9 with an equal chance of each value. If in one in a billion times it can return 1 then very rarely it will return 10 instead.
Some people would fix this after the fact (to decide that 10 should be 9). Multiplying it by 2 should give around a
50% chance of 0 or 1 but will also have a
0.000000000465% chance of returning a 2 like in Bender’s dream.
Saying 0 to 1 as a float might be a bit like mistakenly saying 0 to 10 instead of 0 to 9 as ints when you want ten values starting at zero. In this case because of the broad range of possible float values then it’s more like accidentally saying 0 to 1000000000 instead of 0 to 999999999.
With 64bit it’s exceedingly rare to overflow but in this case some random functions are 32bit internally so it’s not no implausible for that one in two and a half billion chance to occur.
The standard solutions would instead want to be like this:
There can also be small usually insignificant differences in distribution, for example between 0 to 9 then you might find 0 is slightly more likely than 9 due to precision but this will typically be in the billionth or so and is not as severe as the above issue because the above issue can produce an invalid unexpected out of bounds figure for a calculation that would otherwise be flawless.
Java’s Math.random will also never produce a value of 1. Some of this comes from that it is a mouthful to explain specifically what it does. It returns a value from 0 to less than one. It’s Zeno’s arrow, it never reaches 1. This isn’t something someone would conventionally say. Instead people tend to say between 0 and 1 or from 0 to 1 but those are false.
This is somewhat a source of amusement in bug reports. For example, any PHP code using lcg_value without consideration for this may glitch approximately one in a couple billion times if it holds true to its documentation but that makes it painfully difficult to faithfully reproduce.
This kind of off by one error is one of the common sources of «Just turn it off and on again.» issues typically encountered in embedded devices.
mt_rand
(PHP 4, PHP 5, PHP 7, PHP 8)
mt_rand — Генерирует случайное значение методом с помощью генератора простых чисел на базе Вихря Мерсенна
Описание
Список параметров
Необязательный параметр: минимальное значение случайного числа (по умолчанию: 0)
Необязательный параметр: максимальное значение случайного числа (по умолчанию: mt_getrandmax() )
Возвращаемые значения
Список изменений
Примеры
Пример #1 Пример использования mt_rand()
Результатом выполнения данного примера будет что-то подобное:
Примечания
Смотрите также
User Contributed Notes 24 notes
i wanted to spot out the big difference between rand and mt_rand when producing images using randomness as noise.
for example this is a comparation between rand and mt_rand on a 400×400 pixel png: http://oi43.tinypic.com/vwtppl.jpg
code:
( «Content-type: image/png» );
$sizex = 800 ;
$sizey = 400 ;
(rand is on the left, mt_rand on the right)
mt_rand is not calculated by Mersenne Twister.
a better (and likely faster) way to generate a random 6-digit hex string:
A nifty function to generate pretty coupon codes. This will generate unique coupon codes and you don’t have to do a database check whether the code already exists.
To quickly build a human-readable random string for a captcha per example :
To reiterate the message about *not* using mt_rand() for anything security related, here’s a new tool that has been just posted that recovers the seed value given a single mt_rand() output:
Tested over 100’000 iterations, with none/various/random arguments, mt_rand is always 3% slower than rand().
Another good way to get a random float is to divide the result of mt_rand.
Let’s say we want a float between 0.75 and 1.25.
Another graphical comparison of rand() and mt_rand(). It effectively draws a graph showing how the last generated number affects the next by plotting the numbers in consecutive pairs against each other.
( «Content-type: image/png» );
$sizex = 800 ;
$sizey = 800 ;
Another generic random string function, but very small and fast.
If you need some pseudorandom bits for security or cryptographic purposes (e.g.g., random IV for block cipher, random salt for password hash) mt_rand() is a poor source. On most Unix/Linux and/or MS-Windows platforms you can get a better grade of pseudorandom bits from the OS or system library, like this:
// get 128 pseudorandom bits in a string of 16 bytes
A class to generate 99.5% unqiue strings. I found that there is only one or two characters common between two subsequent strings.
public function getRand () <
public function getPrevRand () <
With PHP 5.3.3, we’re seeing odd behavior on 32 bit Linux.
The moral? On 32 bit systems, be careful about crossing the signed number boundary, 0x7FFFFFFF.
Allows characters 0-9, a-z
Weighted (and tested) ok.
rand() comes from the libc, and mt_rand() is internal to PHP. So the differences vary with their respective versions.
On a 64b Debian Stretch with PHP 5.6.21, there is no visible difference: http://oi64.tinypic.com/2nkqas6.jpg
This image compares the two functions. In the top half with random points, in the lower half with random intensity on each point. This is totally different from what was obtained 4 years ago in another note, with an unknown environment.
Here is the code for this visual comparison.
= 400 ;
$sizey = 400 ;
Fast, pseudo-random binary data generation using mt_rand():
mt_rand function returns just a whole numbers. If you want a random float, then here’s an elegant way:
performance: for a repetitive task, it’s much faster not to use the limit parameters, as shown below. just use the % operator.
Php random float between
(PHP 4, PHP 5, PHP 7, PHP 8)
rand — Generate a random integer
Description
Note: On some platforms (such as Windows), getrandmax() is only 32767. If you require a range larger than 32767, specifying min and max will allow you to create a range larger than this, or consider using mt_rand() instead.
Parameters
The lowest value to return (default: 0)
The highest value to return (default: getrandmax() )
Return Values
Changelog
Examples
Example #1 rand() example
The above example will output something similar to:
Notes
See Also
User Contributed Notes 39 notes
quick way to generate randomish numbers and simple strings.
no messing around with functions, so you can just pop the line into the middle of your existing code.
not the most perfect for sure, but ok for plenty of situations.
?>
hope someone finds it useful for somthing.
I also enjoy making one-liners.
Examples:
rand_chars(«ABCEDFG», 10) == GABGFFGCDA
rand_chars(«ABCEDFG», 10, TRUE) == CBGFAEDFEC
Don’t forget, it’s faster to use bitwise operations when you need a random number that’s less than some power of two. For example,
Since many people (myself included) come to this page looking for a way to do a random string, I present a way that uses arrays and shuffle() instead of rand(). This also has the effect of not repeating any characters in the value set.
If you are looking for generate a random expression, like password with alphanumeric or any other character, use this function:
//Here you specify how many characters the returning string must have
echo GeraHash ( 30 );
?>
Random integers with normal distribution,
it’s not scientifically approved, but worked for me.
isn’t this just a simpler way of making a random id for somthing? I mean i know that there is a very slight chance that a duplicate could be made but its a very, very, very small chance, nearly impossible.
and if you don’t want it the md5 can be removed, I’ve just added it as a prefer it there 🙂
I have made this example to generate random number with specific length (10).
Generate a random number with pre-defined length PHP
I’m trying to create a function using mt_rand() in order to generate a truly random number, since rand() just isn’t suffice.
The problem is I need to pre-define the length of the number, say I need a 10 digit random number.
Anyway, I’ve been messing around and this is what I’ve come up with:
In theory that should work (as far as I can tell), but it doesn’t. The length is completely random and it also throws out negative values.
11 Answers 11
Unless you have one of those quantum-static thingies, you can’t get a truly random number. On Unix-based OSes, however, /dev/urandom works for «more randomness», if you really need that.
Anyway, if you want an n-digit number, that’s exactly what you should get: n individual digits.
I’m assuming only legitimate numbers, not strings like 00010. Try useing the size of your number to be:
The only one that doesn’t work is when length is 1, a single digit number ‘0’ won’t be a possible value to be returned.
Here is what I’m using:
One line, nice and simple! The number will never start with 0 and allows 0 at any other place.
The first line ensures that no «0» precedes any number, for instance values like 012, 0598. will be discarded, the rest is easy
Use this for strings of a certain length with both letters and numbers. Tested.
You shouldn’t start with the length constraining the random numbers. Rather accumulate a long enough output, then cut it to the right length:
The padding should be there, because even zeros are randomly generated and should be retained.
Assuming you are using a small range and don’t want to generate the same number twice, how about this:
if the environment is local there is no need to make a random number and mt_rand is like rand but four times faster
Seen lot of answers here, for your need I have a small and effective piece of code
Not the answer you’re looking for? Browse other questions tagged php random numbers or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.