Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Return the real part of the complex argument in Python
To return the real part of complex numbers in Python, use the numpy.real() method. This function extracts the real component from complex arguments. If the input contains real numbers, it returns them with their original type. For complex arrays, it returns float values.
Syntax
numpy.real(val)
Parameters:
-
val? Input array containing complex numbers
Basic Example
Let's extract real parts from a complex array ?
import numpy as np
# Create complex array
arr = np.array([56.+0.j, 27.+0.j, 68.+0.j, 23.+0.j])
print("Original Array:", arr)
# Extract real parts
real_parts = np.real(arr)
print("Real parts:", real_parts)
print("Data type:", real_parts.dtype)
Original Array: [56.+0.j 27.+0.j 68.+0.j 23.+0.j] Real parts: [56. 27. 68. 23.] Data type: float64
Complex Numbers with Imaginary Parts
Here's how it works with complex numbers that have both real and imaginary components ?
import numpy as np
# Complex numbers with imaginary parts
complex_arr = np.array([3+4j, 5-2j, 7+1j, -2+6j])
print("Complex Array:", complex_arr)
# Extract real parts
real_parts = np.real(complex_arr)
print("Real parts:", real_parts)
Complex Array: [ 3.+4.j 5.-2.j 7.+1.j -2.+6.j] Real parts: [ 3. 5. 7. -2.]
Working with Real Numbers
When applied to real numbers, numpy.real() returns the original values ?
import numpy as np
# Real number array
real_arr = np.array([10, 20, 30, 40])
print("Real Array:", real_arr)
# Apply numpy.real()
result = np.real(real_arr)
print("Result:", result)
print("Original type:", real_arr.dtype)
print("Result type:", result.dtype)
Real Array: [10 20 30 40] Result: [10 20 30 40] Original type: int64 Result type: int64
Key Points
-
numpy.real()extracts only the real component of complex numbers - For real inputs, it preserves the original data type
- For complex inputs, it returns float64 type
- Works with both single complex numbers and arrays
Conclusion
Use numpy.real() to extract real parts from complex numbers efficiently. It preserves data types for real inputs and converts complex inputs to float arrays for the real components.
Advertisements
