Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Less than or Equal to" versus "Less than" for processing [closed]

Consider the following conditions:

if(a < 10)

and

if(a <= 9)

Considering only int.

I know these conditions serve the same purpose and the processing difference would be negligible. Yet, what can be the processing difference between the two?

like image 912
Gaurav Bhor Avatar asked Apr 11 '14 11:04

Gaurav Bhor


1 Answers

For int and long there is no real difference as they both deal in whole numbers.
This is because 9 is the next valid value below 10.

But for float, double and other types that can hold values smaller than a whole number there is a big difference.

Consider how these numbers would be handled by your two cases:

float a = 9.0
float b = 10.0
float c = 9.5

Edit:

In the first case if (val < 10):

a < 10  ... true
b < 10  ... false
c < 10  ... true    <--- note this

Second case if (val <= 9):

a <= 9  ... true
b <= 9  ... false
c <= 9  ... false    <--- note this

And this is all assuming that you end up with 'clean' numbers and rounding or division errors are not introduced such as 9.99999999999 and 10.000000000001 through any calculations you may be performing.

When comparing floating point numbers you should use that class's built-in compare method.

a.compare(value) < 0  ... true if 'a' is smaller than 'value'
a.compare(value) > 0  ... true if 'a' is bigger than 'value'
a.compare(value) == 0 ... true if 'a' is equal to 'value'
like image 194
indivisible Avatar answered Nov 14 '22 20:11

indivisible