Here's a piece of code that checks whether a number is an integer or not, it works for both Python 2 and Python 3.
import sys
if sys.version < '3':
integer_types = [int, long,]
else:
integer_types = [int,]
isinstance[yourNumber, integer_types] # returns True if it's an integer
isinstance[yourNumber, float] # returns True if it's a float
Notice that Python 2 has both types int
and long
, while Python 3 has only type int
. Source.
If you want to check whether your number is a float
that represents an int
, do this
[isinstance[yourNumber, float] and [yourNumber].is_integer[]] # True for 3.0
If you don't need to distinguish between int and float, and are ok with either, then ninjagecko's answer is the way to go
import numbers
isinstance[yourNumber, numbers.Real]
The float[]
method returns a floating point number from a number or a string.
Example
int_number = 25
# convert int to float
float_number = float[int_number]
print[float_number]
# Output: 25.0
float[] Syntax
The syntax for float[]
is:
float[[x]]
float[] Parameters
The float[]
method takes a single parameter:
- x [Optional] - number or string that needs to be converted to floating point number
If it's a string, the string should contain decimal points
Float number | Use as a floating number |
Integer | Use as an integer |
String | Must contain decimal numbers. Leading and trailing whitespaces are removed. Optional use of "+", "-" signs. Could contain NaN , Infinity , inf [lowercase or uppercase].
|
float[] Return Value
The float[]
method returns:
- Equivalent floating point number if an argument is passed
- 0.0 if no arguments passed
OverflowError
exception if the argument is outside the range of Python float
Example 1: How float[] works in Python?
# for integers
print[float[10]]
# for floats
print[float[11.22]]
# for string floats
print[float["-13.33"]]
# for string floats with whitespaces
print[float[" -24.45\n"]]
# string float error
print[float["abc"]]
Output
10.0 11.22 -13.33 -24.45 ValueError: could not convert string to float: 'abc'
Example 2: float[] for infinity and Nan[Not a number]?
# for NaN
print[float["nan"]]
print[float["NaN"]]
# for inf/infinity
print[float["inf"]]
print[float["InF"]]
print[float["InFiNiTy"]]
print[float["infinity"]]
Output
nan nan inf inf inf inf
Summary: in this tutorial, you’ll learn about the Python float type, how Python represents floating-point numbers, and how to test the floating-point number for equality.
Introduction to the Python float type
Python uses the float
class to represent real numbers.
CPython implements float using C double type. The C double type usually implements IEEE 754 double-precision binary float, which is also called binary64.
Python float uses 8 bytes [or 64 bits] to represent real numbers. Unlike the integer type, the float type uses a fixed number of bytes.
Technically, Python uses 64 bits as follows:
- 1 bit for sign [positive or negative]
- 11 bits for exponent 1.5e-5 1.5 x 10-5 [exponent is
-5
] the range is[-1022, 1023]
. - 52 bits for significant digits
For the sake of simplicity, significant digits are all digits except leading and trailing zeros.
For example, 0.25 has two significant digits, 0.125 has three significant digits, and 12.25 has four significant digits.
[1.25]10 = [1×20 + 0x2-1 + 1×2-2]10 = [1.01]2
Some numbers have a finite binary representation, but some don’t, e.g., 0.1
. It’s 01.0001100110011...
in binary.
Because of this, Python can only use approximate float representations for those numbers.
Python float class
The float[]
returns a floating-point number based on a number or a string. For example:
>>> float[0.1] 0.1 >>> float['1.25'] 1.25
Code language: JavaScript [javascript]
If you pass an object [obj
] to the float[obj]
, it’ll delegate to the obj.__float__[]
. If the __float__[]
is
not defined, it’ll fall back to __index__[]
.
If you don’t pass any argument to the float[]
, it’ll return 0.0
When you use the print[]
function, you’ll see that the number 0.1
is represented as 0.1
exactly.
Internally, Python can only represent 0.1
approximately.
To see how Python represents the 0.1
internally, you can use the format[]
function.
The following shows how Python represents the number 0.1 using 20 digits:
Code language: JavaScript [javascript]
>>> format[0.1, '.20f'] '0.10000000000000000555'
As you can
see, 0.1
is not exactly 0.1
but 0.10000000000000000555...
Because Python can represent some floats approximately, it will cause many problems when you compare two floating-point numbers.
Equality testing
Let’s take a look at the following example:
Code language: PHP [php]
x = 0.1 + 0.1 + 0.1 y = 0.3 print[x == y]
Output:
Code language: PHP [php]
False
Internally, Python cannot use a finite number of digits to represent the numbers x
and y
:
Code language: PHP [php]
print[format[x, '.20f']] print[format[y, '.20f']]
Output:
Code language: CSS [css]
0.30000000000000004441 0.29999999999999998890
Note that the number of digits is infinite. We just show the first 20 digits.
One way to work around this problem is to round both sides of the equality expression to a number of significant digits. For example:
Code language: PHP [php]
x = 0.1 + 0.1 + 0.1 y = 0.3 print[round[x, 3] == round[y, 3]]
Output:
Code language: PHP [php]
True
This workaround doesn’t work in all cases.
PEP485 provides a solution that fixes this problem by using relative and absolute tolerances.
It provides the isclose[]
function from the math
module returns
True
if two numbers are relatively close to each other.
The following shows the isclose[]
function signature:
isclose[a, b, rel_tol=1e-9, abs_tol=0.0]
For example:
Code language: JavaScript [javascript]
from math import isclose x = 0.1 + 0.1 + 0.1 y = 0.3 print[isclose[x,y]]
Output:
Code language: PHP [php]
True
Summary
- Python uses
float
class to represent real numbers. - Python uses a fixed number of bytes [8 bytes] to represent floats. Therefore, it can represent some numbers in binary approximately.
- Use the
isclose[]
function from the math module to test equality for floating-point numbers.
Did you find this tutorial helpful ?