Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ดึงส่วนจินตภาพ (imaginary part) ของจำนวนเชิงซ้อนใน Python


ภาพรวม

ใช้ numpy.imag() คืนส่วนจินตภาพของ argument แบบเชิงซ้อน ถ้า val เป็น real ใช้ type ของ val สำหรับ output ถ้า val มีองค์ประกอบ complex คืนค่าเป็น float

พารามิเตอร์

  • val: อาร์เรย์อินพุท

ขั้นตอนการทำงาน

1. นำเข้าไลบรารี

import numpy as np

2. สร้างอาร์เรย์จำนวนเชิงซ้อน

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

3. แสดงข้อมูลอาร์เรย์

print("Our Array...\n", arr)
print("\nDimensions of our Array...\n", arr.ndim)
print("\nDatatype of our Array object...\n", arr.dtype)
print("\nShape of our Array...\n", arr.shape)

4. ดึงส่วนจินตภาพ

print("\nResult (Imaginary part)...\n", np.imag(arr))

ตัวอย่างโค้ดเต็ม

import numpy as np
arr = np.array([36.+5.j, 27.+3.j, 68.+2.j, 23.+7.j])
print("Our Array...\n", arr)
print("\nDimensions of our Array...\n", arr.ndim)
print("\nDatatype of our Array object...\n", arr.dtype)
print("\nShape of our Array...\n", arr.shape)
print("\nResult (Imaginary part)...\n", np.imag(arr))

ผลลัพธ์

Our Array... [36.+5.j 27.+3.j 68.+2.j 23.+7.j]
Dimensions of our Array... 1
Datatype of our Array object... complex128
Shape of our Array... (4,)
Result (Imaginary part)... [5. 3. 2. 7.]

สรุป: คืนค่าอาร์เรย์ float64 ที่มีเฉพาะส่วนจินตภาพ [5, 3, 2, 7]