Home »
Python »
Python Programs
Random 3x3 matrix where negatives are replaced by inf in Python
By IncludeHelp Last updated : November 25, 2023
Problem statement
Write a Python program to create a random 3X3 matrix where negative values are replaced by inf.
inf in Python
In NumPy, inf is a special floating-point value that represents positive infinity. It is typically used to represent the result of a calculation that exceeds the range of representable values for a floating-point number.
Replacing negative values in a random 3X3 matrix with inf
To replace negative values in a random 3X3 matrix with inf values, first generate a random 3x3 matrix using the np.random.rand() method and use boolean indexing to replace negative values in the matrix with positive infinity using the np.inf constant.
Example
In this example, there is a random 3x3 matrix and we are replacing the negative values with inf.
# Importing numpy library
import numpy as np
# Creating a random 3x3 matrix
arr = np.random.rand(3, 3) - 0.5
# Display matrix
print("Matrix is:\n", arr, "\n")
# Replacing negative values with inf
arr[arr < 0] = np.inf
# Display updated matrix
print("Result:\n", arr)
Output
The output of the above example is:
Matrix is:
[[ 0.04008929 -0.33233526 0.28312235]
[-0.23213299 -0.44814996 0.05096693]
[ 0.08774295 0.24668775 0.20266993]]
Result:
[[0.04008929 inf 0.28312235]
[ inf inf 0.05096693]
[0.08774295 0.24668775 0.20266993]]
Python NumPy Programs »