KEMBAR78
Numpy For Mathematical Computing | PDF | Matrix (Mathematics) | Trigonometric Functions
0% found this document useful (0 votes)
64 views41 pages

Numpy For Mathematical Computing

Uploaded by

anakinalt9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views41 pages

Numpy For Mathematical Computing

Uploaded by

anakinalt9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 41

Numpy for mathematical computing:

Introduction to Numpy,
Numpy Array,
Numpy Mathematical Function,
Numpy Trigonometric Function,
Numpy random module,
Numpy String Operation.
NumPy (Numerical Python) is a fundamental library in Python for
numerical computing, particularly known for its efficient handling
of multi-dimensional arrays.

1. Introduction to NumPy:

NumPy provides a powerful N-dimensional array object, ndarray,


which is optimized for numerical operations and offers significant
performance advantages over standard Python lists for large
datasets. It forms the basis for many other scientific computing
libraries in Python.

2. NumPy Array (ndarray):

The core of NumPy is the ndarray object, a homogeneous multi-


dimensional array of fixed size. Arrays can be created from Python
lists or tuples using np.array(), or by using functions
like np.zeros(), np.ones(), np.arange(), and np.linspace(). Key
attributes include shape (dimensions), ndim (number of
dimensions), and dtype (data type of elements).
3. NumPy Mathematical Functions:

NumPy provides a wide range of mathematical functions that


operate element-wise on arrays. These include basic arithmetic
operations (+, -, *, /), exponentiation (np.power()), logarithms
(np.log(), np.log10(), np.log2()), and more. These functions are
often referred to as "Universal Functions" (ufuncs) due to their
ability to operate on arrays of varying shapes and data types
efficiently.

4. NumPy Trigonometric Functions:

NumPy includes a comprehensive set of trigonometric functions,


such as np.sin(), np.cos(), np.tan(), and their inverse counterparts
(np.arcsin(), np.arccos(), np.arctan()). These functions also operate
element-wise on arrays, making it easy to perform trigonometric
calculations on entire datasets.
5. NumPy Random Module (np.random):

The np.random module provides functions for generating various


types of random numbers and random arrays. This includes
functions for generating random integers (np.random.randint()),
random floats (np.random.rand()), and samples from different
probability distributions (e.g., np.random.normal(),
np.random.uniform()). It is crucial for simulations, statistical
analysis, and machine learning tasks.

6. NumPy String Operations:

While NumPy is primarily for numerical operations, it also offers


limited string operations through the np.char module. This module
provides vectorized string functions that can be applied to arrays of
strings, such as np.char.add(), np.char.capitalize(),
np.char.upper(), and np.char.split(). However, for extensive
string manipulation, Python's built-in string methods or
the re module (regular expressions) are generally more suitable.
NumPy Introduction
NumPy(Numerical Python) is a fundamental library for Python numerical
computing. It provides efficient multi-dimensional array objects and various
mathematical functions for handling large datasets making it a critical tool for
professionals in fields that require heavy computation.

Key Features of NumPy


NumPy has various features that make it popular over lists.

 N-Dimensional Arrays: NumPy's core feature is ndarray, a powerful N-


dimensional array object that supports homogeneous data types.

 Arrays with High Performance: Arrays are stored in contiguous memory


locations, enabling faster computations than Python lists (Please see Numpy
Array vs Python List for details).

 Broadcasting: This allows element-wise computations between arrays of


different shapes. It simplifies operations on arrays of various shapes by
automatically aligning their dimensions without creating new data.

 Vectorization: Eliminates the need for explicit Python loops by applying


operations directly on entire arrays.

 Linear algebra: NumPy contains routines for linear algebra operations, such as
matrix multiplication, decompositions, and determinants.

Installing NumPy in Python


To begin using NumPy, you need to install it first. This can be done through pip
command:

pip install numpy


Once installed, import the library with the alias np

import numpy as np
Creating NumPy Arrays
 Using ndarray : The array object is called ndarray. NumPy arrays are created
using the array() function.

Example:
import numpy as np

# Creating a 1D array
x = np.array([1, 2, 3])

# Creating a 2D array
y = np.array([[1, 2], [3, 4]])

# Creating a 3D array
z = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

print(x)
print(y)
print(z)

Output
[1 2 3]

