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

หาค่า cosine ของอาร์เรย์มุมที่กำหนดเป็นองศาใน Python


ภาพรวม

ใช้ numpy.cos() หา cosine ของอาร์เรย์มุมที่ให้มาเป็นองศา ต้องแปลงเป็นเรเดียนก่อน: radian = degree × π / 180

พารามิเตอร์

  • x: มุมในเรเดียน (อาร์เรย์)
  • out, where (optional): ตามปกติ

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

1. นำเข้า NumPy

import numpy as np

2. สร้างอาร์เรย์มุม (องศา)

arr = np.array((0., 30., 45., 60., 90., 180.))

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

print("Array...\n", arr)
print("\nArray datatype...\n", arr.dtype)
print("\nArray Dimensions...\n", arr.ndim)
print("\nNumber of elements in the Array...\n", arr.size)

4. คำนวณ cosine (แปลงองศาเป็นเรเดียน)

print("\nResult...", np.cos(arr * np.pi / 180.))

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

import numpy as np
arr = np.array((0., 30., 45., 60., 90., 180.))
print("Array...\n", arr)
print("\nOur Array type...\n", arr.dtype)
print("\nOur Array Dimensions...\n", arr.ndim)
print("\nNumber of elements...\n", arr.size)
print("\nResult...", np.cos(arr * np.pi / 180.))

ผลลัพธ์

Array... [  0.  30.  45.  60.  90. 180.]
Our Array type... float64
Our Array Dimensions... 1
Number of elements... 6
Result... [ 1.00000000e+00  8.66025404e-01  7.07106781e-01  5.00000000e-01
  6.12323400e-17 -1.00000000e+00]

คำอธิบาย:

  • cos(0°) = 1
  • cos(30°) = √3/2 ≈ 0.866
  • cos(45°) = √2/2 ≈ 0.707
  • cos(60°) = 0.5
  • cos(90°) ≈ 0 (6.12e-17)
  • cos(180°) = -1