Python Floats
What Are Floats?
A floating-point number (float) is a number that has a decimal point or is written using scientific notation. Floats are used to represent real numbers, including fractions and numbers with a fractional part.
Creating Floats
You can create floats by writing numbers with a decimal point, using scientific notation, or with the float()
constructor:
x = 3.14
negative = -2.5
zero = 0.0
sci = 1.5e3 # 1500.0
from_string = float("2.718")
from_int = float(42)
Float Operations
Floats support all standard arithmetic operations:
a = 7.5
b = 2.0
print(a + b) # 9.5
print(a - b) # 5.5
print(a * b) # 15.0
print(a / b) # 3.75
print(a // b) # 3.0 (floor division, returns float)
print(a % b) # 1.5
print(a ** b) # 56.25
Special Float Values
Python floats can represent special values:
import math
print(float('inf')) # Infinity
print(float('-inf')) # Negative infinity
print(float('nan')) # Not a Number (NaN)
print(math.isinf(float('inf'))) # True
print(math.isnan(float('nan'))) # True
Float Methods
Python's float type includes several useful methods:
x = 3.5
print(x.as_integer_ratio()) # (7, 2)
print(x.is_integer()) # False
print(x.hex()) # '0x1.c000000000000p+1'
print(float.fromhex('0x1.c000000000000p+1')) # 3.5
Converting Other Types to float
You can convert integers, strings, and other numeric types to float using float()
:
print(float(5)) # 5.0
print(float("2.5")) # 2.5
Precision and Representation
Floats are usually implemented using double in C, which means they have limited precision (about 15-17 decimal digits). Some decimal numbers cannot be represented exactly as floats, which can lead to small rounding errors.
You can check the precision and limits of floats on your system:
import sys
print(sys.float_info)
Summary
- Floats represent real numbers with a decimal point or in scientific notation.
- Support arithmetic operations and special values (inf, nan).
- Have methods for ratio, integer check, and hexadecimal conversion.
- Use
float()
to convert other types to floats. - Limited precision can lead to rounding errors.