Closest integer to a float number

Hello,

I would like to apply a certain operation when my time variable t becomes a multiple of t0. Is there a robust way to implement this?

I think this boils down to check whether t/t0 is an integer in a robust fashion.

t % t0 == 0 works until floating point precision bites you. Then you’ll need to check whether t % t0 is close enough to zero. What’s close enough depends on your application.

3 Likes

There’s isinteger if you want to know if it’s exactly an integer:

help?> isinteger
search: isinteger

  isinteger(x) -> Bool

  Test whether x is numerically equal to some integer.

  Examples
  ≡≡≡≡≡≡≡≡≡≡

  julia> isinteger(4.0)
  true

Maybe something like this would be helpful for testing if it’s close to an integer up to some tolerance:

julia> near_integer(x; tol=1e-3) = abs(x - round(x)) <= tol
near_integer (generic function with 1 method)

julia> near_integer(1.001)
true

julia> near_integer(1.1)
false
1 Like

Note that you have to check both close to 0, and close to t0

1 Like

Thank you all for your answers.

Can’t we just check if the ratio t/t0 is close enough to an integer

I guess it depends on whether you want to have a relative or absolute tolerance. The ratio won’t work for numbers close to 0 though

If you are checking whether something is close to an integer, the natural scale for comparison is 1 (the difference between consecutive integers), in which case relative and absolute tolerance become the same thing. i.e. it sounds like you just want to check abs(t/t0 - round(t/t0)) < δ for some tolerance δ.

Of course, you haven’t said anything about the underlying problem that is driving this. It could be that there is a completely different approach based on reformulating your problem in a more robust form.

6 Likes

You might want to check for the first time t is greater than t_prev+t0 which feels more robust than computing the ratio, at least if there can be any form of jitter involved.

1 Like