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

คำนวณกำลังสองของอินพุทค่าฤทธิ์ (complex) ด้วย numpy.square() ใน Python

เมธอด numpy.square() คำนวณกำลังสองทีละองค์ประกอบ (element-wise) สำหรับอินพุททุกชนิด รวมถึงค่าฤทธิ์ (complex) คืนค่า x*x รูปร่างและ dtype เดียวกับ x

ขั้นตอนการใช้งาน

import numpy as np

สร้างอาร์เรย์ค่าฤทธิ์และตรวจสอบคุณสมบัติ

arr = np.array([[3 + 4j, 5 + 7j], [2 + 6j, -2j]])
print("Our Array...\n", arr)
print("\nDimensions of our Array...\n", arr.ndim)
print("\nDatatype of our Array object...\n", arr.dtype)

คำนวณกำลังสอง

print("\nResult...\n", np.square(arr))

โค้ดตัวอย่างสมบูรณ์

import numpy as np

arr = np.array([[3 + 4j, 5 + 7j], [2 + 6j, -2j]])
print("Our Array...\n", arr)
print("\nDimensions of our Array...\n", arr.ndim)
print("\nDatatype of our Array object...\n", arr.dtype)
print("\nResult...\n", np.square(arr))

ผลลัพธ์ที่คาดหวัง

Our Array...
[[ 3.+4.j  5.+7.j]
 [ 2.+6.j -0.-2.j]]
Dimensions of our Array...
2
Datatype of our Array object...
complex128
Result...
[[ -7.+24.j -24.+70.j]
 [-32.+24.j  -4.+0.j]]