Calculate distance between a value and a multiple of an interval

182 Views Asked by At

I have a value y and an interval i, and I need to calculate the distance between y and a multiple of i for different values of y.

To clarify the problem, imagine that we have an iteration where y increases by 8 for each iteration. The interval i is 30. So basically the result I'm looking for is

iteration   y   result
#1          0   30
#2          8   22
#3          16  14
#4          24  6
#5          32  2
#6          40  10
#7          48  12
#8          56  4
#9          64  4
#10         72  12

What kind of formula could I use to achieve this result?

I tried this formula (sorry if the notation is not 100% correct):

|(i % y) - y|

but it doesn't work all of the time. The results I'm getting is

iteration   y   result
#1          0   30
#2          8   22
#3          16  14
#4          24  6
#5          32  28 (wrong, should be 2)
#6          40  20 (wrong, should be 10)
#7          48  12
#8          56  4
#9          64  26 (wrong, should be 4)
#10         72  18 (wrong, should be 12)

I'm doing this in Java, in case it matters.

1

There are 1 best solutions below

2
On BEST ANSWER

For $\left\lfloor \frac{y}{i} \right\rfloor = 0$, the mathematical expression should be:

$\left| (i \% y) - y \right|$

For $\left\lfloor \frac{y}{i} \right\rfloor > 0$, the mathematical expression should be:

$\min \left( \left| y - \left\lfloor \frac{y}{i} \right\rfloor \times i \right|, \left| y - \left\lceil \frac{y}{i} \right\rceil \times i \right| \right)$

where $|\cdot|$ refers to absolute value, $\lfloor \cdot \rfloor$ refers to the floor function, and $\lceil \cdot \rceil$ refers to the ceiling function.

I'm not a Java expert, but pretty sure Java has these elementary mathematical functions.