เมื่อมีสัมประสิทธิ์พหุนามอยู่ใน List เรียงจากกำลังสูงสุดไปต่ำสุด สามารถคำนวณค่าพหุนามที่ x ใดๆ ได้ด้วยลูปซ้อน
ตัวอย่างโค้ด
my_polynomial = [2, 5, 3, 0]
num = 2
poly_len = len(my_polynomial)
my_result = 0
for i in range(poly_len):
my_sum = my_polynomial[i]
for j in range(poly_len - i - 1):
my_sum = my_sum * num
my_result = my_result + my_sum
print("The polynomial equation for the given list of co-efficients is :")
print(my_result)
ผลลัพธ์
The polynomial equation for the given list of co-efficients is : 42
คำอธิบาย
- List my_polynomial = [2, 5, 3, 0] หมายถึง 2x³ + 5x² + 3x + 0
- แทน x = 2: 2(8) + 5(4) + 3(2) + 0 = 16+20+6 = 42
- ลูปภายนอกวนสัมประสิทธิ์, ลูปภายในคูณ x ตามกำลัง