Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Compute a Polynomial Equation given that the Coefficients of the Polynomial are stored in a List
When you need to compute a polynomial equation where the coefficients are stored in a list, you can use nested loops to calculate each term. A polynomial like 2x³ + 5x² + 3x + 0 can be evaluated by multiplying each coefficient by the corresponding power of x.
Understanding Polynomial Evaluation
For a polynomial represented as a list [2, 5, 3, 0], this corresponds to:
2x³ (coefficient 2, power 3)
5x² (coefficient 5, power 2)
3x¹ (coefficient 3, power 1)
0x? (coefficient 0, power 0)
Example
Here's how to evaluate the polynomial when x = 2 ?
coefficients = [2, 5, 3, 0]
x = 2
poly_len = len(coefficients)
result = 0
for i in range(poly_len):
term = coefficients[i]
for j in range(poly_len - i - 1):
term = term * x
result = result + term
print("The polynomial equation for the given list of coefficients is:")
print(result)
The polynomial equation for the given list of coefficients is: 42
How It Works
The algorithm works by calculating each term of the polynomial:
Term 1: 2 × 2³ = 2 × 8 = 16
Term 2: 5 × 2² = 5 × 4 = 20
Term 3: 3 × 2¹ = 3 × 2 = 6
Term 4: 0 × 2? = 0 × 1 = 0
Final result: 16 + 20 + 6 + 0 = 42
Alternative Method Using Built-in Power Function
You can also use Python's pow() function for cleaner code ?
coefficients = [2, 5, 3, 0]
x = 2
result = 0
for i, coeff in enumerate(coefficients):
power = len(coefficients) - i - 1
result += coeff * pow(x, power)
print("Polynomial result:", result)
Polynomial result: 42
Conclusion
To evaluate a polynomial from a coefficient list, multiply each coefficient by the variable raised to the appropriate power. The nested loop approach builds powers by repeated multiplication, while using pow() provides a more direct solution.
