Numpy Math Functions
We can perform various mathematical operations upon Numpy ndarrays. There are many functions to carry out trigonometric and arithmetic mathematical functions provided by Numpy. There are many functions available for performing operations on complex numbers.
Trigonometric functions
We can perform several basic and standard functions to perform trigonometric operations. Standard trigonometric functions return trigonometric ratios for given angles in radians.
import numpy as np angls = np.array([-30,0,30,45,60,90]) print('Sine of different angles:\n') # Convert to radians by multiplying with pi/180 print(np.sin(angls*np.pi/180)) print('\n') print('Cosine values for angles in array:') print(np.cos(angls*np.pi/180)) print('\n') print('Tangent values for given angles:') print(np.tan(angls*np.pi/180)) #Output Sine of different angles: [-0.5 0. 0.5 0.70710678 0.8660254 1. ] Cosine values for angles in array: [8.66025404e-01 1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01 6.12323400e-17] Tangent values for given angles: [-5.77350269e-01 0.00000000e+00 5.77350269e-01 1.00000000e+00 1.73205081e+00 1.63312394e+16]
import numpy as np a = np.array([0,30,45,60,90]) print('===========sin values======\n') sin_val = np.sin(a*np.pi/180) print('Sin of angles',sin_val) print('=====inverse===============n.') inv_of_sin = np.arcsin(sin_val) print(inv_of_sin) print('=======Check result=======\n') print(np.degrees(inv_of_sin)) #Output ===========sin values====== Sin of angles [0. 0.5 0.70710678 0.8660254 1. ] =====inverse===============n. [0. 0.52359878 0.78539816 1.04719755 1.57079633] =======Check result======= [ 0. 30. 45. 60. 90.]
Functions to round off values
There are functions like around(), floor() and ceil() to round off the array items. These methods are applicable on numbers only.
The numpy.around() function
This function returns the rounded value to the desired precision. The syntax of this method is,
numpy.around(arr,decimals)The arr represents input array and the decimals represent the number of decimals to round off. the default value of this parameter is 0. If it is set to 0, the number is rounded to the left of the decimal position.
import numpy as np arr = np.array([3.0,37.55, 168, 1.567, 0.132]) print('=====Array arr========\n') print(arr) print('=====rounded arrays======\n') print(np.around(arr)) print(np.around(arr, decimals = 1)) print(np.around(arr, decimals = -1)) #Output =====Array arr======== [3.000e+00 3.755e+01 1.680e+02 1.567e+00 1.320e-01] =====rounded arrays====== [ 3. 38. 168. 2. 0.] [3.00e+00 3.76e+01 1.68e+02 1.60e+00 1.00e-01] [ 0. 40. 170. 0. 0.]
The numpy.round_() function
numpy.round_(arr, decimals = 0, out = None)
For example,
import numpy as np arr = [.50, 1.49, 1.5, 5.5, 6.5, 10.1, 0.558, -6.4,-0.36] print ("Original array : \n", arr) round_off_values = np.round_(arr) print ("\nOutput values : \n", round_off_values) round_off_values = np.round_(arr, decimals = 1) print ("\nOutput values : \n", round_off_values) #Ouput Original array : [0.5, 1.49, 1.5, 5.5, 6.5, 10.1, 0.558, -6.4, -0.36] Output values : [ 0. 1. 2. 6. 6. 10. 1. -6. -0.] Output values : [ 0.5 1.5 1.5 5.5 6.5 10.1 0.6 -6.4 -0.4]
The numpy.floor() function
For example,
import numpy as np nums=np.array([12.368, 17.8, 2000, 0.368, -12.32, 752.9234]) print(np.floor(nums)) #Output [ 12. 17. 2000. 0. -13. 752.]
The numpy.ceil() function
This method can be applied to get the ceiling value of the array items which is the smallest integer value greater than the array element.
For example,
import numpy as np nums=np.array([12.368, 17.8, 2000, 0.368, -12.32, 752.9234]) print("Ceil values of array\n",np.ceil(nums)) #Output Ceil values of array [ 1.30e+01 1.80e+01 2.00e+03 1.00e+00 -1.20e+01 7.53e+02]
Other, important functions are
The numpy.rint() round to nearest integer towards zero.
The numpy.fix() round to nearest integer towards zero.
The numpy.rint() round to nearest integer towards zero.
The numpy.fix() round to nearest integer towards zero.
The numpy.trunc() returns the truncated value of the input, element-wise
logarithmic and Exponent Functions
There are various functions provided by the Numpy to calculate logarithmic and exponent values of the array items.
For example,
import numpy as np arr = [2, 3, 4, 5] print ("Original array : \n", arr) exp_values = np.exp(arr) print ("\nExp values : \n", exp_values) log_values = np.log(arr) #natural log print ("\nLog values : \n", log_values) #Output Original array : [2, 3, 4, 5] Exp values : [ 7.3890561 20.08553692 54.59815003 148.4131591 ] Log values : [0.69314718 1.09861229 1.38629436 1.60943791]
- The numpy.expm1() function is used to calculate exp(x) – 1 for all elements in the array.
- The numpy.exp2() function can be used to calculate 2**p for all p in the input array.
- The numpy.log2() returns base-2 logarithm of x.
- The numpy.log10()function returns the base 10 logarithms of the input array, for each item.
- The numpy.log1p()function returns the natural logarithm of one plus the input array, element-wise.
- The numpy.logaddexp() function returns the logarithm of the sum of the exponentiations of the inputs.
- The numpy.logaddexp2()function returns the logarithm of the sum of exponentiations of the inputs in base-2.
Numpy Arithmetic functions
We can apply several arithmetic functions to all the elements in an array to perform general arithmetic operations such as divide(), multiply(), add(), subtract() etc.
import numpy as np arr1 = [[8, 3, 6],[2, 1, 5],[3, 12, 10]] arr2 = [[2, 1, 4],[5, 1, 2],[3, 2, 2]] print("Array 1: \n", arr1) print("Array 2: \n", arr2) print("Div = \n", np.divide(arr1, arr2)) print("Mul = \n", np.divide(arr1, arr2)) print("Mod = \n", np.mod(arr1, arr2)) #Output Array 1: [[8, 3, 6], [2, 1, 5], [3, 12, 10]] Array 2: [[2, 1, 4], [5, 1, 2], [3, 2, 2]] Div = [[4. 3. 1.5] [0.4 1. 2.5] [1. 6. 5. ]] Mul = [[4. 3. 1.5] [0.4 1. 2.5] [1. 6. 5. ]] Mod = [[0 0 2] [2 0 1] [0 0 0]]
- The numpy.add() is used to add arguments item-wise.
- The numpy.positive() is used to calculate numerical positive, item-wise.
- The numpy.negative()is used to calculate numerical negative, item-wise.
- The numpy.multiply()is used to multiply arguments item-wise.
- The numpy.power(), method first array items raised to powers from second array, item-wise.
- The numpy.subtract() is used to calculate subtract arguments, item-wise.
- The numpy.true_divide() function returns a true division of the inputs, item-wise.
- The numpy.floor_divide() function returns the largest integer smaller or equal to the division of the inputs.
- The numpy.float_power() function first array items raised to powers from second array, item-wise.
- The numpy.mod() function returns the item-wise remainder of division.
- The numpy.remainder() function return item-wise remainder of division.
- The numpy.divmod() function return item-wise quotient and remainder simultaneously.
Complex number functions
Numpy offers many functions to work with complex numbers.
import numpy as np print("check if Real ? ", np.isreal([10+1j, 0j]), "\n") print("check if Real ? ", np.isreal([10, 15]), "\n") #Output check if Real ? [False True] check if Real ? [ True True]
For example get the conjugate of imaginary numbers,
import numpy as np complx1 = np.array([10+3j, 8+4j]) conj_complx1 = np.conj(complx1) print ("conjugated complex numbers\n ", conj_complx1) complx2 =np.array([6-7j, 4-3j]) conj_complx2 = np.conj(complx2) print ("conjugated complex numbers\n", conj_complx2) #Output conjugated complex numbers [10.-3.j 8.-4.j] conjugated complex numbers [6.+7.j 4.+3.j]
Other mathematical functions
- The numpy.convolve() function returns the discrete, linear convolution of two one-dimensional sequences.
- The numpy.cbrt() function return the non-negative cube-root of an array, item-wise.
- The numpy.sqrt() function return the non-negative square-root of an array, item-wise.
- The numpy.square() function return the item-wise square of the input.
- The numpy.absolute() function calculate the absolute value item-wise.
- The numpy.fabs() function compute the absolute values item-wise.
- The numpy.sign() function returns an item-wise indication of the sign of a number.
- The numpy.interp() function returns one-dimensional linear interpolation.
- The numpy.maximum() function returns item-wise maximum of array items.
- The numpy.minimum() function returns item-wise minimum of array items.
- The numpy.real_if_close(), If complex input returns a real array if complex parts are close to zero.
- The numpy.nan_to_num() function replaces NaN with zero and infinity with large finite numbers.
- The numpy.heaviside() function computes the Heaviside step function.
For example,
import numpy as np nums = np.array([16, 27, 25, 32, 81]) print('Original array\n') print(nums) print ("Square root\n ", np.sqrt(nums)) print ("cube root\n ", np.cbrt(nums)) print ("Abs values\n ", np.fabs(np.sqrt(nums))) print ("Convolve values\n ", np.convolve(np.sqrt(nums),1)) #Output Original array [16 27 25 32 81] Square root [4. 5.19615242 5. 5.65685425 9. ] cube root [2.5198421 3. 2.92401774 3.1748021 4.32674871] Abs values [4. 5.19615242 5. 5.65685425 9. ] Convolve values [4. 5.19615242 5. 5.65685425 9. ]