How can I create an array of a divided number in PHP? - php

I want to create an array in PHP by dividing a number. So for example when I have the number 200 and I divide it through 0,10, I need to get an array with 2k entries of 0,10.
But when I have a division like 233,12 / 0,10, I also need the array but the last possible entry needs to be a bit higher so that it fills the sum up.
Actually I have no code. This is too complex for me. Maybe someone has an idea. I've did everything around this but got really stuck here...
$number = 200;
$divider = 0.10;

So you want to have an array with 2k entries each having the value 0.1 in them?
So something like
$number = 200;
$divider = 0.1;
$totalArraySize = $number / $divider;
$result = [];
$result = array_fill(0, $totalArraySize, $divider);
However to make it slightly bigger in case of (for example) 233,12/0,1 you would simply need to ceil() the $totalArraySize to round it up to the nearest full integer. And to make sure that the last entry has the difference you basicly need to calculate it. You get it by taking what you expect to be the sum and subtract the values you know to be right. So (totalSize - 1) * 0,1 .. would give you in this example 233,1 so the last entry would be then 233,12 - 233,1 = 0,02
$number = 233,12;
$divider = 0.1;
$totalArraySize = ceil($number / $divider);
$wasRoundUp = $number % 1 === 0
$result = [];
$result = array_fill(0, $totalArraySize, $divider);
if ($wasRoundUp)
$result[$totalArraySize] = $number - (($totalArraySize - 1) * 0,1)
Edit: Actually I realised that my logic to see if it was round up was wrong. I cannot rely on modulo 1 division here as 233,1 would be divisible by 0.1 in an even amount. So we need to check if totalArraySize != ($number / divider).
So new code would be
$number = 233,12;
$divider = 0.1;
$totalArraySize = ceil($number / $divider);
$wasRoundUp = $totalArraySize != ($number / $divider);
$result = [];
$result = array_fill(0, $totalArraySize, $divider);
if ($wasRoundUp)
$result[$totalArraySize] = $number - (($totalArraySize - 1) * 0,1)
Edit 2:
To reflect the question in the comment and "fix" an issue with the code here's the new answer. To fill up the last entry it now takes the divider value and not hardcoded 0.1 which would have to be changed correctly. And due to floating point calculations you would need to round the last value to two decimal points. I cannot guarantee if thats the best aproach tho to avoid the floating point rounding issue you might get there
$number = 164.85;
$divider = 0.2;
$totalArraySize = ceil($number / $divider);
$wasRoundUp = $totalArraySize != ($number / $divider);
$result = array_fill(0, $totalArraySize, $divider);
if ($wasRoundUp)
$result[$totalArraySize] = round($number - (($totalArraySize - 1) * $divider), 2);

Related

Round up decimal number for specific decimal places in PHP

I want to round up my variable if it's decimal larger than .3 and if it's lower or equal it will round down, for example if i have 1.34 it will round up to 2, if i have 1.29 it will round down to 1, and if i have 1.3 it will round down to 1. I don't know how to do this precisely, right now i'm using the round basic function like this:
$weight = $weight/1000;
if($weight < 1) $weight = 1;
else $weight = round($weight, 0, PHP_ROUND_HALF_DOWN);
If you manipulate the numbers a bit, you can figure out if the decimals are .3 or higher. You achieve this by flooring the value, and subtract that from the original value. Check if the result of that, multiplied by 10, is greater than 3. If it is, you've got something above x.3.
$number = 1.31;
$int = floor($number);
$float = $number-$int;
if ($float*10 > 3.1)
$result = ceil($number);
else
$result = $int;
echo $result; // 2
Live demo
I made you a little hack, here's the code
$weight = 5088;
$weight = $weight/1000;
if($weight < 1) {
$weight = 1;
} else {
// I get the last number (I treat the $weight as a string here)
$last_number = substr($weight, -1, 1);
// Then I get the precision (floating numbers)
$precision = strlen(substr(strrchr($weight, "."), 1));
// Then I convert it to a string so I can use some helpful string functions
$weight_str = (string) $weight;
// If the last number is less then 3
if ($last_number > 3)
// I change it to 9 I could just change it to 5 and it would work
// because round will round up if then number is 5 or greater
$weight_str[strlen($weight_str) -1] = 9;
}
}
// Then the round will round up if it's 9 or round down if it's 3 or less
$weight = round($weight_str, $precision);
echo $weight;
Maybe something like this function?
function roundImproved($value, $decimalBreakPart = 0.3) {
$whole = floor($value);
$decimal = $value - $whole;
$decimalPartLen = strlen($decimal) - 2;
return (number_format($decimal, $decimalPartLen) <= number_format($decimalBreakPart, $decimalPartLen) ? $whole : ceil($value));
}
Proof:
http://sandbox.onlinephpfunctions.com/code/d75858f175dd819de069a8a05611ac9e7053f07a
You can specify "break part" if you want.

