tags:

views:

116

answers:

3

there is given real number how find by programming if it is Almost integer?

http://mathworld.wolfram.com/AlmostInteger.html

thanks

+10  A: 
  • Find the integer the number is closest to
  • Find the difference between that integer and the number itself
  • Take the absolute value of that difference
  • If it's below whatever threshold you want to provide, count it as an "almost integer"

Exactly how you would do that depends on the language you're using. For example, in C# using the decimal type you could have:

public static bool IsAlmostInteger(decimal value, decimal threshold)
{
    decimal closestInteger = Math.Round(value);
    decimal diff = Math.Abs(closestInteger - value);
    return diff < threshold;
}
Jon Skeet
A: 

http://www.java2s.com/Open-Source/Java-Document/Science/Apache-commons-math-1.1/org/apache/commons/math/fraction/Fraction.java.htm has an example Fraction method which checks for 'almost' integers with an epsilon allowance value, but whether that's accurate enough for you is up to you?

Mark Mayo
A: 

For any language --

  1. Find the closest integer by casting (your number+0.5) to an integer -- basically, cutting off the decimal part and leaving only the whole number part.
  2. Subtract that from your original number, and note the (absolute value of the) difference. If it's within what you want, you're good.

Note that the rounding method in (1) only is predictable in the positive numbers. If you want one that works for all, try looking at rounding methods. Suffice to say, most programming languages already have a built-in rounding function, if you can find it.

Justin L.