Algorithm to portion - php

I have a number X, consider X = 1000
And I want piecemeal this number at three times, then Y = 3, then X = (X / 3)
This will give me equal, just not always accurate, so I need: a percentage value is set, also consider K = 8, K is the percentage, but what I want to do? I want the first portion has a value over 8% in K, suppose that 8% are: 500 and the other two plots are 250, 250
The algorithm is basically what I need it, add a percentage value for the first installment and the other equals

EDIT
I just realized, this is far simpler than I made it. To find the value of $div in my original answer you can just:
$div = (int)($num / ($parcels + $percent / 100));
Then the $final_parcels will be the same as below. Basically, the line above replaces the while loop entirely. Don't know what I was thinking.
/EDIT
I think this will do what you want... unless I am missing something.
<?php
$num = 1000;
$percent = 8;
$parcels = 3;
$total = PHP_INT_MAX;
$div = (int)($num / $parcels);
while ($total > $num) {
$div -= 1;
$total = (int)($div * ($parcels + $percent / 100));
}
$final_parcels = array();
$final_parcels[] = ($num - (($parcels - 1) * $div));
for ($i = 1; $i < $parcels; $i++) {
$final_parcels[] = $div;
}
print_r($final_parcels);
This output will be
Array
(
[0] => 352
[1] => 324
[2] => 324
)
324 * 1.08 = 350.
352 + 324 * 2 = 1000.

Let $T is your total X, $n is a number of parts and $K is percentage mentioned above. Than
$x1 = $T / $n + $T * $K / 100;
$x2 = $x3 = .. = $xn = ($T - $x1) / ($n - 1);
Applied to your example:
$x1 = 1000 / 3 + 1000 * 0.03 = 363.3333333333333333333333333333
// you could round it if you want
// lets round it to ten, as you mentioned
$x1 = round($x1, -1) = 360
$x2 = $x3 = (1000 - 360) / 2 = 320

Extra for the first piece W = X*K/100
Remaining Z = X-W
Each non-first piece = Z/Y = (X-W)/Y = (100-K)*X/(100*Y)
The first piece = W + (100-K)*X/(100*Y) = X*K/100 + (100-K)*X/(100*Y)

Related

Not the outcome i need... round of floor? [duplicate]

