Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

某地在某日的温度记录如下,共有24个数据点。 时间,p.m. 1 2 3 4 5 6 7 8 9 10 11 午夜 温度 66 66 65 64 63 63 62 61 60…

  1. User

    某地在某日的温度记录如下,共有24个数据点。 时间,p.m. 1 2 3 4 5 6 7 8 9 10 11 午夜 温度 66 66 65 64 63 63 62 61 60 60 59 58 时间,a.m. 1 2 3 4 5 6 7 8 9 10 11 正午 温度 58 58 58 58 57 57 57 58 60 64 67 68 寻找上表的3次多项式最小二乘曲线并画图。 请用python语言实现

  2. Assistant

    可以使用numpy和matplotlib库来实现该问题。

    首先,我们需要将表格数据转换成两个一维数组,即时间和温度。代码如下:

    import numpy as np
    import matplotlib.pyplot as plt
    
    # 时间数据,分别对应 p.m. 1 2 3 ... 11 午夜 和 a.m. 1 2 3 ... 10 11 正午
    time = np.array([
        1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 
        12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
    ])
    
    # 温度数据,对应时间表格中的值
    temperature = np.array([
        66, 66, 65, 64, 63, 63, 62, 61, 60, 60, 59, 58,
        58, 58, 58, 57, 57, 57, 58, 60, 64, 67, 68
    ])
    

    下一步,我们使用numpy库中的polyfit函数来计算3次多项式的系数。该函数的第一个参数是x轴的数据,第二个参数是y轴的数据,第三个参数是多项式阶数。

    # 计算3次多项式的系数,p是一个长度为4的数组
    p = np.polyfit(time, temperature, 3)
    print("多项式系数:", p)
    

    最后,我们使用matplotlib库来绘制图像。首先,我们需要生成一组在时间范围内均匀分布的数据点用于绘制多项式曲线。然后,我们将原始数据和多项式曲线一起绘制在同一个坐标系中。

    # 在时间范围内生成50个均匀分布的数据点
    x = np.linspace(1, 24, 50)
    
    # 计算这些数据点的多项式函数值
    y = np.polyval(p, x)
    
    # 绘制原始数据点和多项式曲线
    plt.plot(time, temperature, 'o', label='原始数据')
    plt.plot(x, y, label='多项式曲线')
    
    # 设置坐标轴标签和图例
    plt.xlabel('时间')
    plt.ylabel('温度')
    plt.legend()
    
    # 显示图像
    plt.show()
    

    完整代码如下:

    import numpy as np
    import matplotlib.pyplot as plt
    
    # 时间数据,分别对应 p.m. 1 2 3 ... 11 午夜 和 a.m. 1 2 3 ... 10 11 正午
    time = np.array([
        1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 
        12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
    ])
    
    # 温度数据,对应时间表格中的值
    temperature = np.array([
        66, 66, 65, 64, 63, 63, 62, 61, 60, 60, 59, 58,
        58, 58, 58, 57, 57, 57, 58, 60, 64, 67, 68
    ])
    
    # 计算3次多项式的系数,p是一个长度为4的数组
    p = np.polyfit(time, temperature, 3)
    print("多项式系数:", p)
    
    # 在时间范围内生成50个均匀分布的数据点
    x = np.linspace(1, 24, 50)
    
    # 计算这些数据点的多项式函数值
    y = np.polyval(p, x)
    
    # 绘制原始数据点和多项式曲线
    plt.plot(time, temperature, 'o', label='原始数据')
    plt.plot(x, y, label='多项式曲线')
    
    # 设置坐标轴标签和图例
    plt.xlabel('时间')
    plt.ylabel('温度')
    plt.legend()
    
    # 显示图像
    plt.show()
    

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.