How to check if a float value is a whole number
To check if a float value is a whole number, use the float.is_integer()
method:
>>> (1.0).is_integer()
True
>>> (1.555).is_integer()
False
The method was added to the float
type in Python 2.6.
Take into account that in Python 2, 1/3
is 0
(floor division for integer operands!), and that floating point arithmetic can be imprecise (a float
is an approximation using binary fractions, not a precise real number). But adjusting your loop a little this gives:
>>> for n in range(12000, -1, -1):
... if (n ** (1.0/3)).is_integer():
... print n
...
27
8
1
0
which means that anything over 3 cubed, (including 10648) was missed out due to the aforementioned imprecision:
>>> (4**3) ** (1.0/3)
3.9999999999999996
>>> 10648 ** (1.0/3)
21.999999999999996
You'd have to check for numbers close to the whole number instead, or not use float()
to find your number. Like rounding down the cube root of 12000
:
>>> int(12000 ** (1.0/3))
22
>>> 22 ** 3
10648
If you are using Python 3.5 or newer, you can use the math.isclose()
function to see if a floating point value is within a configurable margin:
>>> from math import isclose
>>> isclose((4**3) ** (1.0/3), 4)
True
>>> isclose(10648 ** (1.0/3), 22)
True
For older versions, the naive implementation of that function (skipping error checking and ignoring infinity and NaN) as mentioned in PEP485:
def isclose(a, b, rel_tol=1e-9, abs_tol=0.0):
return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
How to detect if a number is a whole number or a float in C?
Compare answer
to the return value of f.e. the floorf()
function (header math.h
) - floorf()
since you dealing with a variable of type float
- with answer
passed as argument.
By doing so, you proof if answer
contains an even decimal value.
For the output itself, Use a precision specifier (f.e. .0
) which specifies the amount of digits in the fraction part and place it between the %
and the f
conversion specifier, For example %.0f
.
The precision of .0
specifies that you want to display no fraction part.
// Checking if the answer is an increase or decrease
if ( answer > 0 ) {
if ( answer == floorf(answer) ) // If answer contains a decimal value.
printf("The answer has been decreased and the final value is: %.0f\n", answer);
else
printf("The answer has been decreased and the final value is: %.3f\n", answer);
}
else {
if ( answer == floorf(answer) ) // If answer contains a decimal value.
printf("The answer has been increased and the final value is: %.0f\n", answer * -1);
else
printf("The answer has been increased and the final value is: %.3f\n", answer * -1);
}
Side Notes:
Note that floating-point often does not provide expected results:
Is floating point math broken?
So, it is possible that even this technique will not work at each and every use case.Always check the return value of input functions such as
scanf()
if an input error occurred.I used
floorf()
, butceilf()
,truncf()
orroundf()
could also be used to achieve the same effect.int main()
is deprecated. Useint main(void)
instead which declares a full prototype formain()
.Since
answer
will be negative when reaching theelse
body, printinganswer * -1
will output a positive value, since- * - = +
. Maybe this is not intended, so this just as a hint.
How to check if float is a whole number?
There isn't really a simple answer
Integral values do have exact representations in the float and double formats. So, if it's really already integral, you can use:
f == floor(f)
However, if your value is the result of a calculation which at one point involved any sort of non-zero fractional part, then you will need to be concerned that you may have something very close to an integer but which isn't really, exactly, to-the-last-bit the same. You probably want to consider that to be integral.
One way this might be done:
fabs(f - round(f)) < 0.000001
And while we are on the subject, for the purists, we should note that int i = f;
or double i = f;
will round according to the FPU mode whereas round(3) will round half-way cases away from zero.
How to test whether a float is a whole number in Go?
Assuming your numbers will fit into an int64
, you can just compare the float value with a converted integer value to see if they're the same:
if a == float64(int64(a)) {
fmt.Println("yay")
} else {
fmt.Println("you fail")
}
Otherwise you can use the math.Trunc
function detailed here, with something like:
if a == math.Trunc(a) {
fmt.Println("yay")
} else {
fmt.Println("you fail")
}
That one should work within the entire float64
domain.
Checking if float is an integer
Apart from the fine answers already given, you can also use ceilf(f) == f
or floorf(f) == f
. Both expressions return true
if f
is an integer. They also returnfalse
for NaNs (NaNs always compare unequal) and true
for ±infinity, and don't have the problem with overflowing the integer type used to hold the truncated result, because floorf()
/ceilf()
return float
s.
How do I determine whether the value of a float is a whole number?
All float types have the same size, so your method won't work. You can check if a float is an integer by using ceilf
float num = 1.5;
if (ceilf(num) == num)
printf ("INTEGER");
else
printf("FLOAT");
How do I tell if a float is a whole number?
if (height_input % 1).zero?
or
if height_input.to_i == height_input
Determining whether an value is a whole number in Python
if x % 3 == 0:
print 'x is divisible by 3'
Numpy: Check if float array contains whole numbers
From what I can tell, there is no such function that returns a boolean array indicating whether floats have a fractional part or not. The closest I can find is np.modf
which returns the fractional and integer parts, but that creates two float arrays (at least temporarily), so it might not be best memory-wise.
If you're happy working in place, you can try something like:
>>> np.mod(x, 1, out=x)
>>> mask = (x == 0)
This should save memory versus using round or floor (where you have to keep x
around), but of course you lose the original x
.
The other option is to ask for it to be implemented in Numpy, or implement it yourself.
Related Topics
How to Select Rows in a Dataframe Between Two Values, in Python Pandas
Fast Haversine Approximation (Python/Pandas)
Making Object JSON Serializable with Regular Encoder
X, = ... - Is This Trailing Comma the Comma Operator
How to Open a File Using the Open with Statement
Best Practice for Using Assert
The 'Is' Operator Behaves Unexpectedly with Non-Cached Integers
How to Escape Os.System() Calls
How to Set Sys.Stdout Encoding in Python 3
Quoting Backslashes in Python String Literals
Pandas: Drop Consecutive Duplicates
What Exactly Does "Import *" Import
Creating Dataframe from a Dictionary Where Entries Have Different Lengths
How to Do a Recursive Sub-Folder Search and Return Files in a List
Attributeerror: 'Module' Object Has No Attribute
What Are Logits? Differencebetween Softmax and Softmax_Cross_Entropy_With_Logits