Python provides three distinct numerical types: arbitrary-precision integers (int), double-precision floating-point numbers (float), and complex numbers (complex).
flowchart LR
A["Numeric Input"] --> B{"Contains decimal/e?"}
B -- "No" --> C["int (Arbitrary Precision)"]
B -- "Yes" --> D{"Contains 'j'?"}
D -- "No" --> E["float (IEEE 754 Double)"]
D -- "Yes" --> F["complex (real + imag j)"]
int: Unlimited precision integer; expands dynamically in memory as needed without integer overflow bugs.float: Implemented using C double (64-bit IEEE 754 floating-point standard).complex: Stored as two 64-bit floats (real + imag * 1j).import math
from decimal import Decimal, getcontext
def numeric_operations_demo() -> None:
# Large integer handling
large_int: int = 10 ** 30
print(f"2^30 power integer: {large_int}")
# Float precision limitation vs Decimal solution
float_sum: float = 0.1 + 0.2
print(f"Standard float 0.1 + 0.2: {float_sum:.17f}") # 0.30000000000000004
# Financial precision with Decimal module
getcontext().prec = 6
dec1 = Decimal("0.1")
dec2 = Decimal("0.2")
print(f"Decimal 0.1 + 0.2: {dec1 + dec2}") # 0.3 Exact
# Complex number math
c1: complex = 3 + 4j
print(f"Complex Number: {c1}, Magnitude (abs): {abs(c1)}")
if __name__ == "__main__":
numeric_operations_demo()
Decimal for Financial Calculations: Standard float arithmetic introduces precision errors (0.1 + 0.2 != 0.3). Use decimal.Decimal for currency values.//) vs True Division (/): / always returns a float, whereas // returns the integer quotient.math.isclose(): Never compare float values directly with ==; use math.isclose(a, b, rel_tol=1e-9).Write a script that accepts a price as a string "19.99" and tax rate "0.07", computes the total using decimal.Decimal, and prints the result rounded to 2 decimal places.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With