[[1 2]
[3 4]]

[[[1 2]
[3 4]]

[[5 6]
[7 8]]]
 Using Numpy Functions: NumPy provides convenient methods to create arrays
initialized with specific values like zeros and ones:

Example:
import numpy as np

a1_zeros = np.zeros((3, 3))


a2_ones = np.ones((2, 2))
a3_range = np.arange(0, 10, 2)

print(a1_zeros)
print(a2_ones)
print(a3_range)

Output
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]

[[1. 1.]
[1. 1.]]

[0 2 4 6 8]
NumPy Array Indexing
Knowing the basics of NumPy array indexing is important for analyzing and
manipulating the array object.
 Basic Indexing: Basic indexing in NumPy allows you to access elements of an
array using indices.

Example:
import numpy as np

# Create a 1D array
arr1d = np.array([10, 20, 30, 40, 50])

# Single element access


print("Single element access:", arr1d[2])

# Negative indexing
print("Negative indexing:", arr1d[-1])

# Create a 2D array
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Multidimensional array access


print("Multidimensional array access:", arr2d[1, 0])

Output
Single element access: 30
Negative indexing: 50
Multidimensional array access: 4
 Slicing: Just like lists in Python, NumPy arrays can be sliced. As arrays can be
multidimensional, you need to specify a slice for each dimension of the array.

Example:
import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])


#elements from index 1 to 3
print("Range of Elements:",arr[1:4])

#all rows, second column


print("Multidimensional Slicing:", arr[:, 1])

Output
Range of Elements: [[4 5 6]]
Multidimensional Slicing: [2 5]

 Advanced Indexing: Advanced Indexing in NumPy provides more powerful


and flexible ways to access and manipulate array elements.

Example:
import numpy as np
arr = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])

# Integer array indexing


indices = np.array([1, 3, 5])
print ("Integer array indexing:", arr[indices])

# boolean array indexing


cond = arr > 0
print ("\nElements greater than 0:\n", arr[cond])

