Change the real part of the complex argument in Python

PythonNumpyServer Side ProgrammingProgramming

To return the real part of the complex argument, use the numpy.real() method. The method returns the real component of the complex argument. If val is real, the type of val is used for the output. If val has complex elements, the returned type is float. The 1st parameter, val is the input array. We will also change the real part of the complex argument using the array.real.

Steps

At first, import the required libraries-

import numpy as np

Create an array using the array() method −

arr = np.array([36.+1.j , 27.+2.j , 68.+3.j , 23.+2.j])

Display the array −

print("Our Array...\n",arr)

Check the Dimensions −

print("\nDimensions of our Array...\n",arr.ndim)

Get the Datatype −

print("\nDatatype of our Array object...\n",arr.dtype)

Get the Shape −

print("\nShape of our Array...\n",arr.shape)

To return the real part of the complex argument, use the numpy.real() method in Python. The method returns the real component of the complex argument. If val is real, the type of val is used for the output. If val has complex elements, the returned type is float.

The 1st parameter, val is the input array −

print("\nReal part...\n",np.real(arr))

Change the real part −

arr.real = 5
print("\nUpdated result...\n",arr)

Example

import numpy as np

# Create an array using the array() method
arr = np.array([36.+1.j , 27.+2.j , 68.+3.j , 23.+2.j])

# Display the array
print("Our Array...\n",arr)

# Check the Dimensions
print("\nDimensions of our Array...\n",arr.ndim)

# Get the Datatype
print("\nDatatype of our Array object...\n",arr.dtype)

# Get the Shape
print("\nShape of our Array...\n",arr.shape)

# To return the real part of the complex argument, use the numpy.real() method in Python
print("\nReal part...\n",np.real(arr))

# Change the real part
arr.real = 5
print("\nUpdated result...\n",arr)

Output

Our Array...
[36.+1.j 27.+2.j 68.+3.j 23.+2.j]

Dimensions of our Array...
1

Datatype of our Array object...
complex128

Shape of our Array...
(4,)

Real part...
[36. 27. 68. 23.]

Updated result...
[5.+1.j 5.+2.j 5.+3.j 5.+2.j]
raja
Updated on 25-Feb-2022 04:35:31

Advertisements