NumPy: Change the sign of a given array to that of a given array, element-wise
NumPy Mathematics: Exercise-37 with Solution
Write a NumPy program to change the sign of a given array to that of a given array, element-wise.
Sample Solution:
Python Code:
# Importing the NumPy library
import numpy as np
# Creating an array with integer values from -1 to 2
x1 = np.array([-1, 0, 1, 2])
# Displaying the original array x1
print("Original array: ")
print(x1)
# Assigning a floating-point value to x2
x2 = -2.1
# Displaying the sign of x1 with respect to x2, element-wise using np.copysign()
print("\nSign of x1 to that of x2, element-wise:")
print(np.copysign(x1, x2))
Sample Output:
Original array: [-1 0 1 2] Sign of x1 to that of x2, element-wise: [-1. -0. -1. -2.]
Explanation:
x1 = np.array([-1, 0, 1, 2]): x1 is a 1-dimensional NumPy array of integers, with the values [-1, 0, 1, 2].
x2 = -2.1: x2 is a scalar value of type float.
np.copysign(x1, x2): This code returns an array with the same magnitude as x1, but with the sign of x2, which is negative. Therefore, the output will be array([-1. -0. -1. -2.]), which is an array with the same magnitude as x1, but with the sign changed to negative.
Python-Numpy Code Editor:
Previous: Write a NumPy program to check element-wise True/False of a given array where signbit is set.
Next: Write a NumPy program to compute numerical negative value for all elements in a given array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/numpy/python-numpy-math-exercise-37.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics