1. 实验结果
(1)在定义的类中设置已知的函数值列表为:
(2)在 test.py 中选择直线拟合:
输出:拟合的直线函数及图像;
(3)选择多项式曲线拟合:
输入:多项式拟合函数的次数;
输出:拟合的多项式函数及图像;
①二次多项式函数


②三次多项式函数

③四次多项式函数

(3)选择指数曲线拟合:
输出:拟合的指数函数及图像;
2. 代码
test.py
from class4 import fitting
fitting = fitting()
# 选择方法,根据所选方法的要求输入所需参数后输出所求值
i = int(input('选择方法:1. 直线拟合; 2. 多项式曲线拟合; 3. 指数曲线拟合; \n'))
if i == 1:
fitting.straight()
elif i == 2:
m = int(input('构造m次的多项式拟合函数, m='))
fitting.curve(m)
elif i == 3:
fitting.exponential()
class4.py
import numpy as np
import matplotlib.pyplot as plt
class fitting(object):
"""包括: 1. 直线拟合; 2. 多项式曲线拟合; 3. 指数曲线拟合; """
# 设置已知的函数值数表
def __init__(self):
self.x = [1.0, 2.0, 3.0, 4.0, 5.0]
self.y = [4.0, 4.5, 6.0, 8.0, 9.0]
# 1. 直线拟合:输出拟合的直线函数及图像
def straight(self):
n = len(self.x)
# 拟合直线:p=a+bx,根据已知的公式求得系数a,b
a = (np.sum(np.power(self.x, 2)) * np.sum(self.y) - np.sum(self.x) * np.sum(np.multiply(np.array(self.x), np.array(self.y)))) /