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

ส่งคืนลอการิทึมฐาน 2 ของอาร์เรย์อินพุตใน Python


ในการคืนค่าลอการิทึมฐาน 2 ของอาร์เรย์อินพุต ให้ใช้เมธอด numpy.log2() ใน Python Numpy วิธีการคืนค่าลอการิทึม Base-2 ของ x นี่คือสเกลาร์ถ้า x เป็นสเกลาร์ พารามิเตอร์ตัวที่ 1 x คือค่าอินพุตแบบอาร์เรย์ พารามิเตอร์ตัวที่ 2 หมด ซึ่งเป็นตำแหน่งที่เก็บผลลัพธ์ หากระบุ จะต้องมีรูปร่างที่อินพุตถ่ายทอดไป หากไม่ระบุหรือไม่มี ระบบจะส่งคืนอาร์เรย์ที่จัดสรรใหม่ ทูเพิลต้องมีความยาวเท่ากับจำนวนเอาต์พุต

พารามิเตอร์ตัวที่ 3 คือตำแหน่งที่เงื่อนไขถูกถ่ายทอดผ่านอินพุต ที่ตำแหน่งที่เงื่อนไขเป็น True อาร์เรย์ขาออกจะถูกตั้งค่าเป็นผลลัพธ์ ufunc ที่อื่นอาร์เรย์ out จะคงค่าเดิมไว้ โปรดทราบว่าหากอาร์เรย์เอาต์ที่ยังไม่ได้กำหนดค่าเริ่มต้นถูกสร้างขึ้นโดยใช้ค่าดีฟอลต์ out=None ตำแหน่งภายในอาร์เรย์ที่มีเงื่อนไขเป็น "เท็จ" จะยังไม่ได้กำหนดค่าเริ่มต้น

ขั้นตอน

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

import numpy as np

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

arr = np.array([1, 2, 10])

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

print("Array...\n", arr)

รับประเภทของอาร์เรย์ -

print("\nOur Array type...\n", arr.dtype)

รับขนาดของอาร์เรย์ -

print("\nOur Array Dimension...\n",arr.ndim)

รับรูปร่างของอาร์เรย์ -

print("\nOur Array Shape...\n",arr.shape)

ในการคืนค่าลอการิทึมฐาน 2 ของอาร์เรย์อินพุต ให้ใช้เมธอด numpy.log2() -

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

ตัวอย่าง

import numpy as np

# Create an array using the array() method
arr = np.array([1, 2, 10])

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

# Get the type of the array
print("\nOur Array type...\n", arr.dtype)

# Get the dimensions of the Array
print("\nOur Array Dimension...\n",arr.ndim)

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

# To return the base 2 logarithm of the input array, use the numpy.log2() method in Python Numpy
# The method returns Base-2 logarithm of x. This is a scalar if x is a scalar.
print("\nResult...\n",np.log2(arr))

ผลลัพธ์

Array...
[ 1 2 10]

Our Array type...
int64

Our Array Dimension...
1

Our Array Shape...
(3,)

Result...
[0. 1. 3.32192809]