Decode Math Symbols with Python: From Summation to Matrix Multiplication
Learn how to translate common mathematical symbols such as summation, product, factorial, conditional expressions, and matrix multiplication into clear Python code, revealing the underlying computations and helping data scientists and ML practitioners deepen their mathematical intuition through practical examples.
Summation and Product Operators
Mathematical summation (∑) and product (∏) symbols can be expressed as simple loops in Python. The following snippets illustrate how a list of numbers is summed or multiplied to produce the same result as the mathematical notation.
x = [1, 2, 3, 4, 5, 6]
result = 0
for i in range(6):
result += x[i]
print(result) # 21The product operator works similarly, but uses multiplication instead of addition.
x = [1, 2, 3, 4, 5, 1]
result = 1
for i in range(6):
result *= x[i]
print(result) # 120Factorial
The factorial symbol (!) can be computed by iterating from 1 to n and accumulating the product.
result = 1
for i in range(1, 6):
result *= i
print(result) # 120Conditional Brackets (Piecewise Functions)
Conditional expressions that select different formulas based on a condition correspond to if‑elif‑else statements in code.
i = 3
y = [-2, 3, 4, 1]
result = 0
if i in y:
result = sum(y)
elif i > 0:
result = 1
else:
result = 0
print(result) # 6Pointwise (Element‑wise) Multiplication
When two matrices have the same shape, their element‑wise product can be computed with nested loops.
y = [[2, 1], [4, 3]]
z = [[1, 2], [3, 4]]
x = [[0, 0], [0, 0]]
for i in range(len(y)):
for j in range(len(y[0])):
x[i][j] = y[i][j] * z[i][j]
print(x) # [[2, 2], [12, 12]]Matrix Multiplication (Dot Product)
True matrix multiplication combines rows of the first matrix with columns of the second using the dot product. Using numpy.dot simplifies the implementation.
y = [[1, 2], [3, 4]]
z = [[2], [1]]
# x will have shape [2, 1]
x = [[0], [0]]
for i in range(len(y)):
for j in range(len(z)):
x[i][j] = np.dot(y[i], [z[k][j] for k in range(len(z))])
print(x) # [[4], [10]]These concise code examples demonstrate how translating mathematical symbols into Python not only executes the calculations but also deepens understanding of the underlying concepts, a valuable skill for anyone working in data science or machine learning.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
