光电效应测普朗克常数实验,科大奥瑞平台计算Python程序

    # 利用最小二乘法
    Xi, Yi, XX, YY, XY = 0, 0, 0, 0, 0
    for i in range(0, int(N)):
        Xi += x[i]
        Yi += y[i]
        XX += x[i]*x[i]
        YY += y[i]*y[i]
        XY += x[i]*y[i]
    a = (Yi*Xi - N*XY)/(Xi*Xi - N*XX)
    b = (Yi - a*Xi)/N
    r = abs(Yi*Xi/N-XY)/math.sqrt((XX-Xi*Xi/N)*(YY-Yi*Yi/N))
# 进行绘制图像
mpl.rcParams['font.sans-serif'] = ['SimHei']
    plt.plot(X, Y, 'ro-', color='blue', alpha=0.5, linewidth=1, label="线性拟合结果:Y={}X+{}".format(a, b))
    plt.legend(loc="upper right")
    plt.xlabel('截止频率V')
    plt.ylabel('遏制电压U')

实验得到遏止电压后

分别输入运行:

结果得到为

光电效应测普朗克常数实验,科大奥瑞平台计算Python程序_第1张图片

 光电效应测普朗克常数实验,科大奥瑞平台计算Python程序_第2张图片

完整代码:

import math
from pylab import *
def 最小二乘法拟合(x, y):
    N = float(len(x))
    Xi, Yi, XX, YY, XY = 0, 0, 0, 0, 0
    for i in range(0, int(N)):
        Xi += x[i]
        Yi += y[i]
        XX += x[i]*x[i]
        YY += y[i]*y[i]
        XY += x[i]*y[i]
    a = (Yi*Xi - N*XY)/(Xi*Xi - N*XX)
    b = (Yi - a*Xi)/N
    r = abs(Yi*Xi/N-XY)/math.sqrt((XX-Xi*Xi/N)*(YY-Yi*Yi/N))
    return a, b, r


if __name__ == '__main__':
    Y = eval(input("请分别输入不同波长对应不同遏制电压:"))
    X = [5.198e14, 5.492e14, 6.882e14, 7.410e14, 8.216e14]
    Z = ["577.0nm 截止频率:", "546.1nm 截止频率:", "435.8nm 截止频率:", "404.7nm 截止频率:", "365.0nm 截止频率:"]
    Z2 = ["577.0nm 截止频率:", "546.1nm 截止频率:", "435.8nm 截止频率:", "404.7nm 截止频率:", "365.0nm 截止频率:"]
    a, b, r = 最小二乘法拟合(X, Y)
    H = 6.6260693e-34
    K = -a * 1.6e-19
    for i, j in enumerate(X):
        z = Z.pop(0)
        print("{} v{}: {}e14 Hz".format(z, i, j/1e14))
    for i, j in enumerate(Y):
        z2 = Z2.pop(0)
        print("{} U{}: {} V".format(z2, i, j))

    print("线性拟合结果:Y = {} X +{}, 相关系数={}".format(a, b, r))
    print("故求得普朗克常量为(h):|h| = k*e = {}J·s".format(K))
    print("公认普朗克值(H):{}J·s".format(H))
    print("相对误差: (h-H)/H = {}%".format(((K-H)/H)*100))

    mpl.rcParams['font.sans-serif'] = ['SimHei']
    plt.plot(X, Y, 'ro-', color='blue', alpha=0.5, linewidth=1, label="线性拟合结果:Y={}X+{}".format(a, b))
    plt.legend(loc="upper right")
    plt.xlabel('截止频率V')
    plt.ylabel('遏制电压U')

plt.show()
# plt.savefig('demo.jpg')  # 保存该图片
plt.plot()

你可能感兴趣的:(python,算法,线性回归)