Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟒 BeginnerπŸ”΅ Advanced
What are Variables?Numbers β€” Integers and FloatsNumber OperationsStrings β€” Creating and Using TextString FormattingBooleans and NoneType ConversionGetting User InputBest Practices
Python/Variables Data Types/Numbers Integers Floats

πŸ”’ Numbers β€” Deep Dive into Integers and Floats

Explore the internal mechanics of Python's numeric types, floating-point precision, and advanced numeric concepts.


🎯 Integer Internals and Arbitrary Precision

Python's `int` type is uniqueβ€”it has unlimited precision. Unlike most languages, integers can grow as large as your system's memory allows.

# Arbitrary precision integers
big_num = 10 ** 1000
print(len(str(big_num)))  # 1001 digits

# Integer representation
x = 42
print(x.bit_length())     # 6 bits needed
print(bin(x))             # '0b101010'
print(x.to_bytes(1, 'big'))  # Convert to bytes

Key insight: Python stores integers as objects with metadata. Small integers (-5 to 256) are cached for performance.


πŸ’‘ Floating-Point Precision and IEEE 754

Floats follow IEEE 754 standard, causing subtle precision issues. Understanding this prevents bugs.

# Precision limits
print(0.1 + 0.2)          # 0.30000000000000004 (not 0.3)
print(0.1 + 0.2 == 0.3)   # False

# Why? 0.1 cannot be exactly represented in binary
print(f"{0.1:.20f}")      # 0.10000000000000000555

# Safe comparison
from decimal import Decimal
Decimal('0.1') + Decimal('0.2') == Decimal('0.3')  # True

Best practice: Use `decimal.Decimal` for financial calculations; use `math.isclose()` for approximate comparisons.


🎨 Special Float Values

import math

# Infinity and NaN
pos_inf = float('inf')
neg_inf = float('-inf')
nan = float('nan')

print(pos_inf + 1 == pos_inf)    # True (infinity arithmetic)
print(nan == nan)                 # False (NaN is never equal to anything)
print(math.isnan(nan))            # True (proper NaN check)
print(math.isinf(pos_inf))        # True
print(math.isfinite(42.0))        # True

# Negative zero exists in floats
neg_zero = -0.0
print(neg_zero == 0.0)            # True (but different bits)
print(1 / neg_zero)               # -inf
print(1 / 0.0)                    # inf

πŸ”‘ Complex Numbers

Python has built-in support for complex numbers with real and imaginary parts.

# Creating complex numbers
z1 = 3 + 4j
z2 = complex(3, 4)  # Same as above

print(z1.real)      # 3.0
print(z1.imag)      # 4.0
print(abs(z1))      # 5.0 (magnitude)
print(z1.conjugate())  # (3-4j)

# Operations
z3 = 2 + 3j
print(z1 + z3)      # (5+7j)
print(z1 * z3)      # (-6+17j)
print(z1 / z3)      # (1.23...-0.15...j)

# Practical use: signal processing, physics simulations
import cmath
print(cmath.sqrt(-1))  # 1j (imaginary unit)

πŸ“Š Numeric Type Conversions and Stability

# Conversion precedence
print(int(3.7))          # 3 (truncates, doesn't round)
print(round(3.7))        # 4 (rounds to nearest even)
print(float(42))         # 42.0

# Integer division vs float division
print(10 / 3)            # 3.333... (float division)
print(10 // 3)           # 3 (integer division, floor)
print(10 % 3)            # 1 (modulo)

# Safe type checking
from numbers import Real, Integral
print(isinstance(3, Integral))   # True
print(isinstance(3.0, Real))     # True
print(isinstance(3.0, Integral)) # False

Stability tip: Avoid accumulating small floating-point errors. Sum from smallest to largest to minimize precision loss:

values = [0.1, 0.1, 1e-15, 0.1]
print(sum(values))  # Slightly inaccurate
print(sum(sorted(values)))  # More accurate

πŸ”— Advanced Operations with `math` and `operator` Modules

import math
import operator

# Math module functions
print(math.ceil(3.2))      # 4
print(math.floor(3.8))     # 3
print(math.trunc(3.8))     # 3 (truncate towards zero)
print(math.fabs(-5))       # 5.0 (absolute, returns float)

# Power and roots
print(math.pow(2, 10))     # 1024.0
print(2 ** 10)             # 1024 (preferred for integers)
print(math.sqrt(16))       # 4.0
print(16 ** 0.5)           # 4.0

# Logarithms
print(math.log(100, 10))   # 2.0 (log base 10)
print(math.log10(100))     # 2.0
print(math.log(1))         # 0.0
print(math.log(0))         # ValueError

# Trigonometry
print(math.sin(math.pi / 2))  # 1.0
print(math.cos(0))            # 1.0

# GCD and LCM
print(math.gcd(48, 18))       # 6
print(math.lcm(12, 18))       # 36 (Python 3.9+)

πŸ”‘ Key Takeaways

ConceptRemember
Int PrecisionPython ints have unlimited precision; small ints (-5 to 256) are cached
Float PrecisionIEEE 754 causes rounding; use `Decimal` for financial data
Special Values`inf` and `nan` have special comparison rules; use `math.isnan()`, `math.isinf()`
Complex NumbersBuilt-in support with `.real`, `.imag`, `.conjugate()` properties
Type StabilityUse `numbers` module for robust type checking; order operations carefully

πŸ”— What's Next?

Explore Number Operations to master bitwise operators and the full range of numeric operations.


Ready to practice? Challenges | Quiz


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep β€’ Build Real β€’ Verify Skills β€’ Launch Forward

Courses

PythonFastapiReactJSCloud

Β© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn