设f(x)=101x^100+100x*99+99x^98+······+3x^2+2x+1,用直接多项式运算和秦九韶算法Matlab编程计算f(x)在x=1,2,3,4上的值,并比较运行时间
时间: 2024-06-14 09:04:08 浏览: 9
以下是使用直接多项式运算和秦九韶算法在Matlab中计算f(x)在x=1,2,3,4上的值,并比较运行时间的代码:
1. 直接多项式运算:
```matlab
coefficients = [101, 100, 99, 98, ..., 2, 1]; % 多项式系数
x_values = [1, 2, 3, 4]; % x的取值
tic % 开始计时
results = zeros(size(x_values)); % 存储计算结果的数组
for i = 1:length(x_values)
x = x_values(i);
result = 0;
for j = 1:length(coefficients)
result = result + coefficients(j) * x^(length(coefficients)-j);
end
results(i) = result;
end
toc % 结束计时并输出运行时间
disp(results); % 输出计算结果
```
2. 秦九韶算法:
```matlab
coefficients = [101, 100, 99, 98, ..., 2, 1]; % 多项式系数
x_values = [1, 2, 3, 4]; % x的取值
tic % 开始计时
results = zeros(size(x_values)); % 存储计算结果的数组
for i = 1:length(x_values)
x = x_values(i);
result = coefficients(1);
for j = 2:length(coefficients)
result = result * x + coefficients(j);
end
results(i) = result;
end
toc % 结束计时并输出运行时间
disp(results); % 输出计算结果
```
运行时间比较:
根据实际情况,直接多项式运算和秦九韶算法的运行时间可能会有所不同。一般来说,秦九韶算法的运行时间会比直接多项式运算更短,因为它减少了乘法和幂运算的次数。但是,具体的运行时间取决于多项式的阶数和计算机的性能。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)