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

ประเมินพหุนามจากราก ที่จุด x ด้วยอาร์เรย์รากหลายมิติใน Python

บทนำ

ในการประเมินพหุนามที่ระบุโดยราก (roots) ที่จุด x สามารถใช้เมธอด polynomial.polyvalfromroots() ใน NumPy ของ Python เมื่อ x เป็นสเกลาร์ (scalar) จะถูกจัดการเป็นค่าเดียว

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

  • x: จุดที่ต้องการประเมิน (สามารถเป็นสเกลาร์ได้)
  • r: อาร์เรย์ของราก หากเป็นหลายมิติ ดัชนีแรกคือดัชนีราก
  • tensor: ค่าเริ่มต้นเป็น True

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

1. นำเข้าไลบรารีที่จำเป็น

import numpy as np
from numpy.polynomial.polynomial import polyvalfromroots

2. สร้างอาร์เรย์หลายมิติ (ใช้เป็นราก)

c = np.arange(-2, 2).reshape(2, 2)

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

print("Our Array...\n", c)
print("\nDimensions of our Array...\n", c.ndim)
print("\nDatatype of our Array object...\n", c.dtype)
print("\nShape of our Array object...\n", c.shape)

4. ประเมินพหุนามจากราก ที่จุด x = 1

print("\nResult...\n", polyvalfromroots(1, c))

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

import numpy as np
from numpy.polynomial.polynomial import polyvalfromroots

# สร้างอาร์เรย์หลายมิติ (ใช้เป็นราก)
c = np.arange(-2, 2).reshape(2, 2)

# แสดงข้อมูลอาร์เรย์
print("Our Array...\n", c)
print("\nDimensions of our Array...\n", c.ndim)
print("\nDatatype of our Array object...\n", c.dtype)
print("\nShape of our Array object...\n", c.shape)

# ประเมินพหุนามจากราก ที่จุด x = 1 (สเกลาร์)
print("\nResult...\n", polyvalfromroots(1, c))

ผลลัพธ์

Our Array...
 [[-2 -1]
  [ 0  1]]
Dimensions of our Array...
 2
Datatype of our Array object...
 int64
Shape of our Array object...
 (2, 2)
Result...
 [3. 0.]

สรุป

เมื่อ x เป็นสเกลาร์ (1) และ tensor=True (ค่าเริ่มต้น) ผลลัพธ์จะเป็นอาร์เรย์ 1 มิติที่มีขนาดเท่ากับจำนวนคอลัมน์ของ r (2 คอลัมน์) แสดงค่าของพหุนามแต่ละตัวที่ x=1