I want a php function which returns 55 when calling it with 52.
I've tried the round() function:
echo round(94, -1); // 90
It returns 90 but I want 95.
Thanks.
This can be accomplished in a number of ways, depending on your preferred rounding convention:
1. Round to the next multiple of 5, exclude the current number
Behaviour: 50 outputs 55, 52 outputs 55
function roundUpToAny($n,$x=5) {
return round(($n+$x/2)/$x)*$x;
}
2. Round to the nearest multiple of 5, include the current number
Behaviour: 50 outputs 50, 52 outputs 55, 50.25 outputs 50
function roundUpToAny($n,$x=5) {
return (round($n)%$x === 0) ? round($n) : round(($n+$x/2)/$x)*$x;
}
3. Round up to an integer, then to the nearest multiple of 5
Behaviour: 50 outputs 50, 52 outputs 55, 50.25 outputs 55
function roundUpToAny($n,$x=5) {
return (ceil($n)%$x === 0) ? ceil($n) : round(($n+$x/2)/$x)*$x;
}
Divide by 5
round() (or ceil() if you want to round up always)
Multiply by 5.
The value 5 (the resolution / granularity) can be anything — replaced it in both step 1 and 3
So in summary:
$rounded_number = ceil( $initial_number / 5 ) * 5
Round down:
$x = floor($x/5) * 5;
Round up:
$x = ceil($x/5) * 5;
Round to closest (up or down):
$x = round($x/5) * 5;
echo $value - ($value % 5);
I know it's an old question, but IMHO using modulus operator is the best way, and far more elegant than the accepted answer.
Try this little function I wrote.
function ceilFive($number) {
$div = floor($number / 5);
$mod = $number % 5;
If ($mod > 0) $add = 5;
Else $add = 0;
return $div * 5 + $add;
}
echo ceilFive(52);
From Gears library
MathType::roundStep(50, 5); // 50
MathType::roundStep(52, 5); // 50
MathType::roundStep(53, 5); // 55
MathType::floorStep(50, 5); // 50
MathType::floorStep(52, 5); // 50
MathType::floorStep(53, 5); // 50
MathType::ceilStep(50, 5); // 50
MathType::ceilStep(52, 5); // 55
MathType::ceilStep(53, 5); // 55
Source:
public static function roundStep($value, int $step = 1)
{
return round($value / $step) * $step;
}
public static function floorStep($value, int $step = 1)
{
return floor($value / $step) * $step;
}
public static function ceilStep($value, int $step = 1)
{
return ceil($value / $step) * $step;
}
Multiply by 2, round to -1, divide by 2.
Here is my version of Musthafa's function. This one is more complex but it has support for Float numbers as well as Integers. The number to be rounded can also be in a string.
/**
* #desc This function will round up a number to the nearest rounding number specified.
* #param $n (Integer || Float) Required -> The original number. Ex. $n = 5.7;
* #param $x (Integer) Optional -> The nearest number to round up to. The default value is 5. Ex. $x = 3;
* #return (Integer) The original number rounded up to the nearest rounding number.
*/
function rounduptoany ($n, $x = 5) {
//If the original number is an integer and is a multiple of
//the "nearest rounding number", return it without change.
if ((intval($n) == $n) && (!is_float(intval($n) / $x))) {
return intval($n);
}
//If the original number is a float or if this integer is
//not a multiple of the "nearest rounding number", do the
//rounding up.
else {
return round(($n + $x / 2) / $x) * $x;
}
}
I tried the functions from Knight, Musthafa and even the suggestion from Praesagus. They don't have support for Float numbers and the solutions from Musthafa's & Praesagus do not work correctly in some numbers. Try the following test numbers and do the comparison yourself:
$x= 5;
$n= 200; // D = 200 K = 200 M = 200 P = 205
$n= 205; // D = 205 K = 205 M = 205 P = 210
$n= 200.50; // D = 205 K = 200 M = 200.5 P = 205.5
$n= '210.50'; // D = 215 K = 210 M = 210.5 P = 215.5
$n= 201; // D = 205 K = 205 M = 200 P = 205
$n= 202; // D = 205 K = 205 M = 200 P = 205
$n= 203; // D = 205 K = 205 M = 205 P = 205
** D = DrupalFever K = Knight M = Musthafa P = Praesagus
I do it like this:
private function roundUpToAny(int $n, $x = 9)
{
return (floor($n / 10) * 10) + $x;
}
Tests:
assert($this->roundUpToAny(0, 9) == 9);
assert($this->roundUpToAny(1, 9) == 9);
assert($this->roundUpToAny(2, 9) == 9);
assert($this->roundUpToAny(3, 9) == 9);
assert($this->roundUpToAny(4, 9) == 9);
assert($this->roundUpToAny(5, 9) == 9);
assert($this->roundUpToAny(6, 9) == 9);
assert($this->roundUpToAny(7, 9) == 9);
assert($this->roundUpToAny(8, 9) == 9);
assert($this->roundUpToAny(9, 9) == 9);
assert($this->roundUpToAny(10, 9) == 19);
assert($this->roundUpToAny(11, 9) == 19);
assert($this->roundUpToAny(12, 9) == 19);
assert($this->roundUpToAny(13, 9) == 19);
assert($this->roundUpToAny(14, 9) == 19);
assert($this->roundUpToAny(15, 9) == 19);
assert($this->roundUpToAny(16, 9) == 19);
assert($this->roundUpToAny(17, 9) == 19);
assert($this->roundUpToAny(18, 9) == 19);
assert($this->roundUpToAny(19, 9) == 19);
function round_up($n, $x = 5) {
$rem = $n % $x;
if ($rem < 3)
return $n - $rem;
else
return $n - $rem + $x;
}
I just wrote this function in 20 min, based on many results I found here and there, I don't know why it works or how it works!! :D
I was mainly interested in converting currency numbers from this 151431.1 LBP to 150000.0 LBP. (151431.1 LBP == ~100 USD) which works perfectly so far, however I tried to make it somehow compatible with other currencies and numbers, but not sure if it works fine!!
/**
* Example:
* Input = 151431.1 >> return = 150000.0
* Input = 17204.13 >> return = 17000.0
* Input = 2358.533 >> return = 2350.0
* Input = 129.2421 >> return = 125.0
* Input = 12.16434 >> return = 10.0
*
* #param $value
* #param int $modBase
*
* #return float
*/
private function currenciesBeautifier($value, int $modBase = 5)
{
// round the value to the nearest
$roundedValue = round($value);
// count the number of digits before the dot
$count = strlen((int)str_replace('.', '', $roundedValue));
// remove 3 to get how many zeros to add the mod base
$numberOfZeros = $count - 3;
// add the zeros to the mod base
$mod = str_pad($modBase, $numberOfZeros + 1, '0', STR_PAD_RIGHT);
// do the magic
return $roundedValue - ($roundedValue % $mod);
}
Feel free to modify it and fix it if there's anything wrong
Probably you can also consider this one liner. It's faster! Works for $num >= 0 and $factor > 0.
$num = 52;
$factor = 55;
$roundedNum = $num + $factor - 1 - ($num + $factor - 1) % $factor;