Output
Elements at indices (0, 3), (1, 2), (2, 1),(3, 0):
[4. 6. 0. 3.]
[ Elements greater than 0:
[2. 4. 4. 6. 2.6 7. 8. 3. 4. 2. ]
NumPy Basic Operations
Element-wise operations in NumPy allow you to perform mathematical operations
on each element of an array individually, without the need for explicit loops.

 Element-wise Operations: We can perform arithmetic operations like addition,


subtraction, multiplication, and division directly on NumPy arrays.

Example:
import numpy as np

x = np.array([1, 2, 3])
y = np.array([4, 5, 6])

# Addition
add = x + y
print("Addition:",add)

# Subtraction
subtract = x - y
print("substration:",subtract)

# Multiplication
multiply = x * y
print("multiplication:",multiply)

# Division
divide = x / y
print("division:", divide)

Output
Addition: [5 7 9]
substration: [-3 -3 -3]
multiplication: [ 4 10 18]
division: [0.25 0.4 0.5 ]
 Unary Operation: These operations are applied to each individual element in
the array, without the need for multiple arrays (as in binary operations).

Example:
import numpy as np

# Example array with both positive and negative values


arr = np.array([-3, -1, 0, 1, 3])

# Applying a unary operation: absolute value


result = np.absolute(arr)
print("Absolute value:", result)

Output
Absolute value: [3 1 0 1 3]

 Binary Operators: Numpy Binary Operations apply to the array elementwise


and a new array is created. We can use all basic arithmetic operators like +, -, /,
etc. In the case of +=, -=, = operators, the existing array is modified.
Example:
import numpy as np

# Two example arrays


arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

# Applying a binary operation: addition


result = np.add(arr1, arr2)

print("Array 1:", arr1)


print("Array 2:", arr2)
print("Addition Result:", result)

Output
Array 1: [1 2 3]
Array 2: [4 5 6]
Addition Result: [5 7 9]
NumPy ufuncs
NumPy provides familiar mathematical functions such as sin, cos, exp, etc. These
functions also operate elementwise on an array, producing an array as output.

Example:
import numpy as np

# create an array of sine values


a = np.array([0, np.pi/2, np.pi])
print ("Sine values of array elements:", np.sin(a))

# exponential values
a = np.array([0, 1, 2, 3])
print ("Exponent of array elements:", np.exp(a))

# square root of array values


print ("Square root of array elements:", np.sqrt(a))

Output:
Sine values of array elements: [ 0.00000000e+00 1.00000000e+00 1.22464680e-
16]
Exponent of array elements: [ 1. 2.71828183 7.3890561 20.08553692]
Square root of array elements: [ 0. 1. 1.41421356 1.73205081]
NumPy Sorting Arrays
We can use a simple np.sort() method for sorting Python NumPy arrays.

Example:
import numpy as np

# set alias names for dtypes


dtypes = [('name', 'S10'), ('grad_year', int), ('cgpa', float)]

# Values to be put in array


values = [('Hrithik', 2009, 8.5), ('Ajay', 2008, 8.7),
('Pankaj', 2008, 7.9), ('Aakash', 2009, 9.0)]
# Creating array
arr = np.array(values, dtype = dtypes)
print ("\nArray sorted by names:\n",
np.sort(arr, order = 'name'))
print ("Array sorted by graduation year and then cgpa:\n",
np.sort(arr, order = ['grad_year', 'cgpa']))

Output
Array sorted by names:
[(b'Aakash', 2009, 9.0 ) (b'Ajay', 2008, 8.7) (b'Hrithik', 2009, 8.5)
(b'Pankaj', 2008, 7.9)]

Array sorted by graduation year and then cgpa:


[(b'Pankaj', 2008, 7.9) (b'Hrithik', 2009, 8.5) (b'Ajay', 2008, 8.7)
[(b'Aakash', 2009, 9. 0)]
Numpy | Mathematical Function
NumPy contains a large number of various mathematical operations. NumPy provides standard
trigonometric functions, functions for arithmetic operations, handling complex numbers, etc.

Trigonometric Functions
NumPy has standard trigonometric functions which return trigonometric ratios for a given angle
in radians.

numpy.sin(x[, out]) = ufunc ‘sin’) : This mathematical function helps user to calculate
trignmetric sine for all x(being the array elements).

# Python program explaining


# sin() function
import numpy as np
import math
in_array = [0, math.pi / 2, np.pi / 3, np.pi]
print ("Input array : \n", in_array)
Sin_Values = np.sin(in_array)
print ("\nSine values : \n", Sin_Values)

Output :
Input array :
[0, 1.5707963267948966, 1.0471975511965976, 3.141592653589793]

Sine values :
[ 0.00000000e+00 1.00000000e+00 8.66025404e-01 1.22464680e-16]

numpy.cos(x[, out]) = ufunc ‘cos’) : This mathematical function helps user to calculate
trignmetric cosine for all x(being the array elements).
# Python program explaining
# cos() function
import numpy as np
import math
in_array = [0, math.pi / 2, np.pi / 3, np.pi]
print ("Input array : \n", in_array)
cos_Values = np.cos(in_array)
print ("\nCosine values : \n", cos_Values)

Output :
Input array :
[0, 1.5707963267948966, 1.0471975511965976, 3.141592653589793]

Cosine values :
[ 1.00000000e+00 6.12323400e-17 5.00000000e-01 -1.00000000e+00]

FUNCTION DESCRIPTION

tan() Compute tangent element-wise.

arcsin() Inverse sine, element-wise.

arccos() Trigonometric inverse cosine, element-wise.

arctan() Trigonometric inverse tangent, element-wise.

arctan2() Element-wise arc tangent of x1/x2 choosing the quadrant correctly.

degrees() Convert angles from radians to degrees.

rad2deg() Convert angles from radians to degrees.

deg2rad Convert angles from degrees to radians.

radians() Convert angles from degrees to radians.

hypot() Given the “legs” of a right triangle, return its hypotenuse.


FUNCTION DESCRIPTION

unwrap() Unwrap by changing deltas between values to 2*pi complement.

Hyperbolic Functions –

numpy.sinh(x[, out]) = ufunc ‘sin’) : This mathematical function helps user to calculate
hyperbolic sine for all x(being the array elements).

Equivalent to 1/2 * (np.exp(x) - np.exp(-x)) or -1j * np.sin(1j*x).

import numpy as np
import math
in_array = [0, math.pi / 2, np.pi / 3, np.pi]
print ("Input array : \n", in_array)
Sinh_Values = np.sinh(in_array)
print ("\nSine Hyperbolic values : \n", Sinh_Values)

