Trying to solve an equation involving the floor function for an algorithm

56 Views Asked by At

I have a c++ function which performs the following operation:

float calculus(float input, float c1, float c2)
{
    auto output = input;

    while (output >= c1)
        output -= c1;

    return output + c2;
}

In my program, I have constant positive float variables called c1 and c2 that are being used repetitively as the function argument, and a variable called counter which is set at c1 at startup.

Then, during the execution of the program, I do the following an unknown number of times (integer and positive):

counter = calculus(counter, c1, c2);

At some unknown point, that variable has a given value that I call $y$, and I would like to know analytically exactly how many times $N$ the function calculus has been called.

I think the equation to solve is the following:

$y = c_1 + N \times c_2 - M \times c_1$

with $M$ being the number of times we substracted c1 to counter, and which can be expressed using the floor function:

$M = \lfloor ( c_1 + N \times c_2 ) / c_1 \rfloor$

So the whole equation to solve is:

$y = c_1 + N \times c_2 - \lfloor ( c_1 + N \times c_2 ) / c_1 \rfloor \times c_1$

As it involves the use of the floor function, I have no idea about a way to find the solution.

Can someone please explain how I can solve this equation and / or my problem? Thank you very much in advance!

1

There are 1 best solutions below

4
On

Let $\frac{c_1 +Nc_2}{c_1} = x$.Then your equation becomes $$\frac{y}{c_1}=x-\lfloor x\rfloor =\{x\}$$ The RHS is the fractional part of $x$. This implies that the decimal part of $x$ is $\frac{y}{c_1}$, and so for some integer $k $, $$x =k +\frac{y}{c_1} \\ c_1 +Nc_2 =kc_1 +y \\ \implies N= \frac{(k-1)c_1 + y}{c_2}$$

I’ll say that this works only if $0\le y\lt c_1$, though.