计算a0+a1*x+a2*x*x+a3*x*x*x+......+an*x*x*...*x的值。
时间: 2023-12-24 11:03:33 浏览: 153
计算多项式的值可以使用普通算法或者秦九韶算法。下面是两种算法的示例:
1. 普通算法:
```python
def calculate_polynomial(x, coefficients):
result = 0
power = 1
for coefficient in coefficients:
result += coefficient * power
power *= x
return result
coefficients = [a0, a1, a2, a3, ..., an]
x = 2 # 假设要计算多项式在x=2处的值
result = calculate_polynomial(x, coefficients)
print(result)
```
2. 秦九韶算法:
```python
def calculate_polynomial(x, coefficients):
result = coefficients[-1]
for i in range(len(coefficients) - 2, -1, -1):
result = result * x + coefficients[i]
return result
coefficients = [a0, a1, a2, a3, ..., an]
x = 2 # 假设要计算多项式在x=2处的值
result = calculate_polynomial(x, coefficients)
print(result)
```
这两种算法都可以计算多项式在给定的x处的值。普通算法逐项相乘再相加,而秦九韶算法通过不断累加和乘法的方式计算多项式的值,效率更高。
阅读全文