Numpy Math functions — Python2

Naraekang
Jul 17, 2022

Math function

  • The function applies to each element without a loop
import math as mnumbers = [0,1,4,9,16,25]square_roots = []
for a_number in numbers:
# Append to new list
square_roots.append(m.sqrt(a_number))
print(square_roots)
# print list
import NumPy as np square_roots = np.sqrt(numbers)
print(square_roots)
  • Unary function: Take the single argument
  • Binary universal function
  • ex) Max: Compare two arrays → result has the max of two elements in each location
a =  np.random.rand(10)
b = np.random.rand(10)
c = np.maximum(a,b)
  • faster than writing a loop

read official documentation: Give an idea of what library types are available.

Vectorized operation is faster than loop

Example

import math as m 
def using_loops():
coordinates = range(-99,100)
matrix = list() for x in coordinates:
# hold the result of our calculation
row = list()
for y in coordinates:
row.append(m.sqrt(x ** 2 + y**2))
matrix.append(row)
return matrix
print(matrix)

--

--