Jump to content

[SOLVED] Newbie Help - Rounding errors


johng

Recommended Posts

I am working on a project that has me dividing, and I am having one small issue. 

 

There are three sites that get a number of items, proportional to the volume at the site.  For example:

 

Site A has 30 volume

Site B has 40 volume

Site C has 50 volume.

 

This is not an issue if the number of items is 10 (then Site A would get 3, Site B would get 4 and Site C would get 5)

The issue comes up with rounding errors. 

 

Say for example that:

 

Site A has 50

Site B has 30

Site C has 30

 

If there are 10 items, it calculates that Site A should get 5, and Site B and Site C should get 3 (2.7 rounded up). 

 

What I would like it to do is to either put the extra one in only B or C, or just put it in A.

 

What I am wondering is if there is a simple (or even not so simple) way to do this, without having a great amount of if statements.

 

Thanks in advance, and hopefully I didn't confuse you too much.  If so, please let me know and I will try to clarify.

Link to comment
https://forums.phpfreaks.com/topic/39648-solved-newbie-help-rounding-errors/
Share on other sites

I'm not sure I follow, but I'll give it a go:

<?php
function calculateDistribution($numbers, $total) {
  $base = 10; // This tells us to use division by 10
  $res = array();
  foreach ($numbers as $k => $v) {
    $myItem = round($v / $base); // This comp's items
    if ($total >= $myItem) { // We have enough to give full value
      $res[$k] = $myItem;
      $total -= $myItem; // Update $total for next loop
    } else { // Not enough, just give what's left
      $res[$k] = $total;
    }
  }
  return $res;
}

$total_avail = 10; // How many items to pass out
$site_report = array(
  'A' => 50,
  'B' => 30,
  'C' => 30
);

$items = calculateDistribution($site_report, $total_avail);
echo "<pre>\n";
print_r($items);
echo "</pre>\n";
?>

 

This will give you results of:

A => 5

B => 3

C => 2

 

Is that what you're after? If not, give me a little more info, and I'll do what I can to help. Good luck!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.