 # While loop with multiple conditions

Hello all!

here is a code:

fun test() {
var a: Int
var b: Int
var c: Int
var result: Double
do {
a = Random.nextInt(1, 1001)
b = Random.nextInt(1, 1001)
c = Random.nextInt(1, 101)

``````        result = (a.toDouble() - b.toDouble()) / c.toDouble()

} while (((result - result.toInt()) != 0.0) && (result <= 0.0 ))
println("(\$a - \$b) / \$c = \$result")
}
``````

It must generate a, b and c such that the result is always > 0 and reminder = 0.
It seems that these both conditions in while loop cannot be considered simultaneously.

Do I do something wrong?

What exactly is the error you see or is it just that your program never ends?

They should. I don’t see anything wrong with that part. You could try changing the remainder check to `(a - b) & c == 0` but that shouldn’t change anything.

I’m not sure but how high is the probability that generating 3 random numbers fullfills that condition? Maybe it’s just super unlikely. What exactly are you trying to do?
Mayabe a better approach would be to generate the numbers (a, b, c) in another way. Start by generating a random `result`. After that you can calculate `maxC` so that `result * c` is never greater than `1000 = maxA - minB`. After that all you need to do is generate a random `a` and calculate `b`. That might change the probablilites for a, b and c though so it might not be a valid approach.
That way you no longer need the loop to calculate the numbers and it can be done in constant time.

Hi and thanks for prompt reply.

The problem is that the function does not do what it should, namely to return the result that satisfies both conditions: be > 0 and reminder = 0. It returns always the positive result (as it shoud) , but the reminder is not = 0. I cannot figure out why…

You want result to satisfy: “be > 0 and reminder = 0”

But the code demands that result not satisfy: “be <= 0 and remainder != 0”

These are not the same. Think through some example results like -1 or 1.1 that would exit the while loop but not satisfy your condition.

If still unsure, try googling “De Morgan’s laws” for some insight.

1 Like

thanks a lot!
I checked “De Morgan’s laws” and found:
not (A or B) = not A and not B; and
not (A and B) = not A or not B

So, in this case while (((result - result.toInt()) != 0.0) || (result <= 0.0 )) does exactly what I need!
Thanks again.

Much appreciated!

Equality/inequality tests are tricky when using floating point numbers, due to discretization error. A small variance such as 0.000000001 would cause the test to produce an undesired result. The conventional alternative to `x != 0` is to use a tolerance, e.g., `abs(x) > epsilon`, where epsilon is a small value.

2 Likes