题目:
首先编织一个利用秦九韶算法计算一个多项式在给定点的函数值的通用程序,程序包括输入多项式的系数以及给定点,输出函数值,利用编制的程序计算在 x=2 邻域附近的值。画出 p(x) 在 x ∈[1.95,2.05] 上的图像。
算法公式:
实验程序:
- 计算函数值程序(C++)
#include <iostream>
using namespace std;
//秦九韶算法,a数组代表系数(从左往右),n代表系数总数
void QinJiuShao(float a[], int n, float x) {
float sum = a[0];
for (int i = 0; i + 1 < n; i++) {
sum = sum * x + a[i + 1];
}
cout << "秦九韶算法的计算结果为:" << sum << endl;
}
void main() {
cout << "请输入多项式的系数总数n:" << endl;
int n;
cin >> n;
cout << "请依次输入系数:" << endl;
float a[10];
for (int i = 0; i < n; i++) {
float j;
cin >> j;
a[i] = j;
}
cout << "请输入x的值:" << endl;
float x;
cin >> x;
//调用秦九韶算法
QinJiuShao(a, n, x);
}
- 绘制函数图像程序(python)
import numpy as np
import matplotlib.pyplot as plt
func = np.poly1d(np.array([1, -18, 144, -672, 2016, -4032, 5376, -4608, 2304, -512]).astype(float))
x = np.linspace(1.95, 2.05, 30)
y = func(x)
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y(x)')
plt.show()
数值结果:
计算函数值结果:
绘制函数图像结果: