Universal Functions

NumPy provides standard trigonometric functions, functions for arithmetic operations, handling complex numbers, statistical functions,etc. In NumPy, these are called “universal functions”(ufunc).

import numpy as np

Trigonometric Functions

angles = np.array([0,30,45,60,90]) 

Angles need to be converted to radians by multiplying by pi/180

Only then can we appy trigonometric functions to our array

angles_radians = angles * np.pi/180
angles_radians
array([0.        , 0.52359878, 0.78539816, 1.04719755, 1.57079633])
print('Sine of angles in the array:')
print(np.sin(angles_radians))      
Sine of angles in the array:
[0.         0.5        0.70710678 0.8660254  1.        ]

Alternatively, use the np.radians() function to convert to radians

angles_radians = np.radians(angles)
angles_radians
array([0.        , 0.52359878, 0.78539816, 1.04719755, 1.57079633])
print('Cosine of angles in the array:')
print(np.cos(angles_radians))
Cosine of angles in the array:
[1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01
 6.12323400e-17]
print('Tangent of angles in the array:')
print(np.tan(angles_radians))
Tangent of angles in the array:
[0.00000000e+00 5.77350269e-01 1.00000000e+00 1.73205081e+00
 1.63312394e+16]

arcsin, arcos, and arctan functions return the trigonometric inverse of sin, cos, and tan of the given angle. The result of these functions can be verified by numpy.degrees() function by converting radians to degrees.

sin = np.sin(angles * np.pi/180) 
print ('Compute sine inverse of angles. Returned values are in radians.')

inv = np.arcsin(sin) 
print (inv) 
Compute sine inverse of angles. Returned values are in radians.
[0.         0.52359878 0.78539816 1.04719755 1.57079633]

np.degrees() converts radians to degrees

print ('Check result by converting to degrees:' )
print (np.degrees(inv)) 
Check result by converting to degrees:
[ 0. 30. 45. 60. 90.]

Statistical Functions

test_scores = np.array([32.32, 56.98, 21.52, 44.32, 
                        55.63, 13.75, 43.47, 43.34])
print('Mean test scores of the students: ')
print(np.mean(test_scores))
Mean test scores of the students: 
38.91625
print('Median test scores of the students: ')
print(np.median(test_scores))
Median test scores of the students: 
43.405

We will now perform basic statistical methods on real life dataset. We will use salary data of 1147 European developers.

salaries = np.genfromtxt('data/salary.csv', 
                         delimiter=',')
salaries
array([60000., 58000., 56967., ..., 54647., 25000., 70000.])
salaries.shape
(1147,)
mean     = np.mean(salaries)
median   = np.median(salaries)
sd       = np.std(salaries)
variance = np.var(salaries)
print('Mean = %i' %mean)
print('Median = %i' %median)
print('Standard Deviation = %i' %sd)
print('Variance = %i' %variance)
Mean = 55894
Median = 48000
Standard Deviation = 55170
Variance = 3043770333