Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

Mastering Numbers, Type Conversion, and Mathematics in Python

Mastering Numbers, Type Conversion, and Mathematics in Python

Discover how Python handles numeric data, the nuances of type conversion, and the powerful math utilities available for everyday programming.

Number Data Types in Python

Python categorizes numbers into three core types: int for whole numbers, float for real numbers with fractional parts, and complex for numbers with real and imaginary components. The presence of a decimal point distinguishes int from float (e.g., 5 is an integer, 5.0 is a float). Complex numbers follow the x + yj notation, where x is the real part and y the imaginary part.

Use type() to inspect a value’s class and isinstance() to verify membership in a particular type. For example:

a = 5

print(type(a))

print(type(5.0))

c = 5 + 3j
print(c + 3)

print(isinstance(c, complex))

Output:

<class 'int'>
<class 'float'>
(8+3j)
True

Integers in Python have arbitrary precision; floats retain about 15 decimal digits of accuracy. For developers working with binary, hexadecimal, or octal representations, Python offers convenient prefixes:

Number SystemPrefix
Binary0b or 0B
Octal0o or 0O
Hexadecimal0x or 0X

Examples:

# Output: 107
print(0b1101011)

# Output: 253 (251 + 2)
print(0xFB + 0b10)

# Output: 13
print(0o15)

Result:

107
253
13

Type Conversion (Coercion)

Python automatically promotes integers to floats during arithmetic when a float operand is involved. For instance:

>>> 1 + 2.0
3.0

Explicit conversions are equally straightforward with int(), float(), and complex(), which can also parse strings:

>>> int(2.3)
2
>>> int(-2.8)
-2
>>> float(5)
5.0
>>> complex('3+5j')
(3+5j)

When converting a float to an int, Python truncates the decimal portion rather than rounding.

Python Decimal

Floating‑point arithmetic can produce surprising results due to binary representation limits. For example:

>>> (1.1 + 2.2) == 3.3
False

Because numbers like 0.1 cannot be represented exactly in binary, operations yield small rounding errors. The decimal module mitigates this by providing arbitrary‑precision decimal arithmetic:

import decimal

print(0.1)
print(decimal.Decimal(0.1))

Output:

0.1
0.1000000000000000055511151231257827021181583404541015625

Using Decimal preserves significant digits and exact decimal representations, essential for financial calculations:

from decimal import Decimal as D

print(D('1.1') + D('2.2'))
print(D('1.2') * D('2.50'))

Output:

3.3
3.000

Because decimal operations are slower than binary floats, reserve Decimal for scenarios requiring exact precision, such as monetary values, configurable precision, or significant‑digit control.

When to Use Decimal Instead of Float?

Python Fractions

The fractions module offers rational number support, enabling exact arithmetic with numerator and denominator as integers:

import fractions

print(fractions.Fraction(1.5))
print(fractions.Fraction(5))
print(fractions.Fraction(1,3))

Output:

3/2
5
1/3

Creating a Fraction from a float can produce unintuitive results due to binary rounding, so prefer string inputs for decimal numbers:

import fractions

# From float
print(fractions.Fraction(1.1))
# From string
print(fractions.Fraction('1.1'))

Output:

2476979795053773/2251799813685248
11/10

Fractions support all arithmetic operators:

from fractions import Fraction as F

print(F(1, 3) + F(1, 3))
print(1 / F(5, 6))
print(F(-3, 10) > 0)
print(F(-3, 10) < 0)

Output:

2/3
6/5
False
True

Python Mathematics

Python’s math module supplies functions for trigonometry, logarithms, factorials, and more:

import math

print(math.pi)
print(math.cos(math.pi))
print(math.exp(10))
print(math.log10(1000))
print(math.sinh(1))
print(math.factorial(6))

Output:

3.141592653589793
-1.0
22026.465794806718
3.0
1.1752011936438014
720

For randomness and sampling, the random module offers:

import random

print(random.randrange(10, 20))

x = ['a', 'b', 'c', 'd', 'e']
print(random.choice(x))
random.shuffle(x)
print(x)
print(random.random())

Sample output (values vary):

18
e
['c', 'e', 'd', 'b', 'a']
0.5682821194654443

Both modules provide comprehensive documentation detailing all available functions and attributes.

Python

  1. Decoding Numbers and Symbols in Electronics
  2. Converting Octal and Hexadecimal Numbers to Decimal: A Practical Guide
  3. Mastering C# Type Conversion: Implicit, Explicit, Parse, and Convert Methods
  4. Understanding C++ Type Conversion: Implicit, Explicit, and Casting Techniques
  5. Python Keywords and Identifiers: Mastering Reserved Words and Naming Conventions
  6. Mastering Python Type Conversion & Casting: A Comprehensive Guide
  7. Python Namespaces & Variable Scope: Understanding Names, Bindings, and Scopes
  8. Understanding type() and isinstance() in Python: Practical Examples
  9. Understanding Type Conversion in C#: Implicit & Explicit Casting Explained
  10. Python Numbers: Understanding Immutable Numeric Data Types