Achieve 921 and 999 by 39 loops as whole numbers

I am in a situation where I need to achieve divide 921/39 and by giving whole numbers (39 times for loop), achieve 921 again.
$packagesCount = count($packages); // = 39
$averageWeight = 921/$packagesCount; // = 23.6153846154
foreach ($packages as $package) {
$package['Weight'] = "<whole number>";
}
The reason is, I need to give the api whole numbers but the total should be 921. Thus, I can't give round numbers.
One way I thought of is:
$packagesCount = count($packages); // = 39
$averageWeight = 921/$packagesCount; // = 23.6153846154
$remainder = ceil($averageWeight); // = 24
foreach ($packages as $package) {
$package['Weight'] = floor($averageWeight);
if ($remainder > 0) {
$package['Weight'] += 1;
$remainder -= 1;
}
}
But trying it with 999 total weight doesn't work with this approach; instead of 999 in the end, it gives 39 * 25 + 26 = 1001.
For 999, I should use 39 * 25 + 24 = 999 but how?
I think you need intdiv and modulo %:
$packagesCount = count($packages);
$averageWeight = $totalWeight/$packagesCount;
$wholeWeight = intdiv($totalWeight,$packagesCount);
$weightRest = $totalWeight % $packagesCount;
// totalWeight = wholeWeight * packagesCount + weightRest
$i = 0;
foreach ($packages as $key => $package) {
$w = $wholeWeight;
if ($i < $weightRest) {
$w += 1;
}
$i+= 1;
$packages[$key]['Weight'] = $w;
}
The idea is that each package while have at least intdiv weight and first weightRest packages will have +1 to their weight. In such a way you will exactly match your totalWeight.
See also an online demo
P.S. PHP is not my language so the code might be very non-idiomatic. Still I hope it conveys the idea.

Easiest way to round down to nearest 50 or 00

i want to round up a number like this
1439 to 1400
1399 to 1350
What are the nearest way to do this in php?
Given the new examples...
Looks like you want to use PHP floor instead and apply the 50 yourself
50 * floor($number / 50)
OLD ANSWER
Going from your examples, rather than the question title..
Try the PHP round function.
In your case:
round($number, -2);
The second param is the number of decimal figures to round to, negative values go to the left of the 'ones' digit instead.
There is also a third parameter for some more subtle variations.
$rounded_n1 = round($n1 / 50, 0) * 50;
You can do something like that (only to round down) :
$n1 = 1439;
$n2 = 1399;
$round1 = $n1 - $n1 % 50; // round1 = 1439 - 39 = 1400
$round2 = $n2 - $n2 % 50; // round2 = 1399 - 49 = 1350
To round up, you can do this :
$n1 = 1439;
$n2 = 1399;
$round1 = $n1 + (50 - $n1 % 50); // round1 = 1439 + (50 - 39) = 1450
$round2 = $n2 + (50 - $n2 % 50); // round2 = 1399 + (50 - 49) = 1400
You can do it like:
Divide it by 100.
Truncate.
Multiply by 100.
This is the best thing I could come up with.
$num = 1401;
$num /= 100;
$num = round($num);
$num *= 100;
Use ceil to always round up
$round1 = ceil($n1/ 50) * 50
You should try:
function specialRoundUp($val) {
return 100 * round($val / 100);
}

