-1

I have an array of floats. Some of these floats are VERY close to integers, but they're still floats. I need to filter these values.

For example:

array_n = [n]; //an array of floats k = 160.

In the if loop, n is an element in array_n. I need to pick n out of the array using k. I've tried doing n%k <= k, but it just didn't work. I tried just filtering out numbers that are close to integers by doing n%1 <= .000000001, but certain values came out to 1 when I did n%1 (I'm really not sure why or how).

Any ideas?

I'm using MATLAB, but I think the problem applies to any language.

  • 1
    Floating point rounding error is equally likely to make the result smaller or bigger than the real number arithmetic result. If a float is very slightly smaller than an integer its reduction mod 1 will be very slightly smaller than 1, and its rounded printout may be 1. – Patricia Shanahan Feb 22 '15 at 19:51

3 Answers3

2

let x be the rounded number to the closest integer.

if abs(x - number) < threshold, then this number is an integer.

mattsap
  • 3,790
  • 1
  • 15
  • 36
  • 1
    threshold is usually denoted `epsilon`, and should be quite small (e.g. 10^-6 or smaller). Also, I think OP wanted `x` close to arbitrary integers, not a specific `number` (but I still upvoted you). – John Castleman Feb 22 '15 at 20:00
  • this worked. Thanks so much. It turns out I actually had some other unrelated error, but I still used this solution. – user3552360 Feb 22 '15 at 20:13
0

I'm going with C#, since that's what I know, sorry:

bool IsIntegerish(float f)
{
    const float epsilon = 0.000000001; // using epsilon from OP
    return abs(f - (int)f) < epsilon;
}

Used (in C#, anyway) as:

foreach (var i in myFloats.Where(f => !IsIntegerish(f)))
{
    // do something useful
}
John Castleman
  • 1,552
  • 11
  • 12
0

You should probably use relative instead of absolute error tolerance:

tolerance = 1e-3;
a( abs(a-round(a)) < tolerance*(eps(a)/eps) )
knedlsepp
  • 6,065
  • 3
  • 20
  • 41