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

คำนวณลอการิทึมฐาน 2 ด้วย scimath ใน Python


ในการคำนวณลอการิทึมฐาน 2 ด้วย scimath ให้ใช้เมธอด np.emath.log2() ใน Python Numpy วิธีการคืนค่าล็อกฐาน 2 ของค่า x ถ้า x เป็นสเกลาร์ ก็จะออกมา ไม่เช่นนั้นอาร์เรย์จะถูกส่งคืน พารามิเตอร์ตัวที่ 1 x คือค่าที่ต้องการ log base 2

ขั้นตอน

ขั้นแรก นำเข้าไลบรารีที่จำเป็น -

import numpy as np

การสร้างอาร์เรย์ numpy โดยใช้เมธอด array() -

arr = np.array([np.inf, -np.inf, 16, np.exp(1), -np.exp(1), -32])

แสดงอาร์เรย์ -

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 object...\n",arr.shape)

ในการคำนวณลอการิทึมฐาน 2 ด้วย scimath ให้ใช้เมธอด np.emath.log2() ใน Python Numpy วิธีการคืนค่าล็อกฐาน 2 ของค่า x ถ้า x เป็นสเกลาร์ ก็จะออกมา ไม่เช่นนั้นอาร์เรย์จะถูกส่งคืน −

print("\nResult (log2)...\n",np.emath.log2(arr))

ตัวอย่าง

import numpy as np

# Creating a numpy array using the array() method
arr = np.array([np.inf, -np.inf, 16, np.exp(1), -np.exp(1), -32])

# Display the array
print("Our Array...\n",arr)

# Check the Dimensions
print("\nDimensions of our Array...\n",arr.ndim)

# Get the Datatype
print("\nDatatype of our Array object...\n",arr.dtype)

# Get the Shape
print("\nShape of our Array object...\n",arr.shape)

# To compute the logarithm base 2 with scimath, use the np.emath.log2() method in Python Numpy
# The method returns the log base 2 of the x value(s). If x was a scalar, so is out, otherwise an array is returned.
print("\nResult (log2)...\n",np.emath.log2(arr))

ผลลัพธ์

Our Array...
[ inf -inf 16. 2.71828183 -2.71828183
-32. ]

Dimensions of our Array...
1

Datatype of our Array object...
float64

Shape of our Array object...
(6,)

Result (log2)...
[ inf+0.j inf+4.53236014j 4. +0.j
1.44269504+0.j 1.44269504+4.53236014j 5. +4.53236014j]