displaying axis from min to max value - calculating scale and labels

Writing a routine to display data on a horizontal axis (using PHP gd2, but that's not the point here).
The axis starts at $min to $max and displays a diamond at $result, such an image will be around 300px wide and 30px high, like this:
(source: testwolke.de)
In the example above, $min=0, $max=3, $result=0.6.
Now, I need to calculate a scale and labels that make sense, in the above example e.g. dotted lines at 0 .25 .50 .75 1 1.25 ... up to 3, with number-labels at 0 1 2 3.
If $min=-200 and $max=600, dotted lines should be at -200 -150 -100 -50 0 50 100 ... up to 600, with number-labels at -200 -100 0 100 ... up to 600.
With $min=.02and $max=5.80, dotted lines at .02 .5 1 1.5 2 2.5 ... 5.5 5.8 and numbers at .02 1 2 3 4 5 5.8.
I tried explicitly telling the function where to put dotted lines and numbers by arrays, but hey, it's the computer who's supposed to work, not me, right?!
So, how to calculate???
An algorithm (example values $min=-186 and $max=+153 as limits):
Take these two limits $min, $max and mark them if you wish
Calculate the difference between $max and $min: $diff = $max - $min
153 - (-186) = 339
Calculate 10th logarithm of the difference $base10 = log($diff,10) = 2,5302
Round down: $power = round($base10) = 2.
This is your tenth power as base unit
To calculate $step calculate this:
$base_unit = 10^$power = 100;
$step = $base_unit / 2; (if you want 2 ticks per one $base_unit).
Calculate if $min is divisible by $step, if not take the nearest (round up) one
(in the case of $step = 50 it is $loop_start = -150)
for ($i=$loop_start; $i<=$max; $i++=$step){ // $i's are your ticks
end
I tested it in Excel and it gives quite nice results, you may want to increase its functionality,
for example (in point 5) by calculating $step first from $diff,
say $step = $diff / 4 and round $step in such way that $base_unit is divisible by $step;
this will avoid such situations that you have between (101;201) four ticks with $step=25 and you have 39 steps $step=25 between 0 and 999.
ACM Algorithm 463 provides three simple functions to produce good axis scales with outputs xminp, xmaxp and dist for the minimum and maximum values on the scale and the distance between tick marks on the scale, given a request for n intervals that include the data points xmin and xmax:
Scale1() gives a linear scale with approximately n intervals and dist being an integer power of 10 times 1, 2 or 5.
Scale2() gives a linear scale with exactly n intervals (the gap between xminp and xmaxp tends to be larger than the gap produced by Scale1()).
Scale3() gives a logarithmic scale.
The original 1973 paper is online here, which provides more explanation than the code linked to above.
The code is in Fortran but it is just a set of arithmetical calculations so it is very straightforward to interpret and convert into other languages. I haven't written any PHP myself, but it looks a lot like C so you might want to start by running the code through f2c which should give you something close to runnable in PHP.
There are more complicated functions that give prettier scales (e.g. the ones in gnuplot), but Scale1() would likely do the job for you with minimal code.
(This answer builds on my answer to a previous question Graph axis calibration in C++)
(EDIT -- I've found an implementation of Scale1() that I did in Perl):
use strict;
sub scale1 ($$$) {
# from TOMS 463
# returns a suitable scale ($xMinp, $xMaxp, $dist), when called with
# the minimum and maximum x values, and an approximate number of intervals
# to divide into. $dist is the size of each interval that results.
# #vInt is an array of acceptable values for $dist.
# #sqr is an array of geometric means of adjacent values of #vInt, which
# is used as break points to determine which #vInt value to use.
#
my ($xMin, $xMax, $n) = #_;
#vInt = {1, 2, 5, 10};
#sqr = {1.414214, 3.162278, 7.071068 }
if ($xMin > $xMax) {
my ($tmp) = $xMin;
$xMin = $xMax;
$xMax = $tmp;
}
my ($del) = 0.0002; # accounts for computer round-off
my ($fn) = $n;
# find approximate interval size $a
my ($a) = ($xMax - $xMin) / $fn;
my ($al) = log10($a);
my ($nal) = int($al);
if ($a < 1) {
$nal = $nal - 1;
}
# $a is scaled into a variable named $b, between 1 and 10
my ($b) = $a / 10^$nal;
# the closest permissable value for $b is found)
my ($i);
for ($i = 0; $i < $_sqr; $i++) {
if ($b < $sqr[$i]) last;
}
# the interval size is computed
$dist = $vInt[$i] * 10^$nal;
$fm1 = $xMin / $dist;
$m1 = int($fm1);
if ($fm1 < 0) $m1--;
if (abs(($m1 + 1.0) - $fm1) < $del) $m1++;
# the new minimum and maximum limits are found
$xMinp = $dist * $m1;
$fm2 = $xMax / $dist;
$m2 = $fm2 + 1;
if ($fm2 < -1) $m2--;
if (abs ($fm2 + 1 - $m2) < $del) $m2--;
$xMaxp = $dist * $m2;
# adjust limits to account for round-off if necessary
if ($xMinp > $xMin) $xMinp = $xMin;
if ($xMaxp < $xMax) $xMaxp = $xMax;
return ($xMinp, $xMaxp, $dist);
}
sub scale1_Test {
$par = (-3.1, 11.1, 5,
5.2, 10.1, 5,
-12000, -100, 9);
print "xMin\txMax\tn\txMinp\txMaxp,dist\n";
for ($i = 0; $i < $_par/3; $i++) {
($xMinp, $xMaxp, $dist) = scale1($par[3*$i+0],
$par[3*$i+1], $par[3*$i+2]);
print "$par[3*$i+0]\t$par[3*$i+1]\t$par[3*$i+2]\t$xMinp\t$xMaxp,$dist\n";
}
}
I know that this isn't exactly what you are looking for, but hopefully it will get you started in the right direction.
$min = -200;
$max = 600;
$difference = $max - $min;
$labels = 10;
$picture_width = 300;
/* Get units per label */
$difference_between = $difference / ($labels - 1);
$width_between = $picture_width / $labels;
/* Make the label array */
$label_arr = array();
$label_arr[] = array('label' => $min, 'x_pos' => 0);
/* Loop through the number of labels */
for($i = 1, $l = $labels; $i < $l; $i++) {
$label = $min + ($difference_between * $i);
$label_arr[] = array('label' => $label, 'x_pos' => $width_between * $i);
}
A quick example would be something in the lines of $increment = ($max-$min)/$scale where you can tweak scale to be the variable by which the increment scales. Since you devide by it, it should change proportionately as your max and min values change. After that you will have a function like:
$end = false;
while($end==false){
$breakpoint = $last_value + $increment; // that's your current breakpoint
if($breakpoint > $max){
$end = true;
}
}
At least thats the concept... Let me know if you have troubles with it.

PHP formula needed to calculate a simple format

I am trying to take an amount and convert it to a units type format...
For example:
( note: don't worry about the dollar sign )
Total is $400
I need to display it as 4 * 100
Another Example
Total is $450
I need to display it as 4 * 100 | 50 * 1
So another words there are only 100 and 1 units.
I was thinking for 3 hours already and nothing seems to come to mind...Perhaps someone out there has done something similar and already know the answer?
Hoping I am not doing your homework. Try this:
$num = 450;
$ones = $num % 100;
$hundreds = floor($num / 100);
echo "$hundreds * 100 | $ones * 1";
Here's a simple implementation
$amount = 450;
$hundreds = floor($amount / 100);
$ones = $amount % 100;
$string = array();
if( $hundreds )
$string[] = "$hundreds * 100";
if( $ones )
$string[] = "$ones * 1";
echo implode(' | ', $string);
Check out the modulus (%) operator
Here's a simple solution which will only show the units present, you can get rid of the array/join stuff if you always need to show both units:
$total = 400;
$out = array();
$hundreds = floor($total / 100);
if ($hundreds) {
$out[] = $hundreds . ' * 100';
}
$ones = $total % 100;
if ($ones) {
$out[] = $ones . ' * 1';
}
echo join(' | ', $out);
Use the modulus operator to break down the number (this kind of thing is good to learn how to do because you'll need it for many other units conversion tasks like seconds -> minutes & seconds conversion):
$value=450;
$ones = $value % 100;
$hundreds = floor($value / 100);
echo "$hundreds * 100 | $ones * 1\n";

Categories