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

คำนวณกำลังสองขององค์ประกอบอาร์เรย์แต่ละตัวด้วย numpy.square() ใน Python

เพื่อคืนค่ากำลังสองของอินพุตอาร์เรย์ทีละองค์ประกอบ (element-wise) ให้ใช้ numpy.square() เมธอดนี้คืนค่า x*x ที่มีรูปร่างและ dtype เหมือน x เป็นสเกลาร์หาก x เป็นสเกลาร์

พารามิเตอร์สำคัญ

  • x: ข้อมูลอินพุต
  • out (ไม่บังคับ): ตำแหน่งเก็บผลลัพธ์ ต้อง broadcast ได้
  • where (ไม่บังคับ): เงื่อนไข broadcast ที่ True ตั้งค่า ufunc ที่ False เก็บค่าเดิม

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

import numpy as np

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

arr = np.array([[25, -50, 75], [-90, 81, 64]])
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([[25, -50, 75], [-90, 81, 64]])
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...
[[ 25 -50  75]
 [-90  81  64]]
Dimensions of our Array...
2
Datatype of our Array object...
int64
Result...
[[ 625 2500 5625]
 [8100 6561 4096]]