PHP distribute percentage based on total numbers

I'm trying to distribute 100% to total numbers (not equally), it can be done manually but I'm looking for a automatically way in PHP. I had to open calculator and get it done for manual.
What I'm trying to achieve is the result similar to this:
$value = 10000;
$total_numbers = 9
$a1 = $value*0.2;
$a2 = $value*0.175;
$a3 = $value*0.15;
$a4 = $value*0.125;
$a5 = $value*0.1;
$a6 = $value*0.08;
$a7 = $value*0.07;
$a8 = $value*0.05;
$a9 = $value*0.04;
So as you can see, the first variables have more quantity than the later ones, but if you add these, it will be 1 which is 100%. So lets say I have total_numbers=20 then I'll have to re-write it and get a calculator and do it the hard way to accomplish my goal. Is there any way this can be done automatically with a function where I can just tell the total number and it can distribute it to proportions or something?
The first one will always be bigger than rest, then second one bigger than rest but smaller than first, third one being greater than rest but small than first and second, and so on.
function distributeValue($value, $num) {
$parts = $num * ($num + 1) / 2;
$values = [];
for ($i = $num; $i > 1; --$i) {
$values[] = round($value * $i / $parts);
}
$values[] = $value - array_sum($values);
return $values;
}
var_dump(distributeValue(10000, 9));
This works by calculating the $numth triangle number (the number you get by adding all the numbers from 1 to $num) and dividing the total value up into this number of parts.
It then starts by taking $num parts, then $num-1 parts and so on.
Since it's rounding the numbers, the last step is to take the total minus all the other values which is around one part. If you are fine with getting floats instead of ints out, then you can remove the $values[] = $value - array_sum($values); line and change the condition of the for loop to $i > 0.

doing maths with php array based on excel function

I am new to PHP and stackoverflow and try to figure things out for myself before asking but I am having a little trouble doing some maths on an array I have pulled from a database with PHP.
So far I have an array of numbers called $array['sn']
I have created a function in excel that does the maths and works well in excel but I cant figure out a way to do it in PHP.
the excel function is =QUOTIENT(E32,65536)&QUOTIENT(E32-F34*65536,256)&(G33-G35*256)
E32 being the value I start with i.e $sn
F34 being the answer to the first quotient
G35 being the answer to the second quotient
G33 being E32-F34*65536
I want to take a number e.g. 3675177 divide it by 65536 but without the remainder which is 56, then multiply 56 by 65536 which equals 3670016, then find the difference between 3670016 and 3675177 which is 5161. Then divide 5161 by 256 with no remainder which is 20 then multiply 20 by 256 and subtract 5161 which is 41.
The end result from 3675177 should be 562041. I want to do this calculation on every number in the $array['sn'], any help would be appreciated.
The calculation and formatting of the output would be like this:
$n = 3675177;
$const = 65536;
$const2 = 256;
$a = intval($n / $const); // intval returns only the integer part of a number
$x = $n % $const; // $n % $const means "the remainder of $n / $const"
$b = intval($x / $const2);
$c = $x % $const2;
// Two options to handle values of $c < 10:
// if ($c < 10) $c = "0$c";
// $c = str_pad($c, 2, "0", STR_PAD_LEFT);
echo "$a$b$c";
I would recommend using array_map to apply the calculation to your array of values.
There are php arithmetic operations you can use.
I would do something like this:
$initialNumber = //the initial number, wherever you get it from
$entireDivision = ceil($initialNumber/65536)-1;
$remainder = $initialNumber%65536;
$remainderMultiplied = $remainder * 56;
$difference = $initialNumber - $remainderMultiplied;
$differenceDivided = ceil($difference/256)-1;
$differenceMultipliedAndSubstracted = ($differenceDivided * 256) - $difference;
Maybe I used too many variables, this is to be a bit more easy to understand for you. Maybe I did some operation wrong, check it out too. But this is the idea of mathematic operations in php. Maybe you should put this inside a php function with parameters, so your code gets cleaner if you use multiple times.
EDIT: You should put this code inside a function, then run a foreach loop in your array running this function taking as parameter the value of the array position.
$results = array();
foreach ($array['sn'] as $key => $a) {
$b = intval($a / 65536);
$c = ($a - $b * 65536);
$d = intval($c / 256);
$e = $c - $d * 256;
$results[$key] = $b . $d . $e;
}
var_dump($results);

Generating random values and keeping track of their sum

