In Python, floating point numbers (float
) are used to represent real numbers, both positive and negative, with a precision that depends on the machine implementation.
These numbers can include a fractional part and are represented using the IEEE 754 floating point standard.
Floating point numbers in Python can be declared using standard decimal notation:
numero_float = 3.14159
They can also be expressed in scientific notation, using the letter e
to indicate the power of ten:
numero_cientifico = 6.022e23 # 6.022 × 10^23
Operations with Floating Point Numbers
Python supports basic mathematical operations with floating point numbers, such as addition, subtraction, multiplication, and division:
# Addition
suma = 3.14 + 2.71
print(suma) # Output: 5.85
# Subtraction
resta = 10.5 - 4.2
print(resta) # Output: 6.3
# Multiplication
multiplicacion = 2.5 * 4.0
print(multiplicacion) # Output: 10.0
# Division
division = 10.0 / 3.0
print(division) # Output: 3.3333333333333335 (limited precision due to binary representation)
Advanced Operations
Python also allows for other advanced operations with floating point numbers, such as exponentiation and trigonometric calculations using the math
module:
import math
# Exponentiation
potencia = math.pow(2.0, 3.0)
print(potencia) # Output: 8.0
# Sine
seno_valor = math.sin(math.pi / 2)
print(seno_valor) # Output: 1.0 (sine of 90 degrees in radians)
Precision and Rounding
Floating point numbers in Python have limited precision due to binary representation. This is common to most programming languages.
It is important to keep this in mind as it can lead to unexpected results in certain calculations:
# Addition with limited precision
suma_precisa = 0.1 + 0.2
print(suma_precisa) # Output: 0.30000000000000004 (limited precision)
Due to limited precision, direct comparisons between floating point numbers may not be exact:
a = 0.1 + 0.2
b = 0.3
print(a == b) # Output: False (due to limited precision)
Infinity and Not-a-Number (NaN)
Python also handles special values like infinity (inf
) and Not-a-Number (NaN
) to represent results outside of normal numerical limits:
# Positive infinity
infinito_positivo = float('inf')
print(infinito_positivo) # Output: inf
# Not-a-Number
nan_valor = float('nan')
print(nan_valor) # Output: nan
Conversion Between Types
It is possible to convert other data types to floating point numbers using the float()
function:
texto = "3.14"
numero_float = float(texto)
print(numero_float) # Output: 3.14
Floating point objects in Python also have useful methods, such as is_integer()
to check if the number is an integer:
numero = 3.0
print(numero.is_integer()) # Output: True (the number 3.0 is an integer)