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

ประเมินพหุนามที่จุด x ใน Python

บทนำ

ในการประเมินพหุนามที่จุด x สามารถใช้เมธอด polynomial.polyval() ใน NumPy ของ Python นี่คือการใช้งานพื้นฐานที่สุดกับอาร์เรย์สัมประสิทธิ์ 1 มิติและจุด x เป็นสเกลาร์

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

  • x: จุดที่ต้องการประเมิน (สามารถเป็นสเกลาร์ ลิสต์ หรืออาร์เรย์)
  • c: อาร์เรย์สัมประสิทธิ์ จัดเรียงโดยที่สัมประสิทธิ์ของพจน์ดีกรี n อยู่ใน c[n]
  • tensor: ควบคุมการแบรอดคาสต์ (ค่าเริ่มต้น: True)

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

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

import numpy as np
from numpy.polynomial.polynomial import polyval

2. สร้างอาร์เรย์สัมประสิทธิ์

c = np.array([1, 2, 3])

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", polyval(1, c))

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

import numpy as np
from numpy.polynomial.polynomial import polyval

# สร้างอาร์เรย์สัมประสิทธิ์
c = np.array([1, 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)

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

ผลลัพธ์

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

สรุป

พหุนาม 1 + 2x + 3x² ที่ x = 1 ให้ค่า 1 + 2(1) + 3(1)² = 6 นี่คือวิธีการประเมินพหุนามพื้นฐานที่สุดใน NumPy