w3resource

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


38. Compute Numerical Negation

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.


For more Practice: Solve these Related Problems:

  • Implement a function that returns the negative of each element in an array using the unary minus operator.
  • Test the function on an array of positive, negative, and zero values to verify correct negation.
  • Create a solution that uses np.negative to compute the negation and compares it with a manual approach.
  • Apply the negation operation to a multi-dimensional array and ensure that the shape remains unchanged.

Python-Numpy Code Editor:

Previous: Write a NumPy program to change the sign of a given array to that of a given array, element-wise.

Next: Write a NumPy program to compute the reciprocal for all elements in a given array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.