Output :
Input array :
[0, 1.5707963267948966, 1.0471975511965976, 3.141592653589793]

Sine Hyperbolic values :


[ 0. 2.3012989 1.24936705 11.54873936]

numpy.cosh(x[, out]) = ufunc ‘cos’) : This mathematical function helps user to calculate
hyperbolic cosine for all x(being the array elements).

Equivalent to 1/2 * (np.exp(x) - np.exp(-x)) and np.cos(1j*x)

# Python3 program explaining


# cosh() function
import numpy as np
import math
in_array = [0, math.pi / 2, np.pi / 3, np.pi]
print ("Input array : \n", in_array)
cosh_Values = np.cosh(in_array)
print ("\ncosine Hyperbolic values : \n", cosh_Values)

Output :
Input array :
[0, 1.5707963267948966, 1.0471975511965976, 3.141592653589793]

cosine Hyperbolic values :


[ 1. 2.50917848 1.60028686 11.59195328]

FUNCTION DESCRIPTION

tanh() Compute hyperbolic tangent element-wise.

arcsinh() Inverse hyperbolic sine element-wise.

arccosh() Inverse hyperbolic cosine, element-wise.

arctanh() Inverse hyperbolic tangent element-wise.


Functions for Rounding –

numpy.around(arr, decimals = 0, out = None) : This mathematical function helps user to


evenly round array elements to the given number of decimals.

# Python program explaining


# around() function
import numpy as np
in_array = [.5, 1.5, 2.5, 3.5, 4.5, 10.1]
print ("Input array : \n", in_array)
round_off_values = np.around(in_array)
print ("\nRounded values : \n", round_off_values)
in_array = [.53, 1.54, .71]
print ("\nInput array : \n", in_array)
round_off_values = np.around(in_array)
print ("\nRounded values : \n", round_off_values)
in_array = [.5538, 1.33354, .71445]
print ("\nInput array : \n", in_array)
round_off_values = np.around(in_array, decimals = 3)
print ("\nRounded values : \n", round_off_values)

Output :
Input array :
[0.5, 1.5, 2.5, 3.5, 4.5, 10.1]

Rounded values :
[ 0. 2. 2. 4. 4. 10.]

Input array :
[0.53, 1.54, 0.71]

Rounded values :
[ 1. 2. 1.]

Input array :
[0.5538, 1.33354, 0.71445]

Rounded values :
[ 0.554 1.334 0.714]
numpy.round_(arr, decimals = 0, out = None) : This mathematical function round an array to
the given number of decimals.

# Python program explaining


# round_() function
import numpy as np
in_array = [.5, 1.5, 2.5, 3.5, 4.5, 10.1]
print ("Input array : \n", in_array)
round_off_values = np.round_(in_array)
print ("\nRounded values : \n", round_off_values)
in_array = [.53, 1.54, .71]
print ("\nInput array : \n", in_array)
round_off_values = np.round_(in_array)
print ("\nRounded values : \n", round_off_values)
in_array = [.5538, 1.33354, .71445]
print ("\nInput array : \n", in_array)
round_off_values = np.round_(in_array, decimals = 3)
print ("\nRounded values : \n", round_off_values)

Output :
Input array :
[0.5, 1.5, 2.5, 3.5, 4.5, 10.1]

Rounded values :
[ 0. 2. 2. 4. 4. 10.]

Input array :
[0.53, 1.54, 0.71]

Rounded values :
[ 1. 2. 1.]

Input array :
[0.5538, 1.33354, 0.71445]

Rounded values :
[ 0.554 1.334 0.714]
FUNCTION DESCRIPTION

rint() Round to nearest integer towards zero.

fix() Round to nearest integer towards zero.

floor() Return the floor of the input, element-wise.

ceil() Return the ceiling of the input, element-wise.

Return the truncated value of the input, element-


trunc() wise.

Exponents and logarithms Functions –

numpy.exp(array, out = None, where = True, casting = ‘same_kind’, order = ‘K’, dtype =
None) : This mathematical function helps user to calculate exponential of all the elements in the
input array.

# Python program explaining


