Divide an integer in the sum of two integers with percentage factor using ceil and floor

93 Views Asked by At

I have encoutered a problem in a software that I use for invoicing. I have a variable (quantity) integer A which I want to split in a sum of two integers using a percentage p where $A1 = p*A$ and $A2 = (1-p)*A$.

Currently the software is using a rounding function. But as it takes a percentage of the value and rounds it to two integers, the equation (very often) is no longer true. This is the sum of A1 and A2 is not A.

More formally: Let A be a positive integer ($A \in Z^+$) and $p \in [0,1]$. I want $A = A1+A2$ where $A1, A2 \in Z^+$

I came up with this

$$A = \lfloor{p*A\rfloor} + \lceil{(1-p)*A\rceil}$$

where I make use of the floor and ceil function. Does it make sense, is this true?

1

There are 1 best solutions below

0
On

Yes. Since: $$A - \lfloor p*A \rfloor = A + \lceil -p*A \rceil = \lceil A - p*A \rceil$$ However, since your software is using a rounding function, it would be better to set: $$A1 = rnd(p*A) \text{ and } A2 = A - A1$$ Then there is no need to invoke the floor/ceiling functions.