บทนำ
ในการประเมินพหุนามที่ระบุโดยราก (roots) ที่จุด x สามารถใช้เมธอด polynomial.polyvalfromroots() ใน NumPy พร้อม tensor=True (ค่าเริ่มต้น) ซึ่งจะทำให้ทุกคอลัมน์ของสัมประสิทธิ์ใน r ถูกประเมินสำหรับทุกองค์ประกอบของ x
พารามิเตอร์สำคัญ
- x: จุดที่ต้องการประเมิน
- r: อาร์เรย์ของราก ดัชนีแรกคือดัชนีราก ดัชนีที่เหลือนับพหุนามหลายตัว
- tensor: หากเป็น True (ค่าเริ่มต้น) รูปร่างของ r จะขยาย ทำให้ทุกคอลัมน์ของ r ถูกประเมินสำหรับทุก x
ขั้นตอนการทำงาน
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. ประเมินพหุนามจากราก ด้วย tensor=True
print("\nResult...\n", polyvalfromroots([-2, 1], c, tensor=True))
ตัวอย่างโค้ดสมบูรณ์
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)
# ประเมินพหุนามจากราก ด้วย tensor=True
print("\nResult...\n", polyvalfromroots([-2, 1], c, tensor=True))
ผลลัพธ์
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...
[[-0. 3.]
[ 3. 0.]]
สรุป
เมื่อ tensor=True ผลลัพธ์มีรูปร่าง (2, 2) ซึ่งแต่ละแถวสอดคล้องกับจุด x (-2 และ 1) และแต่ละคอลัมน์สอดคล้องกับพหุนามจากคอลัมน์ของ r ทุกชุดรูทจะถูกประเมินที่ทุกจุด x