# exp() function
import numpy as np
in_array = [1, 3, 5]
print ("Input array : ", in_array)
out_array = np.exp(in_array)
print ("Output array : ", out_array)

Output :
Input array : [1, 3, 5]
Output array : [ 2.71828183 20.08553692 148.4131591 ]
numpy.log(x[, out] = ufunc ‘log1p’) : This mathematical function helps user to
calculate Natural logarithm of x where x belongs to all the input array elements.
Natural logarithm log is the inverse of the exp(), so that log(exp(x)) = x. The natural logarithm
is log in base e.

# Python program explaining


# log() function
import numpy as np
in_array = [1, 3, 5, 2**8]
print ("Input array : ", in_array)
out_array = np.log(in_array)
print ("Output array : ", out_array)

print("\nnp.log(4**4) : ", np.log(4**4))


print("np.log(2**8) : ", np.log(2**8))

Output :
Input array : [1, 3, 5, 256]
Output array : [ 0. 1.09861229 1.60943791 5.54517744]

np.log(4**4) : 5.54517744448
np.log(2**8) : 5.54517744448

FUNCTION DESCRIPTION

expm1() Calculate exp(x) – 1 for all elements in the array.

exp2() Calculate 2**p for all p in the input array.

log10() Return the base 10 logarithm of the input array, element-wise.

log2() Base-2 logarithm of x.

Return the natural logarithm of one plus the input array, element-
log1p()
wise.

logaddexp() Logarithm of the sum of exponentiations of the inputs.

logaddexp2() Logarithm of the sum of exponentiations of the inputs in base-2.


Arithmetic Functions –

numpy.reciprocal(x, /, out=None, *, where=True) : This mathematical function is used to


calculate reciprocal of all the elements in the input array.

Note: For integer arguments with absolute value larger than 1, the result is always zero because
of the way Python handles integer division. For integer zero the result is an overflow.

# Python3 code demonstrate reciprocal() function


# importing numpy
import numpy as np
in_num = 2.0
print ("Input number : ", in_num)
out_num = np.reciprocal(in_num)
print ("Output number : ", out_num)

Output :
Input number : 2.0
Output number : 0.5

numpy.divide(arr1, arr2, out = None, where = True, casting = ‘same_kind’, order = ‘K’,
dtype = None) : Array element from first array is divided by elements from second element (all
happens element-wise). Both arr1 and arr2 must have same shape and element in arr2 must not
be zero; otherwise it will raise an error.

# Python program explaining


# divide() function
import numpy as np
# input_array
arr1 = [2, 27, 2, 21, 23]
arr2 = [2, 3, 4, 5, 6]
print ("arr1 : ", arr1)
print ("arr2 : ", arr2)
# output_array
out = np.divide(arr1, arr2)
print ("\nOutput array : \n", out)
Output :
arr1 : [2, 27, 2, 21, 23]
arr2 : [2, 3, 4, 5, 6]

Output array :
[ 1. 9. 0.5 4.2 3.83333333]

FUNCTION DESCRIPTION

add() Add arguments element-wise.

positive() Numerical positive, element-wise.

negative() Numerical negative, element-wise.

multiply() Multiply arguments element-wise.

power() First array elements raised to powers from second array, element-wise.

subtract() Subtract arguments, element-wise.

true_divide() Returns a true division of the inputs, element-wise.

floor_divide() Return the largest integer smaller or equal to the division of the inputs.

float_power() First array elements raised to powers from second array, element-wise.
FUNCTION DESCRIPTION

mod() Return the element-wise remainder of division.

remainder() Return element-wise remainder of division.

divmod() Return element-wise quotient and remainder simultaneously.

Complex number Function –

numpy.isreal(array) : Test element-wise whether it is a real number or not(not infinity or not


Not a Number) and return the result as a boolean array.

# Python Program illustrating


# numpy.isreal() method
import numpy as geek
print("Is Real : ", geek.isreal([1+1j, 0j]), "\n")
print("Is Real : ", geek.isreal([1, 0]), "\n")

Output :
Is Real : [False True]

Is Real : [ True True]


numpy.conj(x[, out] = ufunc ‘conjugate’) : This function helps the user to conjugate any
complex number.
The conjugate of a complex number is obtained by changing the sign of its imaginary part. If
the complex number is 2+5j then its conjugate is 2-5j.

# Python3 code demonstrate conj() function


#importing numpy
import numpy as np
in_complx1 = 2+4j
out_complx1 = np.conj(in_complx1)
print ("Output conjugated complex number of 2+4j : ", out_complx1)
in_complx2 =5-8j
out_complx2 = np.conj(in_complx2)
print ("Output conjugated complex number of 5-8j: ", out_complx2)

Output :
Output conjugated complex number of 2+4j : (2-4j)
Output conjugated complex number of 5-8j: (5+8j)

Special functions –

numpy.cbrt(arr, out = None, ufunc ‘cbrt’) : This mathematical function helps user to
calculate cube root of x for all x being the array elements.

# Python program explaining


# cbrt () function
import numpy as np
arr1 = [1, 27000, 64, -1000]
print ("cbrt Value of arr1 : \n", np.cbrt(arr1))
arr2 = [1024 ,-128]
print ("\ncbrt Value of arr2 : ", np.cbrt(arr2))
Output :
cbrt Value of arr1 :
[ 1. 30. 4. -10.]

cbrt Value of arr2 : [ 10.0793684 -5.0396842]

numpy.clip() : This function is used to Clip (limit) the values in an array.


Given an interval, values outside the interval are clipped to the interval edges. For example, if
an interval of [0, 1] is specified, values smaller than 0 become 0, and values larger than 1
become 1.

# Python3 code demonstrate clip() function


# importing the numpy
import numpy as np
in_array = [1, 2, 3, 4, 5, 6, 7, 8 ]
print ("Input array : ", in_array)
out_array = np.clip(in_array, a_min = 2, a_max = 6)
print ("Output array : ", out_array)

Output :
Input array : [1, 2, 3, 4, 5, 6, 7, 8]
Output array : [2 2 3 4 5 6 6 6]

FUNCTION DESCRIPTION

Returns the discrete, linear convolution of two one-dimensional


convolve() sequences.

sqrt() Return the non-negative square-root of an array, element-wise.

square() Return the element-wise square of the input.

absolute() Calculate the absolute value element-wise.

fabs() Compute the absolute values element-wise.

sign() Returns an element-wise indication of the sign of a number.

interp() One-dimensional linear interpolation.

maximum() Element-wise maximum of array elements.

minimum() Element-wise minimum of array elements.

real_if_close() If complex input returns a real array if complex parts are close to zero.

nan_to_num() Replace NaN with zero and infinity with large finite numbers.

heaviside() Compute the Heaviside step function.


Python Random Module
Python Random module generates random numbers in Python. These are pseudo-random
numbers means they are not truly random.

This module can be used to perform random actions such as generating random numbers,
printing random a value for a list or string, etc. It is an in-built function in Python.

Applications of Python Random Module


Here are some real-life uses of Python's random module:
1. Games (dice rolls, card draws)
2. Simulations (traffic, finance, etc.)
3. Data sampling
4. Machine learning dataset splitting
5. Generating passwords or session tokens
6. Software testing and stress testing

List of all the functions Python Random Module


There are different random functions in the Random Module of Python. Look at the table below
to learn more about these functions:
Function Name Description

seed() Initialize the random number generator

Returns an object with the current internal


getstate() state of the random number generator

Used to restore the state of the random


setstate() number generator back to the specified state

Return an integer with a specified number


getrandbits() of bits

randrange() Returns a random number within the range

randint() Returns a random integer within the range


Function Name Description

Returns a random item from a list, tuple, or


choice() string

Returns multiple random elements from the


choices() list with replacement

Returns a particular length list of items


sample() chosen from the sequence

random() Generate random floating numbers

Return a random floating number between


uniform() two numbers both inclusive

Return a random floating point number


within a range with a bias towards one
triangular() extreme

Return a random floating point number


betavariate() with beta distribution

Return a random floating point number


expovariate() with exponential distribution

Return a random floating point number


gammavariate() with a gamma distribution

Return a random floating point number


gauss() with Gaussian distribution
Function Name Description

Return a random floating point number


lognormvariate() with a log-normal distribution

Return a random floating point number


normalvariate() with normal distribution

Return a random floating point number


with von Mises distribution or circular
vonmisesvariate() normal distribution

Return a random floating point number


paretovariate() with a Pareto distribution

