Floats are a built-in numeric data type in Python used to represent real numbers that contain a decimal part. Any real number that has a decimal point is classified as a floating-point number in Python, even if the decimal part is zero (0), e.g., 6.0.
How to Represent a Float
A float can be initialized by adding a decimal point to any number; in fact, a number is classified as a float in Python the moment it contains a decimal point.
Leading and Trailing Decimals
Python allows for shorthand notation where the leading or trailing zero can be omitted.
.5is interpreted as0.55.is interpreted as5.0
Using Scientific Notation in Floats
To represent very large or very small numbers, Python provides the scientific notation e or E. This notation multiplies a number by a power of 10. For those familiar with mathematics, the value after e represents the exponent of 10. For example, 1e3 means 1 × 10³.
Mathematical Representation:
A number in scientific notation is defined as:
Technical Limitations of Floats:
Because numbers are represented in base-2 rather than base-10, some fractions cannot be stored exactly. This introduces small precision errors that are usually insignificant in calculations, but can cause unexpected results in logical comparisons.
The widely know 0.1 + 0.2 Problem:
Due to this binary approximation, floating point numbers should generally not be compared for exact equality (==) in financial or high-precision calculations.
The float() Constructor
We use the float() constructor to convert intergers or compactible strings to floating point numbers
The .is_integer() Method
Floats have a built-in method called .is_integer() which returns True if the float has no fractional part (i.e., it is a whole number).
Do not confuse this withisinstance(). The.is_integer()method checks whether a float's value is mathematically a whole number, whileisinstance()checks the object's type. Even if3.0.is_integer()returnsTrue,isinstance(3.0, float)will still returnTruebecause the object remains a float.
In the first example, 3.0 is stored as a float, but it has no fractional part, so .is_integer() returns True. However, isinstance() still reports that the object is a float.
Summary
- Definition: Floats are numbers with decimal points used for fractional precision.
- Scientific Notation: Supported via e or E for powers of 10 ().
- Comparison: Avoid using
==for floats due to precision ghosts. - Verification: Use
.is_integer()to check if a float represents a whole number.
