w3resource

NumPy: Compute numerical negative value for all elements in a given array


Write a NumPy program to compute numerical negative value for all elements in a given array.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating an array containing integers 0, 1, and -1
x = np.array([0, 1, -1])

# Displaying the original array x
print("Original array: ")
print(x)

# Calculating the numerical negative value of each element in array x using np.negative()
r1 = np.negative(x)

# Calculating the numerical negative value of each element in array x using the unary minus operator
r2 = -x

# Checking if the results from np.negative() and the unary minus operator are equal using np.array_equal()
assert np.array_equal(r1, r2)

# Displaying the numerical negative value for all elements of the array obtained using np.negative()
print("Numerical negative value for all elements of the said array:")
print(r1) 

Sample Output:

Original array: 
[ 0  1 -1]
Numerical negative value for all elements of the said array:
[ 0 -1  1]

Explanation:

x = np.array([0, 1, -1]): x is a 1-dimensional NumPy array of integers, with the values [ 0, 1, -1].

r1 = np.negative(x): Compute the negation of each element of the array and store the result in r1.

r2 = -x: Here ‘-x’ computes the negation of each element of the array and stores the result in r2.

assert np.array_equal(r1, r2): Finally, np.array_equal() function is used to verify if r1 and r2 have the same values. If the assertion passes, then it confirms that r1 and r2 have the same values.

Python-Numpy Code Editor: