well this is what i am doing:
$total = (array_sum($odds))+$evens;
$total = str_split($total);
echo 'total[1]: '.$total[1].'<br />';
echo '10-$total[1]: ' . (10-($total[1]));
and the output is:
total[1]: 2
10-$total[1]: 87
my guess is it is being treated as a string, but how do i fix it?
so, what i want to know is
wh does (10-($total[1])); = 87?
Update:
yeah my mistake, a phantom 7,
but can anyone now tell me why:
echo $flybuys.' % '.$check.'<br />';
$res = $flybuys % $check;
echo 'res: '.$res;
outputs:
6014359000000928 % 8
res: 7
The inaccurate modulus result is because 6014359000000928 (~2^52) is beyond the bounds of an int, so PHP interprets it as a float. That implies you have a 32-bit system (PHP data type sizes vary depending on architecture). If you need to do math on large numbers, you can use a library like GMP. E.g.:
$flybuys = gmp_init("6014359000000928");
$res = gmp_mod($flybuys, 8);
Make sure you pass large numbers to GMP as strings.
If it is getting recognized as a string you could try casting it to an int using
(int)$total[1];
To be honest, you could probably cast the $total array into an int right when you do the string split:
(int)$total = ...;
Strings that represent numbers can also be cast into (float), and depending on which version of php you have (double).
Couldn't reproduce this issue:
$total = 2222; // some imaginary number as I don't know your $odds and $evens;
$total = str_split($total);
var_dump($total);
/*
*array(4) {
* [0]=>
* string(1) "2"
* [1]=>
* string(1) "2"
* [2]=>
* string(1) "2"
* [3]=>
* string(1) "2"
*}
*/
var_dump($total[1]);
/*
* string(1) "2"
*/
var_dump((10-($total[1])));
/*
* int(8)
*/
Absolutely the expected behavior...
I added this as an answer because in a comment is not enough space:
If this is the implementation of the algorithm described here i really think that modulo check 6014359000000928 % 8 == 0 shouldn't be there.
For example consider the number with the first 15 digits like that: 6014 3590 0000 062. For that evens is 15, odds is 24, total is 39 and check is 1. Any number modulo 1 is 0. So 6014 3590 0000 0628 is valid as 6014 3590 0000 0620 is or 6014 3590 0000 0627. That doesn't make sense.
I think you have to check the last digit for equality with check. In that case only 6014 3590 0000 0621 would be valid.
Related
I was just goofing around with PHP and I decided to generate some random numbers with PHP_INT_MIN (-9223372036854775808) and PHP_INT_MAX (9223372036854775807). I simply echoed the following:
echo rand(-9223372036854775808, 9223372036854775807);
I kept refreshing to see the numbers generated and to view the randomness of the numbers, as a result I started to notice a pattern emerging. Every 2-4 refreshes 0 appeared and this happened without fail, at one stage I even got 0 to appear 4x in a row.
I wanted to experiment further so I created the following snippet:
<?php
$countedZero = 0;
$totalGen = 250;
for ($i = 1; $i <= $totalGen; $i++) {
$rand = rand(-9223372036854775808, 9223372036854775807);
if ($rand == 0) {
echo $i . ": <font color='red'>" . $rand . "</font><br/>";
$countedZero++;
} else {
echo $i . ": " . $rand . "<br/>";
}
}
echo "0 was generated " . $countedZero . "/" . $totalGen . " times which is " . (($countedZero / $totalGen) * 100) . "%."
?>
this would give me a clear idea of what the generation rate is. I ran 8 tests:
The first 3 tests were using a $totalGen of 250. (3 tests total).
The second 3 tests were using a $totalGen of 1000. (6 tests total).
The third test was just to see what the results would be on a larger number, I chose 10,000. (7 tests total).
The fourth test was the final test, I was intrigued at this point because the last (large number) test got such a high result surprisingly so I raised the stakes and set $totalGen to 500,000. (8th test total).
Results
I took a screenshot of the results. I took the first output, I didn't keep testing it to try and get it to fit a certain pattern:
Test 1 (250)
(1).
(2).
(3).
Test 2 (1000)
(1).
(2).
(3).
Test 3 (10,000)
(1).
Test 4 (500,000)
(1).
From the above results, it is safe to assume that 0 has a very high probability of showing up even when the range of possible numbers is at its maximum. So my question is:
Is there a logical reason to why this is happening?
Considering how many numbers it can choose from why is 0 a recurring number?
Note Test 8 was originally going to be 1,000,000 but it lagged out quite badly so I reduced it to 500,000 if someone could test 1,000,000 and show the results by editing the OP it would be much appreciated.
Edit 1
As requested by #maiorano84 I used mt_rand instead of rand and these were the results.
Test 1 (250)
(1).
(2).
(3).
Test 2 (1000)
(1).
(2).
(3).
Test 3 (10,000)
(1).
Test 4 (500,000)
(1).
The results as you can see show that 0 still has a high probability of showing up. Also using the function rand provided the lowest result.
Update
It seems that in PHP7 when using the new function random_int it fixes the issue.
Example PHP7 random_int
https://3v4l.org/76aEH
This is basically an example of how someone wrote a bad rand() function. When you specify the min/max range in rand(), you hit a part of PHP's source that just results in imperfect distribution in the PRNG.
Specifically lines 44-45 of php_rand.h in php-src, which is the following macro:
#define RAND_RANGE(__n, __min, __max, __tmax) \
(__n) = (__min) + (zend_long) ((double) ( (double) (__max) - (__min) + 1.0) * ((__n) / ((__tmax) + 1.0)))
From higher up the call stack (lines 300-302 in rand.c of php-src):
if (argc == 2) {
RAND_RANGE(number, min, max, PHP_RAND_MAX);
}
RAND_RANGE being the macro defined above. By removing the range parameters by just calling rand() instead of rand(-9223372036854775808, 9223372036854775807) you will get even distribution again.
Here's a script to demonstrate the effects...
function unevenRandDist() {
$r = [];
for ($i = 0; $i < 10000; $i++) {
$n = rand(-9223372036854775808,9223372036854775807);
if (isset($r[$n])) {
$r[$n]++;
} else {
$r[$n] = 1;
}
}
arsort($r);
// you should see 0 well above average in the top 10 here
var_dump(array_slice($r, 0, 10));
}
function evenRandDist() {
$r = [];
for ($i = 0; $i < 10000; $i++) {
$n = rand();
if (isset($r[$n])) {
$r[$n]++;
} else {
$r[$n] = 1;
}
}
arsort($r);
// you should see the top 10 are about identical
var_dump(array_slice($r, 0, 10)); //
}
unevenRandDist();
evenRandDist();
Sample Output I Got
array(10) {
[0]=>
int(5005)
[1]=>
int(1)
[2]=>
int(1)
[3]=>
int(1)
[4]=>
int(1)
[5]=>
int(1)
[6]=>
int(1)
[7]=>
int(1)
[8]=>
int(1)
[9]=>
int(1)
}
array(10) {
[0]=>
int(1)
[1]=>
int(1)
[2]=>
int(1)
[3]=>
int(1)
[4]=>
int(1)
[5]=>
int(1)
[6]=>
int(1)
[7]=>
int(1)
[8]=>
int(1)
[9]=>
int(1)
}
Notice the inordinate difference in the number of times 0 shows up in the first array vs. the second array. Even though technically they are both generating random numbers within the same exact range of PHP_INT_MIN to PHP_INT_MAX.
I guess you could blame PHP for this, but it's important to note here that glibc rand is not known for generating good random numbers (regardless of crypto). This problem is known in glibc's implementation of rand as pointed out by this SO answer
I took a quick look at your script and ran it through the command line. The first thing I had noticed is that because I was running a 32-bit version of PHP, my Integer Minimum and Maximum were different from yours.
Because I was using your original values, I was actually getting 0 100% of the time. I resolved this by modifying the script like so:
$countedZero = 0;
$totalGen = 1000000;
for ($i = 1; $i <= $totalGen; $i++) {
$rand = rand(~PHP_INT_MAX, PHP_INT_MAX);
if ($rand === 0) {
//echo $i . ": <font color='red'>" . $rand . "</font><br/>";
$countedZero++;
} else {
//echo $i . ": " . $rand . "<br/>";
}
}
echo "0 was generated " . $countedZero . "/" . $totalGen . " times which is " . (($countedZero / $totalGen) * 100) . "%.";
I was able to confirm that each test would yield just shy of a 50% hit rate for 0.
Here's the interesting part, though:
$rand = rand(~PHP_INT_MAX+1, PHP_INT_MAX-1);
Altering the range to these values causes the likelihood of zero coming up to plummet to an average of 0.003% (after 8 tests). The weird part was that after checking the value of $rand that was not zero, I was seeing many values of 1, and many random negative numbers. No positive numbers greater than 1 were showing up.
After changing the range to the following, I was able to see consistent behavior and more randomization:
$rand = rand(~PHP_INT_MAX/2, PHP_INT_MAX/2);
Here's what I'm pretty sure is happening:
Because you're dealing with a range here, you have to take into account the difference between the minimum and the maximum, and whether or not PHP can support that value.
In my case, the minimum that PHP is able to support is -2147483648, the maximum 2147483647, but the difference between them actually ends up being 4294967295 - a much larger number than PHP can store, so it truncates the maximum in order to try to manage that value.
Ultimately, if the difference of your minimum and maximum exceeds the PHP_INT_MAX constant, you're going to see unexpected behavior.
I am extracting information from a certificate using php and whilst the data is returned okay, there is one particular value "SerialNumber" which is being returned in what seems to be a different number format not sure what it is..
As an example, the actual format I am expecting to receive is:
58 ce a5 e3 63 51 b9 1f 49 e4 7a 20 ce ff 25 0f
However, what I am actually getting back is this:
118045041395046077749311747456482878735
Here is my php to perform the lookup:
$serial = $cert['tbsCertificate']['serialNumber'];
I have tried doing a few different conversions but none of them came back with the expected format.
Sample of a typical certificate serialnumber field..
VAR DUMP
["version"]=>
string(2) "v3"
["serialNumber"]=>
object(Math_BigInteger)#5 (6) {
["value"]=>
string(39) "118045041395046077749311747456482878735"
["is_negative"]=>
bool(false)
["generator"]=>
string(7) "mt_rand"
["precision"]=>
int(-1)
["bitmask"]=>
bool(false)
["hex"]=>
NULL
Your SerialNumber is a Math_BigInteger object as the var_dump shows.
Use the toHex method to retrieve the contained number in a hexadecimal format.
See reference on PEAR website.
$serial = $cert['tbsCertificate']['serialNumber'];
$valueInHex = $serial->toHex();
Note: 118045041395046077749311747456482878735 in decimal format equals to 58CEA5E36351B91F49E47A20CEFF250F in hexadecimal format. You may easily check that with an online converter like this.
Here is alternative solution to convert decimal number to hexadecimal format without using external libraries.
$dec = '118045041395046077749311747456482878735';
// init hex array
$hex = array();
while ($dec) {
// get modulus // based on docs both params are string
$modulus = bcmod($dec, '16');
// convert to hex and prepend to array
array_unshift($hex, dechex($modulus));
// update decimal number
$dec = bcdiv(bcsub($dec, $modulus), 16);
}
// array elements to string
echo implode('', $hex);
And the output of the code ... Online Demo
58cea5e36351b91f49e47a20ceff250f
You can also use string concatenation instead of array prepend. Hope this helps. Thanks!
This question already has answers here:
Is floating point math broken?
(31 answers)
PHP integer rounding problems
(5 answers)
Closed 8 years ago.
I am trying to get the first decimal place of a float number as an integer by subtracting the integer part, multiplying the remainder with 10 and then casting the result to int or using intval(). I noticed that the result for numbers with x.1 is correctly 1 as float, but after converting it to integer, it becomes sometimes 0, sometimes 1.
I tried to test it with numbers from 1.1 to 9.1:
for ($number = 1; $number < 10; $number++) {
$result = 10 * ($number + 0.1 - $number);
echo "<br/> number = " . ($number + 0.1) . ", result: ";
var_dump($result);
$result_int = intval($result);
var_dump($result_int);
}
Starting with 4.1 as input, the 1 oddly gets converted to 0:
number = 1.1, result: float(1) int(1)
number = 2.1, result: float(1) int(1)
number = 3.1, result: float(1) int(1)
number = 4.1, result: float(1) int(0)
number = 5.1, result: float(1) int(0)
number = 6.1, result: float(1) int(0)
number = 7.1, result: float(1) int(0)
number = 8.1, result: float(1) int(0)
number = 9.1, result: float(1) int(0)
Why at 4.1? That doesn't make any sense to me. Can anyone give me a hint what I am doing wrong?
PS: also tested at http://ideone.com/hr7M0A
You are seeing these results because floating point arithmetic is not perfectly accurate.
Instead of trying to manually get the first decimal point use fmod:
$result = substr(fmod($number, 1) * 10, 0, 1)
My php is a bit rusty, so my syntax in probably off, but shouldn't it be simpler to convert to string and take the rightmost digit ?
sprintf($Str, "%.1f", $number);
$digit=$Str[strlen($Str)-1]; // Last digit
I have a question.
I am using php to generate a number based on operations that a user has specified
This variable is called
$new
$new is an integer, I want to be able to round $new to a 12 digit number, regardless of the answer
I was thinking I could use
round() or ceil()
but I believe these are used for rounding decimel places
So, I have an integer stored in $new, when $new is echoed out I want for it to print 12 digits. Whether the number is 60 billion or 0.00000000006
If i understand correctly
function showNumber($input) {
$show = 12;
$input = number_format(min($input,str_repeat('9', $show)), ($show-1) - strlen(number_format($input,0,'.','')),'.','');
return $input;
}
var_dump(showNumber(1));
var_dump(showNumber(0.00000000006));
var_dump(showNumber(100000000000000000000000));
gives
string(12) "1.0000000000"
string(12) "0.0000000001"
string(12) "999999999999"
This question already has answers here:
Getting N random numbers whose sum is M
(9 answers)
Closed 1 year ago.
do you know a way to split an integer into say... 5 groups.
Each group total must be at random but the total of them must equal a fixed number.
for example I have "100" I wanna split this number into
1- 20
2- 3
3- 34
4- 15
5- 18
EDIT: i forgot to say that yes a balance would be a good thing.I suppose this could be done by making a if statement blocking any number above 30 instance.
I have a slightly different approach to some of the answers here. I create a loose percentage based on the number of items you want to sum, and then plus or minus 10% on a random basis.
I then do this n-1 times (n is total of iterations), so you have a remainder. The remainder is then the last number, which isn't itself truley random, but it's based off other random numbers.
Works pretty well.
/**
* Calculate n random numbers that sum y.
* Function calculates a percentage based on the number
* required, gives a random number around that number, then
* deducts the rest from the total for the final number.
* Final number cannot be truely random, as it's a fixed total,
* but it will appear random, as it's based on other random
* values.
*
* #author Mike Griffiths
* #return Array
*/
private function _random_numbers_sum($num_numbers=3, $total=500)
{
$numbers = [];
$loose_pcc = $total / $num_numbers;
for($i = 1; $i < $num_numbers; $i++) {
// Random number +/- 10%
$ten_pcc = $loose_pcc * 0.1;
$rand_num = mt_rand( ($loose_pcc - $ten_pcc), ($loose_pcc + $ten_pcc) );
$numbers[] = $rand_num;
}
// $numbers now contains 1 less number than it should do, sum
// all the numbers and use the difference as final number.
$numbers_total = array_sum($numbers);
$numbers[] = $total - $numbers_total;
return $numbers;
}
This:
$random = $this->_random_numbers_sum();
echo 'Total: '. array_sum($random) ."\n";
print_r($random);
Outputs:
Total: 500
Array
(
[0] => 167
[1] => 164
[2] => 169
)
Pick 4 random numbers, each around an average of 20 (with distribution of e.g. around 40% of 20, i.e. 8). Add a fifth number such that the total is 100.
In response to several other answers here, in fact the last number cannot be random, because the sum is fixed. As an explanation, in below image, there are only 4 points (smaller ticks) that can be randomly choosen, represented accumulatively with each adding a random number around the mean of all (total/n, 20) to have a sum of 100. The result is 5 spacings, representing the 5 random numbers you are looking for.
Depending on how random you need it to be and how resource rich is the environment you plan to run the script, you might try the following approach.
<?php
set_time_limit(10);
$number_of_groups = 5;
$sum_to = 100;
$groups = array();
$group = 0;
while(array_sum($groups) != $sum_to)
{
$groups[$group] = mt_rand(0, $sum_to/mt_rand(1,5));
if(++$group == $number_of_groups)
{
$group = 0;
}
}
The example of generated result, will look something like this. Pretty random.
[root#server ~]# php /var/www/dev/test.php
array(5) {
[0]=>
int(11)
[1]=>
int(2)
[2]=>
int(13)
[3]=>
int(9)
[4]=>
int(65)
}
[root#server ~]# php /var/www/dev/test.php
array(5) {
[0]=>
int(9)
[1]=>
int(29)
[2]=>
int(21)
[3]=>
int(27)
[4]=>
int(14)
}
[root#server ~]# php /var/www/dev/test.php
array(5) {
[0]=>
int(18)
[1]=>
int(26)
[2]=>
int(2)
[3]=>
int(5)
[4]=>
int(49)
}
[root#server ~]# php /var/www/dev/test.php
array(5) {
[0]=>
int(20)
[1]=>
int(25)
[2]=>
int(27)
[3]=>
int(26)
[4]=>
int(2)
}
[root#server ~]# php /var/www/dev/test.php
array(5) {
[0]=>
int(9)
[1]=>
int(18)
[2]=>
int(56)
[3]=>
int(12)
[4]=>
int(5)
}
[root#server ~]# php /var/www/dev/test.php
array(5) {
[0]=>
int(0)
[1]=>
int(50)
[2]=>
int(25)
[3]=>
int(17)
[4]=>
int(8)
}
[root#server ~]# php /var/www/dev/test.php
array(5) {
[0]=>
int(17)
[1]=>
int(43)
[2]=>
int(20)
[3]=>
int(3)
[4]=>
int(17)
}
$number = 100;
$numbers = array();
$iteration = 0;
while($number > 0 && $iteration < 5) {
$sub_number = rand(1,$number);
if (in_array($sub_number, $numbers)) {
continue;
}
$iteration++;
$number -= $sub_number;
$numbers[] = $sub_number;
}
if ($number != 0) {
$numbers[] = $number;
}
print_r($numbers);
This should do what you need:
<?php
$tot = 100;
$groups = 5;
$numbers = array();
for($i = 1; $i < $groups; $i++) {
$num = rand(1, $tot-($groups-$i));
$tot -= $num;
$numbers[] = $num;
}
$numbers[] = $tot;
It won't give you a truly balanced distribution, though, since the first numbers will on average be larger.
I think the trick to this is to keep setting the ceiling for your random # generator to 100 - currentTotal
The solution depends on how random you want your values to be, in other words, what random situation you're going to simulate.
To get totally random distribution, you'll have to do 100 polls in which each element will be binded to a group, in symbolic language
foreach i from 1 to n
group[ random(1,n) ] ++;
For bigger numbers, you could increase the selected group by random(1, n/100) or something like that until the total sum would match the n.
However, you want to get the balance, so I think the best for you would be the normal distribution. Draw 5 gaussian values, which will divide the number (their sum) into 5 parts. Now you need to scale this parts so that their sum would be n and round them, so you got your 5 groups.
The solution I found to this problem is a little different but makes makes more sense to me, so in this example I generate an array of numbers that add up to 960. Hope this is helpful.
// the range of the array
$arry = range(1, 999, 1);
// howmany numbers do you want
$nrresult = 3;
do {
//select three numbers from the array
$arry_rand = array_rand ( $arry, $nrresult );
$arry_fin = array_sum($arry_rand);
// dont stop till they sum 960
} while ( $arry_fin != 960 );
//to see the results
foreach ($arry_rand as $aryid) {
echo $arryid . '+ ';
}