Thursday, March 14, 2024

Python Tutorials: Exploring Basic Operations with Built-in Numerics


Welcome back to another article! Today, we’re going to dive into the fascinating world of operations that can be performed on built-in numeric types in Python.

Basic Operations

All numeric types in Python support basic mathematical operations effortlessly:

a, b = 5, 2

# Sum

a + b

# 7

# Difference

a - b

# 3

# Product

a * b

# 10

# Quotient

a / b

# 2.5

# Exponentiation

a ** b

# 25


Even boolean values support these operations since they are a subclass of integers:

False ** True

# 0

True ** False

# 1

However, complex numbers don't support certain operations:

a, b = 5, 2.1

# Floored quotient

a // b

# 2

# Remainder

a % b

# 1

# Quotient and remainder

divmod(a, b)

# (2, 1)

Modifying the sign of a numeric is also possible:

a = -3

# Negate

-a

# 3

# Absolute value

abs(a)

# 3


Converting between numeric types is straightforward:

i = 1

f = 2.0

# To integer

int(f)

# 2

# To floating point number

float(i)

# 1.0

# To complex number

complex(i, f)

# (1+2j)


Real Numbers

Real numbers in Python, based on the `numbers.Real` class, can undergo certain operations unique to them:

import math

# Truncate to integer

math.trunc(1.23123)

# 1

# Round to nearest integer

round(12.6)

# 13

# Nearest least integer

math.floor(1.6)

# 1

# Nearest greater integer

math.ceil(1.3)

# 2

Integers

Integers, as integral numbers, have specific operations tailored for them:

i = 10 

# Number of necessary bits to represent the integer

i.bit_length()

# 4

# Number of bits set to one

i.bit_count()

# 2

# Array of bytes representing integer

i.to_bytes(2, byteorder='big')

# b'\x00\n'

# Create an integer from a byte array

int.from_bytes(b'\x00\n')

# 10


Bitwise operations are also available for integers:

a = 5

b = 4

# Bitwise OR

a | b

# 5

# Bitwise XOR

a ^ b

# 1

# Bitwise AND

a & b

# 4

# Left shift

a << 2

# 20

# Right shift

a >> 2

# 1


Floats

Floats offer unique values and operations:

f = 2.5

# Integer ratio representation

f.as_integer_ratio()

# (5, 2)

# Check if it has an integral value

f.is_integer()

# False

# Hexadecimal string representation

f.hex()

# '0x1.4000000000000p+1'

# Float equivalent to hexadecimal string

float.fromhex('0x1.4000000000000p+1')

# 2.5

Lastly, all numerics support hashing, making them suitable for dictionary keys or set values. Stay tuned for more fascinating insights into Python's numeric operations!

0 comments:

Post a Comment