I have more than 200 entries in a database table and I would like to generate a random value for each entry, but in the end, the sum of entries values must equal 100. Is it possible to do this using a for loop and rand() in PHP?
You could simply normalize a set of numbers, like:
$numbers = array();
for ($i = 0; $i < 200; $i += 1) {
$numbers[] = rand();
}
$sum = array_sum($numbers);
// divide $sum by the target sum, to have an instant result, e.g.:
// $sum = array_sum($numbers) / 100;
// $sum = array_sum($numbers) / 42;
// ...
$numbers = array_map(function ($n) use($sum) {
return $n / $sum;
}, $numbers);
print_r($numbers);
print_r(array_sum($numbers)); // ~ 1
demo: http://codepad.viper-7.com/RDOIvX
The solution for your problem is to rand number from 0 to 200 then put in array, then sum the values and divide it by 200 after that. Loop through elements and divide every element by result of previous equatation it will give you the answer
$sum = 0;
$max = 100; //max value to be sumed
$nr_of_records = 200; // number of records that should sum to $max
$arr = array();
for($i=0;$i<$nr_of_records;++$i)
{
$arr[$i] = rand(0,$max);
}
$div = array_sum($arr) / $max;
for($i=0;$i<$nr_of_records;++$i)
{
$arr[$i] /= $div;
echo $arr[$i].'<br>';
}
echo array_sum($arr);
Created living example
How exact has the 100 to be? Just curious, because all hints end at using floating point values, which tend to be inacurate.
I'd propose using fractions... lets say 10000 fractions, each count 1/100 point (10000 * 1/100 = 100 points). Distribute 10000 points to 200 elements, using integers - and be absolutely sure, that the sum of all integers divided by 10000 is 100. There is no need for floats, just think around the corner...
Do a little over/under:
$size = 200;
$sum = 100;
$places = 3;
$base = round($sum/$size, $places);
$values = array_fill(0, $size, $base);
for($i=0; $i<$size; $i+=2) {
$diff = round((rand()/getrandmax()) * $base, $places);
$values[$i] += $diff;
$values[$i+1] -= $diff;
}
//optional: array_shuffle($values);
$sum = 0;
foreach($values as $item) {
printf("%0.3f ", $item);
$sum += $item;
}
echo $sum;
Output:
0.650 0.350 0.649 0.351 0.911 0.089 0.678 0.322 0.566 0.434 0.563 0.437 0.933 0.067 0.505 0.495 0.503 0.497 0.752 0.248 0.957 0.043 0.856 0.144 0.977 0.023 0.863 0.137 0.766 0.234 0.653 0.347 0.770 0.230 0.888 0.112 0.637 0.363 0.716 0.284 0.891 0.109 0.549 0.451 0.629 0.371 0.501 0.499 0.652 0.348 0.729 0.271 0.957 0.043 0.769 0.231 0.767 0.233 0.513 0.487 0.647 0.353 0.612 0.388 0.509 0.491 0.925 0.075 0.797 0.203 0.799 0.201 0.588 0.412 0.788 0.212 0.693 0.307 0.688 0.312 0.847 0.153 0.903 0.097 0.843 0.157 0.801 0.199 0.538 0.462 0.954 0.046 0.541 0.459 0.893 0.107 0.592 0.408 0.913 0.087 0.711 0.289 0.679 0.321 0.816 0.184 0.781 0.219 0.632 0.368 0.839 0.161 0.568 0.432 0.914 0.086 0.991 0.009 0.979 0.021 0.666 0.334 0.678 0.322 0.705 0.295 0.683 0.317 0.869 0.131 0.837 0.163 0.792 0.208 0.618 0.382 0.606 0.394 0.574 0.426 0.927 0.073 0.661 0.339 0.986 0.014 0.759 0.241 0.547 0.453 0.804 0.196 0.681 0.319 0.960 0.040 0.708 0.292 0.558 0.442 0.605 0.395 0.986 0.014 0.621 0.379 0.992 0.008 0.622 0.378 0.937 0.063 0.884 0.116 0.840 0.160 0.607 0.393 0.765 0.235 0.632 0.368 0.898 0.102 0.946 0.054 0.794 0.206 0.561 0.439 0.801 0.199 0.770 0.230 0.843 0.157 0.681 0.319 0.794 0.206 100
The rounding gets a bit squiffy if you're not using nice numbers like 100 and 200, but never more than 0.1 off.
Original question yesterday had exactly 200 entries and the sum "not greater than 100".
My original answer from yesterday:
Use random numbers not greater than 0.5 to be sure.
Alternatively, depending on how "random" those numbers need to be (how
much correlation is allowed), you could keep a running total, and if
it gets disproportionately high, you can mix in a bunch of smaller
values.
Edit:
Way to go changing the question, making me look stupid and get downvoted.
To get the exact sum you have to normalize, and better use exact fractions instead of floats to avoid rounding errors.

How to round down to the nearest significant figure in php

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.)

Categories