Related
I need generate 4 different random numbers, with given range. Like this:
define('min', 3000);
define('range', 6000);
define('diff', 200);
$array[0] = rand(min ,min + range);
$array[1] = rand(min ,min + range);
while(abs($array[0]-$array[1])<diff)
$array[0] = rand(min ,min + range);
$array[2] = rand(min ,min + range);
while((abs($array[2]-$array[0])<diff)
||(abs($array[2]-$array[1])<diff))
$array[2] = rand(min ,min + range);
$array[3] =rand(min ,min + range);
while((abs($array[3]-$array[0])<diff)
||(abs($array[3]-$array[1])<diff)
||(abs($array[3]-$array[2])<diff))
$array[3] = rand(min ,min + range);
Is there any way to optimize this algorithm?
First, you might want to state that you want four random numbers within the same interval but with a minimum distance to each other (as the code does). Your current method involves looping, possibly indefinitely, but probably just for a while, until those numbers are reached.
So long as you only need four random numbers, it does not really matter much if you do it like this. It could be written more generically, allowing the natural extension of drawing more numbers than four, but that will not necessarily make it any faster, even for four numbers.
Assuming you want an upper bound on the time it takes (which your current code only gives with some probability), here is an algorithm that will work (so long as the interval is large enough): Draw a random number N and create two partitions of the interval, one for valid subsequent numbers lower than N and one for valid subsequent numbers higher than N. For each subsequent random number, pick an available partition at random and continue in the same fashion.
This runs in O($n) if you disregard the time count($intervals) takes (it could take O(1), but it gets a little uglier). I cannot say that this algorithm produces numbers with the same probability distribution as your initial algorithm. One thing that suggests that the probability distribution is biased: A partition is chosen at random with equal weight, not based on how large the interval is.
<?php
function random_interval($n, $min, $max, $distance) {
$result = array();
$intervals = array(array($min, $max));
while ($n-- > 0 && count($intervals) > 0) {
// find a random, valid interval
$i = array_rand($intervals);
// extract this interval
$cur_min = $intervals[$i][0];
$cur_max = $intervals[$i][1];
unset($intervals[$i]);
// find a random value within this interval
$r = rand($cur_min, $cur_max);
$result[] = $r;
// if there are valid intervals before and after $r,
// add these intervals back to the set of intervals
if ($r - $distance > $cur_min)
$intervals[] = array($cur_min, $r - $distance);
if ($r + $distance < $cur_max)
$intervals[] = array($r + $distance, $cur_max);
}
return $result;
}
When you generate the nth number, generate it within the range (min, min+range-2*diff*(n-1)), then iterate through the previous numbers, and if the currently generated number is "blocked" by the previous number, add 2*diff to it. Here is the code that does that, but also considers situations where a previously generated number is close to the bounds (in this case, you dont need to add 2*diff to the newly generated number, only a smaller amount):
define('min', 3000);
define('range', 6000);
define('diff', 200);
$numbers = array();
$bounds = array();
for($i = 0; $i<4; $i++){
$min = min;
$range = range;
foreach($bounds as $amount){
$range -= $amount;
}
$rnd = rand($min, $min + $range);
foreach($bounds as $position => $amount){
if($position <= $rnd){
$rnd += $amount;
}
else{
break;
}
}
$numbers[$i] = $rnd;
if($rnd <= min + diff){
$bounds['0'] = $rnd - min + diff;
}
elseif($rnd >= min + range - diff){
$bounds[strval($rnd-diff)] = min + range - $rnd + diff;
}
else{
$bounds[strval($rnd-diff)] = 2 * diff;
}
ksort($bounds);
}
print_r($numbers);
Its not to optimized, it runs in O(n^2log(n)), even thought O(nlog(n)) would be possible.
I need to generate x amount of random odd numbers, within a given range.
I know this can be achieved with simple looping, but I'm unsure which approach would be the best, and is there a better mathematical way of solving this.
EDIT: Also I cannot have the same number more than once.
Generate x integer values over half the range, and for each value double it and add 1.
ANSWERING REVISED QUESTION: 1) Generate a list of candidates in range, shuffle them, and then take the first x. Or 2) generate values as per my original recommendation, and reject and retry if the generated value is in the list of already generated values.
The first will work better if x is a substantial fraction of the range, the latter if x is small relative to the range.
ADDENDUM: Should have thought of this approach earlier, it's based on conditional probability. I don't know php (I came at this from the "random" tag), so I'll express it as pseudo-code:
generate(x, upper_limit)
loop with index i from upper_limit downto 1 by 2
p_value = x / floor((i + 1) / 2)
if rand <= p_value
include i in selected set
decrement x
return/exit if x <= 0
end if
end loop
end generate
x is the desired number of values to generate, upper_limit is the largest odd number in the range, and rand generates a uniformly distributed random number between zero and one. Basically, it steps through the candidate set of odd numbers and accepts or rejects each one based how many values you still need and how many candidates still remain.
I've tested this and it really works. It requires less intermediate storage than shuffling and fewer iterations than the original acceptance/rejection.
Generate a list of elements in the range, remove the element you want in your random series. Repeat x times.
Or you can generate an array with the odd numbers in the range, then do a shuffle
Generation is easy:
$range_array = array();
for( $i = 0; $i < $max_value; $i++){
$range_array[] .= $i*2 + 1;
}
Shuffle
shuffle( $range_array );
splice out the x first elements.
$result = array_slice( $range_array, 0, $x );
This is a complete solution.
function mt_rands($min_rand, $max_rand, $num_rand){
if(!is_integer($min_rand) or !is_integer($max_rand)){
return false;
}
if($min_rand >= $max_rand){
return false;
}
if(!is_integer($num_rand) or ($num_rand < 1)){
return false;
}
if($num_rand <= ($max_rand - $min_rand)){
return false;
}
$rands = array();
while(count($rands) < $num_rand){
$loops = 0;
do{
++$loops; // loop limiter, use it if you want to
$rand = mt_rand($min_rand, $max_rand);
}while(in_array($rand, $rands, true));
$rands[] = $rand;
}
return $rands;
}
// let's see how it went
var_export($rands = mt_rands(0, 50, 5));
Code is not tested. Just wrote it. Can be improved a bit but it's up to you.
This code generates 5 odd unique numbers in the interval [1, 20]. Change $min, $max and $n = 5 according to your needs.
<?php
function odd_filter($x)
{
if (($x % 2) == 1)
{
return true;
}
return false;
}
// seed with microseconds
function make_seed()
{
list($usec, $sec) = explode(' ', microtime());
return (float) $sec + ((float) $usec * 100000);
}
srand(make_seed());
$min = 1;
$max = 20;
//number of random numbers
$n = 5;
if (($max - $min + 1)/2 < $n)
{
print "iterval [$min, $max] is too short to generate $n odd numbers!\n";
exit(1);
}
$result = array();
for ($i = 0; $i < $n; ++$i)
{
$x = rand($min, $max);
//not exists in the hash and is odd
if(!isset($result{$x}) && odd_filter($x))
{
$result[$x] = 1;
}
else//new iteration needed
{
--$i;
}
}
$result = array_keys($result);
var_dump($result);
I am generating some data of latitude and longitude with rand(10000000, 3000000); for example. But I need to calculate distance between two locations, so basically I need to convert my result, for example 22049256 to 22.049256 in order to pass to my function.
How can I achieve this most effectively with using least amount of resources?
TL;DR
I have integer 22049256, needs to be converted to float 22.049256.
Divide by 1M?
22049256 / 1000000 = 22.049256
$foo = rand(10000000, 30000000);
$foo /= 1000000;
echo $foo;
If you always want the decimal after the first two digits, that should do the trick.
<?php
$n = rand(10000000, 3000000);
$len = strlen($n);
$div = pow(10, $len - 2);
$n /= $div;
var_dump($n);
?>
http://codepad.viper-7.com/Nrql15
Basically just dividing by a number made by checking how many characters there are in your original number.
Simplest way would be to treat the number as a string and iterate through it, adding the decimal point at the appropriate position.
$new_number = '';
for($i=0;$i<strlen((string)$number;$i++)
{
if($i == 2)
$new_number .= '.';
$new_number .= substr((string)$number, $i, 1);
}
Edit:
Another possibility is to divide by 1000000 and run number_format to ensure proper decimal places:
$new_number = number_format($number/1000000, 6);
I need to create a random number with x amount of digits.
So lets say x is 5, I need a number to be eg. 35562
If x is 3, then it would throw back something like; 463
Could someone show me how this is done?
You can use rand() together with pow() to make this happen:
$digits = 3;
echo rand(pow(10, $digits-1), pow(10, $digits)-1);
This will output a number between 100 and 999. This because 10^2 = 100 and 10^3 = 1000 and then you need to subtract it with one to get it in the desired range.
If 005 also is a valid example you'd use the following code to pad it with leading zeros:
$digits = 3;
echo str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);
I usually just use RAND() http://php.net/manual/en/function.rand.php
e.g.
rand ( 10000 , 99999 );
for your 5 digit random number
Here is a simple solution without any loops or any hassle which will
allow you to create random string with characters, numbers or even with special symbols.
$randomNum = substr(str_shuffle("0123456789"), 0, $x);
where $x can be number of digits
Eg.
substr(str_shuffle("0123456789"), 0, 5);
Results after a couple of executions
98450
79324
23017
04317
26479
You can use the same code to generate random string also, like this
$randomNum=substr(str_shuffle("0123456789abcdefghijklmnopqrstvwxyzABCDEFGHIJKLMNOPQRSTVWXYZ"), 0, $x);
Results with $x = 11
FgHmqpTR3Ox
O9BsNgcPJDb
1v8Aw5b6H7f
haH40dmAxZf
0EpvHL5lTKr
You can use rand($min, $max) for that exact purpose.
In order to limit the values to values with x digits you can use the following:
$x = 3; // Amount of digits
$min = pow(10,$x);
$max = pow(10,$x+1)-1);
$value = rand($min, $max);
Treat your number as a list of digits and just append a random digit each time:
function n_digit_random($digits) {
$temp = "";
for ($i = 0; $i < $digits; $i++) {
$temp .= rand(0, 9);
}
return (int)$temp;
}
Or a purely numerical solution:
function n_digit_random($digits)
return rand(pow(10, $digits - 1) - 1, pow(10, $digits) - 1);
}
the simplest way i can think of is using rand function with str_pad
<?php
echo str_pad(rand(0,999), 5, "0", STR_PAD_LEFT);
?>
In above example , it will generate random number in range 0 to 999.
And having 5 digits.
function random_numbers($digits) {
$min = pow(10, $digits - 1);
$max = pow(10, $digits) - 1;
return mt_rand($min, $max);
}
Tested here.
rand(1000, 9999); works more faster than x4 times rand(0,9);
benchmark:
rand(1000, 9999) : 0.147 sec.
rand(0,9)x4 times : 0.547 sec.
both functions was running in 100000 iterations to make results more explicit
Well you can use as simple php function mt_rand(2000,9000) which can generate a 4 digit random number
mt_rand(2000,9000)
You can generate any x-digit random number with mt_rand() function.
mt_rand() is faster than rand().
Syntax : mt_rand() or mt_rand($min , $max).
Example : <?php echo mt_rand(); ?>
read more
do it with a loop:
function randomWithLength($length){
$number = '';
for ($i = 0; $i < $length; $i++){
$number .= rand(0,9);
}
return (int)$number;
}
rand or mt_rand will do...
usage:
rand(min, max);
mt_rand(min, max);
function random_number($size = 5)
{
$random_number='';
$count=0;
while ($count < $size )
{
$random_digit = mt_rand(0, 9);
$random_number .= $random_digit;
$count++;
}
return $random_number;
}
Following is simple method to generate specific length verification code. Length can be specified, by default, it generates 4 digit code.
function get_sms_token($length = 4) {
return rand(
((int) str_pad(1, $length, 0, STR_PAD_RIGHT)),
((int) str_pad(9, $length, 9, STR_PAD_RIGHT))
);
}
echo get_sms_token(6);
this simple script will do
$x = 4;//want number of digits for the random number
$sum = 0;
for($i=0;$i<$x;$i++)
{
$sum = $sum + rand(0,9)*pow(10,$i);
}
echo $sum;
This is another simple solution to generate random number of N digits:
$number_of_digits = 10;
echo substr(number_format(time() * mt_rand(),0,'',''),0,$number_of_digits);
Check it here: http://codepad.org/pyVvNiof
function rand_number_available($already_mem_array,$boundary_min,$boundary_max,$digits_num)
{
$already_mem_array_dim = count($already_mem_array); // dimension of array, that contain occupied elements
// --- creating Boundaries and possible Errors
if( empty($digits_num) ){
$boundary_dim = $boundary_max - $boundary_min;
if($boundary_dim <= 0){
$error = -1; // Error that might happen. Difference between $boundary_max and $boundary_min must be positive
}else{
$error = -2; // Error that might happen. All numbers between, $boundary_min and $boundary_max , are occupied, by $already_mem_array
}
}else{
if($digits_num < 0){ // Error. If exist, $digits_num must be, 1,2,3 or higher
$error = -3;
}elseif($digits_num == 1){ // if 'one-figure' number
$error = -4; // Error that might happen. All 'one-figure' numbers are occupied, by $already_mem_array
$boundary_min = 0;
$boundary_max = 9;
$boundary_dim = $boundary_max-$boundary_min;
}elseif($digits_num == 2){ // if 'two-figure' number
$error = -5; // Error that might happen. All 'two-figure' numbers are occupied, by $already_mem_array
$boundary_min = 10;
$boundary_max = 99;
$boundary_dim = $boundary_max-$boundary_min;
}elseif($digits_num>2){ // if 'X-figure' number. X>2
$error = -6; // Error that might happen. All 'X-figure' numbers are occupied, by $already_mem_array. Unlikely to happen
$boundary_min = pow(10, $digits_num-1); // stepenovanje - graduation
$boundary_max = pow(10, $digits_num)-1;
$boundary_dim = $boundary_max-$boundary_min;
}
}
// -------------------------------------------------------------------
// --- creating response ---------------------------------------------
if( ($already_mem_array_dim <= $boundary_dim) && $boundary_dim>0 ){ // go here only if, there are AVAILABLE numbers to extract, and [difference] $boundary_dim , is positive
do{
$num = rand($boundary_min,$boundary_max);
}while( in_array($num, $already_mem_array) );
$result = $num;
}else{
$result = $error; // Limit that happened
}
return $result;
// -------------------------------------------------------------------
}
This function works perfectly with no repeats and desired number of digits.
$digits = '';
function randomDigits($length){
$numbers = range(0,9);
shuffle($numbers);
for($i = 0; $i < $length; $i++){
global $digits;
$digits .= $numbers[$i];
}
return $digits;
}
You can call the function and pass the number of digits for example:
randomDigits(4);
sample results:
4957 8710 6730 6082 2987 2041 6721
Original script got from this gist
Please not that rand() does not generate a cryptographically secure value according to the docs:
http://php.net/manual/en/function.rand.php
This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int(), random_bytes(), or openssl_random_pseudo_bytes() instead.
Instead it is better to use random_int(), available on PHP 7 (See: http://php.net/manual/en/function.random-int.php).
So to extend #Marcus's answer, you should use:
function generateSecureRandomNumber($digits): int {
return random_int(pow(10, $digits - 1), pow(10, $digits) - 1);
}
function generateSecureRandomNumberWithPadding($digits): string {
$randomNumber = random_int(0, pow(10, $digits) - 1);
return str_pad($randomNumber, $digits, '0', STR_PAD_LEFT);
}
Note that using rand() is fine if you don't need a secure random number.
The following code generates a 4 digits random number:
echo sprintf( "%04d", rand(0,9999));
you people really likes to complicate things :)
the real problem is that the OP wants to, probably, add that to the end of some really big number. if not, there is no need I can think of for that to be required. as left zeros in any number is just, well, left zeroes.
so, just append the larger portion of that number as a math sum, not string.
e.g.
$x = "102384129" . complex_3_digit_random_string();
simply becomes
$x = 102384129000 + rand(0, 999);
done.
Is there any slick way to round down to the nearest significant figure in php?
So:
0->0
9->9
10->10
17->10
77->70
114->100
745->700
1200->1000
?
$numbers = array(1, 9, 14, 53, 112, 725, 1001, 1200);
foreach($numbers as $number) {
printf('%d => %d'
, $number
, $number - $number % pow(10, floor(log10($number)))
);
echo "\n";
}
Unfortunately this fails horribly when $number is 0, but it does produce the expected result for positive integers. And it is a math-only solution.
Here's a pure math solution. This is also a more flexible solution if you ever wanted to round up or down, and not just down. And it works on 0 :)
if($num === 0) return 0;
$digits = (int)(log10($num));
$num = (pow(10, $digits)) * floor($num/(pow(10, $digits)));
You could replace floor with round or ceil. Actually, if you wanted to round to the nearest, you could simplify the third line even more.
$num = round($num, -$digits);
If you do want to have a mathy solution, try this:
function floorToFirst($int) {
if (0 === $int) return 0;
$nearest = pow(10, floor(log($int, 10)));
return floor($int / $nearest) * $nearest;
}
Something like this:
$str = (string)$value;
echo (int)($str[0] . str_repeat('0', strlen($str) - 1));
It's totally non-mathy, but I would just do this utilizing sting length... there's probably a smoother way to handle it but you could acomplish it with
function significant($number){
$digits = count($number);
if($digits >= 2){
$newNumber = substr($number,0,1);
$digits--;
for($i = 0; $i < $digits; $i++){
$newNumber = $newNumber . "0";
}
}
return $newNumber;
}
A math based alternative:
$mod = pow(10, intval(round(log10($value) - 0.5)));
$answer = ((int)($value / $mod)) * $mod;
I know this is an old thread but I read it when looking for inspiration on how to solve this problem. Here's what I came up with:
class Math
{
public static function round($number, $numberOfSigFigs = 1)
{
// If the number is 0 return 0
if ($number == 0) {
return 0;
}
// Deal with negative numbers
if ($number < 0) {
$number = -$number;
return -Math::sigFigRound($number, $numberOfSigFigs);
}
return Math::sigFigRound($number, $numberOfSigFigs);
}
private static function sigFigRound($number, $numberOfSigFigs)
{
// Log the number passed
$log = log10($number);
// Round $log down to determine the integer part of the log
$logIntegerPart = floor($log);
// Subtract the integer part from the log itself to determine the fractional part of the log
$logFractionalPart = $log - $logIntegerPart;
// Calculate the value of 10 raised to the power of $logFractionalPart
$value = pow(10, $logFractionalPart);
// Round $value to specified number of significant figures
$value = round($value, $numberOfSigFigs - 1);
// Return the correct value
return $value * pow(10, $logIntegerPart);
}
}
While the functions here worked, I needed significant digits for very small numbers (comparing low-value cryptocurrency to bitcoin).
The answer at Format number to N significant digits in PHP worked, somewhat, though very small numbers are displayed by PHP in scientific notation, which makes them hard for some people to read.
I tried using number_format, though that needs a specific number of digits after the decimal, which broke the 'significant' part of the number (if a set number is entered) and sometimes returned 0 (for numbers smaller than the set number).
The solution was to modify the function to identify really small numbers and then use number_format on them - taking the number of scientific notation digits as the number of digits for number_format:
function roundRate($rate, $digits)
{
$mod = pow(10, intval(round(log10($rate))));
$mod = $mod / pow(10, $digits);
$answer = ((int)($rate / $mod)) * $mod;
$small = strstr($answer,"-");
if($small)
{
$answer = number_format($answer,str_replace("-","",$small));
}
return $answer;
}
This function retains the significant digits as well as presents the numbers in easy-to-read format for everyone. (I know, it is not the best for scientific people nor even the most consistently length 'pretty' looking numbers, but it is overall the best solution for what we needed.)