Return a random floating point number


weibullvariate() with Weibull distribution

Examples of Random Module

Example 1: Pick a Random Element from a List


Selects a single random item from a list using random.choice().

import random
a = [1, 2, 3, 4, 5, 6]
print(random.choice(a))

Output

3
Example 2: Using seed() for Reproducible Output
Random numbers depend on the seeding value. For example, if the seeding value is 5 then the
output of the below program will always be the same. Therefore, it must not be used for
encryption.

The code sets the random number generator's seed to 5 using random.seed(5). It then prints
two random floating-point numbers between 0 and 1 using random.random(). The seed makes
these numbers the same every time we run the code with a seed of 5.

import random
random.seed(5)
print(random.random())
print(random.random())

Output

0.6229016948897019
0.7417869892607294

Example 3: Generate Random Integers in a Range


random.randint() method is used to generate random integers between the given range.
Syntax: randint(start, end)

import random
r1 = random.randint(5, 15)
print(r1)

r2 = random.randint(-10, -2)
print(r2)

Output

8
-7
Explanation:
 r1 is a andom number between 5 and 15.
 r2 is a random number between -10 and -2.
Example 4: Generate a Random Float Between 0 and 1
A random.random() method is used to generate random floats between 0.0 to 1.
Syntax: random.random()

from random import random


print(random())

Output

0.8443722499369146
Explanation: random() generates a float number in the range [0.0, 1.0).

Example 5: Randomly Select from List, String, and Tuple


Shows how to use choice() with different sequence types.

import random

a = [1, 2, 3, 4, 5, 6]
print(random.choice(a))

s = "geeks"
print(random.choice(s))

tup = (1, 2, 3, 4, 5)
print(random.choice(tup))

Output

2
g
2
Explanation: choice() picks a random element from a list, string, or tuple.

Example 6: Select Multiple Unique Random Items


this example demonstrates the use of sample() to pick multiple items from sequences without
repeating.
Syntax: random.sample(sequence, length)
from random import sample

a = [1, 2, 3, 4, 5]
print(sample(a,3))

b = (4, 5, 6, 7, 8)
print(sample(b,3))

c = "45678"
print(sample(c,3))
Output

[4, 2, 3]
[4, 7, 8]
['6', '4', '8']
Explanation: sample() returns a list of unique random elements from the input sequence.

Example 7: Shuffle Elements in a List


random.shuffle() method is used to shuffle a sequence (list). Shuffling means changing the
position of the elements of the sequence. Here, the shuffling operation is inplace.

import random
a = [1, 2, 3, 4, 5]

random.shuffle(a)
print("After shuffle : ")
print(a)

random.shuffle(a)
print("\nSecond shuffle : ")
print(a)

Output

After shuffle :
[1, 4, 2, 5, 3]

Second shuffle :
[1, 4, 3, 5, 2]
Explanation: shuffle() changes the order of elements in the list randomly, in-place.
Numpy - String Functions & Operations
NumPy String functions belong to the numpy.char module and are designed to perform
element-wise operations on arrays. These functions can help to handle and manipulate string
data efficiently.

String Operations String Information String Comparison

In this article, we’ll explore the various string functions provided by NumPy along with their
examples.

String Operations
 numpy.lower(): This function returns the lowercase string from the given string. It converts
all uppercase characters to lowercase. If no uppercase characters exist, it returns the original
string.

import numpy as np

# converting to lowercase
print(np.char.lower(['GEEKS', 'FOR']))

# converting to lowercase
print(np.char.lower('GEEKS'))

Output
['geeks' 'for']
geeks

 numpy.split() : This function returns a list of strings after breaking the given string by the
specified separator.

import numpy as np

# splitting a string
print(np.char.split('geeks for geeks'))

# splitting a string
print(np.char.split('geeks, for, geeks', sep = ','))

Output
['geeks', 'for', 'geeks']
['geeks', ' for', ' geeks']
 numpy.join() : This function is a string method and returns a string in which the elements of
sequence have been joined by str separator.

import numpy as np

# splitting a string
print(np.char.join('-', 'geeks'))

# splitting a string
print(np.char.join(['-', ':'], ['geeks', 'for']))

Output
g-e-e-k-s
['g-e-e-k-s' 'f:o:r']
FUNCTION DESCRIPTION

