Using Floor and Int in a computation

334 views Asked by At

I am using a calculation to locate a base pixel. Seems to me that the two calculations for i and j are equivalent (i.e. i==j is always true) when I tried a few examples. Is this always true?

i = (int ((x - xmin) / a)) + 1
j = (floor ((x - xmin) / a)) + 1

In addition to the above, the following may give different result for i and j (i.e. there exist situations where i/=j).

i = (nint ((x - xmin) / a)) + 1
j = (ceiling ((x - xmin) / a)) + 1
2

There are 2 answers

3
Mithun Ravindran On BEST ANSWER

It will be always TRUE only in this scenario

When the value stored in ix with 'int' function, it will ignore the float values and just consider the whole number before the decimal point. In case of Floor, it will convert to the nearest lower whole number.

The only difference is: In first case, floats are ignored, and in second case- the entire number is converted.

Ultimately, both the results are same. (Only in this scenario) But its recommended to use right functions for right calculation.

1
Alexander Vogt On

INT and FLOOR are different functions!

Consider this example:

program test
  print *,int(-1.2)
  print *,floor(-1.2)
end program

INT will return -1, FLOOR will return -2! So, no, these two statements are not the same!

To incorporate the changes to the question: NINT rounds to the nearest integer, and returns an integer. CEILING is the opposite of FLOOR and will return the next largest integer.