NumPy real()

The numpy.real() function extracts the real part of a complex number or an array of complex numbers. If the input is already real, it remains unchanged.

Syntax

</>
Copy
numpy.real(val)

Parameters

ParameterTypeDescription
valarray_likeInput array, which can contain real or complex numbers.

Return Value

Returns an array or scalar containing the real component of the input. If the input is real, it remains unchanged. If the input contains complex numbers, the output will be of type float.


Examples

1. Extracting the Real Part of a Complex Number

Here, we extract the real part from a single complex number.

</>
Copy
import numpy as np

# Define a complex number
complex_num = 3 + 4j

# Extract the real part
real_part = np.real(complex_num)

# Print the result
print("Real part of", complex_num, ":", real_part)

Output:

Real part of (3+4j) : 3.0

2. Extracting the Real Part from an Array of Complex Numbers

We apply numpy.real() to an array containing complex numbers.

</>
Copy
import numpy as np

# Define an array of complex numbers
complex_array = np.array([1+2j, 3-4j, 5+6j, 7-8j])

# Extract the real parts
real_parts = np.real(complex_array)

# Print the results
print("Original complex array:", complex_array)
print("Real parts:", real_parts)

Output:

Original complex array: [1.+2.j 3.-4.j 5.+6.j 7.-8.j]
Real parts: [1. 3. 5. 7.]

3. Extracting the Real Part from a Mixed Array

Applying numpy.real() on an array that contains both real and complex numbers.

</>
Copy
import numpy as np

# Define an array with both real and complex numbers
mixed_array = np.array([2, 3+4j, 5, 6-7j])

# Extract the real parts
real_parts = np.real(mixed_array)

# Print the results
print("Original array:", mixed_array)
print("Real parts:", real_parts)

Output:

Original array: [2.+0.j 3.+4.j 5.+0.j 6.-7.j]
Real parts: [2. 3. 5. 6.]

4. Extracting the Real Part from a 2D Complex Array

Using numpy.real() on a 2D array of complex numbers.

</>
Copy
import numpy as np

# Define a 2D array of complex numbers
complex_matrix = np.array([[1+1j, 2-2j], [3+3j, 4-4j]])

# Extract the real parts
real_matrix = np.real(complex_matrix)

# Print the results
print("Original complex matrix:\n", complex_matrix)
print("Real part matrix:\n", real_matrix)

Output:

Original complex matrix:
 [[1.+1.j 2.-2.j]
 [3.+3.j 4.-4.j]]
Real part matrix:
 [[1. 2.]
 [3. 4.]]