numpy.strip() It is used to remove all the leading and trailing spaces from a string.

It converts the first character of a string to capital (uppercase) letter. If the string has its
numpy.capitalize()
first character as capital, then it returns the original string.

numpy.center() It creates and returns a new string which is padded with the specified character..

It is used to convert from one encoding scheme, in which argument string is encoded to
numpy.decode()
the desired encoding scheme.

numpy.encode() Returns the string in the encoded form

numpy.ljust() Return an array with the elements of a left-justified in a string of length width.

numpy.rjust() For each element in a, return a copy with the leading characters removed.

numpy.strip() For each element in a, return a copy with the leading and trailing characters removed.

numpy.lstrip() Convert angles from degrees to radians.

numpy.rstrip() For each element in a, return a copy with the trailing characters removed.

numpy.partition() Partition each element in a around sep.

numpy.rpartition Partition (split) each element around the right-most separator.

For each element in a, return a list of the words in the string, using sep as the delimiter
numpy.rsplit()
string.

It is used to convert the first character in each word to Uppercase and remaining
numpy.title()
characters to Lowercase in string and returns new string.

Returns the uppercased string from the given string. It converts all lowercase characters
numpy.upper()
to uppercase.If no lowercase characters exist, it returns the original string.
String Information
 numpy.count() : This function returns the number of occurrences of a substring in the given
string.

import numpy as np

a=np.array(['geeks', 'for', 'geeks'])

# counting a substring
print(np.char.count(a,'geek'))

# counting a substring
print(np.char.count(a, 'fo'))

Output
[1 0 1]
[0 1 0]

 numpy.rfind() : This function returns the highest index of the substring if found in given
string. If not found then it returns -1.

import numpy as np

a=np.array(['geeks', 'for', 'geeks'])

# counting a substring
print(np.char.rfind(a,'geek'))

# counting a substring
print(np.char.rfind(a, 'fo'))

Output
[ 0 -1 0]
[-1 0 -1]
 numpy.isnumeric() : This function returns “True” if all characters in the string are numeric
characters, Otherwise, It returns “False”.

import numpy as np

# counting a substring
print(np.char.isnumeric('geeks'))

# counting a substring
print(np.char.isnumeric('12geeks'))

Output
False
False
FUNCTION DESCRIPTION

It returns the lowest index of the substring if it is found in given string. If its is not
numpy.find()
found then it returns -1.

numpy.index() It returns the position of the first occurrence of substring in a string

It returns “True” if all characters in the string are alphabets, Otherwise, It returns
numpy.isalpha()
“False”.

It returns true if all characters in a string are decimal. If all characters are not decimal
numpy.isdecimal()
then it returns false.

numpy.isdigit() It returns “True” if all characters in the string are digits, Otherwise, It returns “False”.

It returns “True” if all characters in the string are lowercase, Otherwise, It returns
numpy.islower()
“False”.

Returns true for each element if there are only whitespace characters in the string and
numpy.isspace()
there is at least one character, false otherwise.

Returns true for each element if the element is a titlecased string and there is at least
numpy.istitle()
one character, false otherwise.

Returns true for each element if all cased characters in the string are uppercase and
numpy.isupper()
there is at least one character, false otherwise.

Returns the highest index of the substring inside the string if substring is found.
numpy.rindex()
Otherwise it raises an exception.

numpy.startswith(
Returns True if a string starts with the given prefix otherwise returns False.
)
String Comparison

 numpy.equal(): This function checks for string1 == string2 elementwise.

import numpy as np

# using equal() method


a=np.char.equal('geeks','for')

print(a)

Output
False

 numpy.not_equal(): This function checks whether two string is unequal or not.

import numpy as np

# Comparing a string element-wise using not_equal() method


a = np.char.not_equal('geeks', 'for')

print(a)

Output
True

 numpy.greater(): This function checks whether string1 is greater than string2 or not.

import numpy as np

# comparing a string elementwise


a=np.char.greater('geeks','for')

print(a)

Output
True
FUNCTION DESCRIPTION

numpy.greater_equal() It checks whether string1 >= string2 or not.

numpy.less_equal() It checks whether string1 is <= string2 or not.

It check whether string1 is lesser than string2 or


numpy.less()
not.

You might also like