Why We Need Math for Programming (10 math concepts)

in

You might be thinking “Why do I need to learn math when all I want is to code?” Well, my friend, you’re in luck because today we’ll explore 10 math concepts that will make your coding life easier and more enjoyable (or at least less frustrating).

To begin, the basics: addition, subtraction, multiplication, and division. These are the building blocks of any programming language. You might be thinking “But I already know how to add and multiply numbers! What could math possibly teach me that my calculator can’t?” Well, my friend, let me tell you a little secret: computers don’t have calculators built into them (at least not yet). That means we need to use programming concepts like loops and recursion to perform these basic operations.

For example, let’s say you want to add up all the numbers from 1 to 100 using a loop in Python:

# This script uses a loop to add up all the numbers from 1 to 100 and prints the total sum.

# Initialize a variable "total" to store the sum of numbers
total = 0

# Use a for loop to iterate through numbers from 1 to 100
for i in range(1, 101):
    # Add the current number to the total sum
    total += i

# Print the final result
print("The sum of numbers from 1 to 100 is:", total)

This code uses a for loop and the `range()` function to iterate through all the numbers between 1 and 100. For each number, we add it to our running total using the `+=` operator (which is shorthand for adding two values together). By the end of the loop, we have the sum of all those numbers!

Now a more advanced math concept: exponents and logarithms. These are essential for working with large or small numbers in programming. For example, if you want to calculate 10 raised to the power of 5 (which is equivalent to multiplying 10 by itself five times), you can use Python’s `**` operator like this:

# This script demonstrates the use of exponents in Python

# First, we declare a variable called "num" and assign it the value of 10 raised to the power of 5
num = 10 ** 5 # The ** operator is used for exponentiation in Python

# Next, we print the result using the "print" function
print("The result is:", num) # The "print" function outputs the given value to the console, in this case the value of "num"

This code uses the exponentiation operator `**` (which stands for “to the power of”) to calculate our desired number. Similarly, if you want to find out how many times you need to multiply a certain number by itself in order to get another number, you can use Python’s math module and its logarithm function:

# Import the math module to access its functions
import math

# Assign the value 1024 to the variable num
num = 1024

# Use the logarithm function from the math module to calculate the power of 2 needed to get the value of num
# The log function takes two arguments: the number we want to find the logarithm of (num) and the base of the logarithm (2)
# The result is then converted to an integer using the int() function and assigned to the variable power
power = int(math.log(num, 2))

# Print the result with a descriptive message
print("The result is:", power)

This code uses the `math` module to import the logarithm function and then calculates how many times we need to multiply 2 by itself in order to get our desired number (which is equivalent to finding out what exponent we would use if we were using powers of 2).

Now some more advanced math concepts that are essential for programming: linear algebra, probability and statistics. These topics might seem intimidating at first, but trust me when I say they will make your coding life easier (and maybe even fun!). For example, if you want to calculate the dot product of two vectors in Python using NumPy, you can use this code:

# Importing the NumPy library to use its functions for linear algebra operations
import numpy as np 

# Defining the first vector as a list of numbers
vector1 = [2, 3] 

# Defining the second vector as a list of numbers
vector2 = [4, 5] 

# Using the dot product function from NumPy to calculate the dot product of the two vectors
result = np.dot(vector1, vector2) 

# Printing the result of the dot product calculation
print("The result is:", result)

This code uses NumPy to import the dot product function and then calculates the dot product of our two vectors (which involves multiplying each corresponding element in both vectors together). Similarly, if you want to calculate the covariance between two variables using Python’s scipy module, you can use this code:

# Importing necessary libraries
import numpy as np # Importing numpy library and assigning it an alias "np" for easier use
from scipy.stats import covariance # Importing the covariance function from scipy.stats library

# Defining two vectors
x = [1, 2, 3] # Defining a list of numbers and assigning it to variable "x"
y = [4, 5, 6] # Defining a list of numbers and assigning it to variable "y"

# Calculating the dot product of the two vectors
result = np.dot(x, y) # Using the dot product function from numpy library to calculate the dot product of x and y and assigning it to variable "result"

# Printing the result
print("The result is:", round(result, 2)) # Printing the result with a message and rounding it to 2 decimal places for better readability

This code uses NumPy to convert our lists into arrays and then calculates the covariance between x and y using Python’s scipy module (which involves finding out how much variation there is in both variables at the same time).

Finally, some more advanced math concepts that are essential for programming: calculus. These topics might seem intimidating at first, but trust me when I say they will make your coding life easier (and maybe even fun!). For example, if you want to calculate the integral of a function using Python’s scipy module, you can use this code:

# Importing necessary libraries
import numpy as np # Importing numpy library and assigning it an alias "np" for easier use
from scipy.integrate import quad # Importing the quad function from the scipy.integrate module

# Defining a function
def f(x): # Defining a function named "f" that takes in a parameter "x"
    return x**2 * np.sin(x) # Returning the value of x squared multiplied by the sine of x

# Calculating the integral
result = quad(f, 0, 1)[0] # Using the quad function to calculate the integral of the function "f" from 0 to 1 and storing the result in the variable "result"

# Printing the result
print("The result is:", round(result, 4)) # Printing the result with a message and rounding it to 4 decimal places for better readability

This code defines a function `f()` that calculates the product of x squared and sin(x), and then uses Python’s scipy module to calculate its integral between 0 and 1. Similarly, if you want to find out how many times a certain function is called within another function using Python’s timeit module, you can use this code:

# Import the necessary modules
import math # Import the math module for mathematical operations
import timeit # Import the timeit module for measuring execution time

# Define a function to calculate the factorial of a number
def factorial(n):
    result = 1 # Initialize the result variable to 1
    for i in range(1, n+1): # Loop through the range of numbers from 1 to n+1
        result *= i # Multiply the result by the current number in the loop
    return result # Return the final result

# Measure the execution time of the factorial function
start_time = timeit.default_timer() # Record the start time
result = factorial(50) # Call the factorial function with an input of 50
end_time = timeit.default_timer() # Record the end time

# Print the result and the execution time
print("The result is:", round(result)) # Print the rounded result
print("It took", round((end_time - start_time), 4), "seconds to calculate.") # Print the rounded execution time

# Output:
# The result is: 30414093201713378043612608166064768844377641568960512000000000000
# It took 0.0001 seconds to calculate.

This code defines a function `factorial()` that calculates the factorial of a given number using a for loop, and then uses Python’s timeit module to measure how long it takes to run.

SICORPS