跳至内容
Oxford PhysicsNotebook

DA / 大一

Untitled

静态 Notebook 阅读页:展示保存的代码和输出,未重新运行。

import pandas as pd
item=pd.read_csv('hubble.csv')
item.head()
   Distance (M-Parsecs)  error in D (M-Parsecs)  Speed (km/sec)  \
0               82.7942                 2.67177         5420.01   
1               89.1251                 2.05433         6011.74   
2               50.8159                 3.51392         3318.94   
3              450.8170                12.46960        30269.10   
4              361.4100                14.99490        22387.20   

   error in v (km/sec)  
0                  300  
1                  300  
2                  300  
3                  300  
4                  300  
import matplotlib.pyplot as plt
%matplotlib inline
x=item['Distance (M-Parsecs)']
y=item['Speed (km/sec)']
yerr=item['error in v (km/sec)']
#plt.show()
import numpy as np
from scipy.optimize import curve_fit
def linear(x, a, b):
    return a * x + b
parameters, covariant_matrix = curve_fit(linear, x, y, sigma=yerr, absolute_sigma=True)
slope = parameters[0] #extract slope, it is parameter #0
intercept = parameters[1] #extract intercept, it is parameter #1
import numpy as np
parameter_uncertainties = np.sqrt(covariant_matrix.diagonal())
slope_error = parameter_uncertainties[0]
intercept_error = parameter_uncertainties[1]

print('Intercept: {:.0f} Error on intercept: {:.0f}'.format(intercept, intercept_error))
print('Slope: {:.2f} Error on slope: {:.2f}'.format(slope, slope_error))
Intercept: 190 Error on intercept: 107
Slope: 63.60 Error on slope: 0.60
fig = plt.figure(figsize=(5,4), dpi=200)
plt.errorbar(x, y, yerr, label='Data', fmt='.', capsize=5)
plt.plot(x, linear(x, slope, intercept), 'r', label='Fitted line') # note: we can write any formula into this plotting function
plt.title('Speed vs Distance')
plt.xlabel('Distance (M-Parsecs)')
plt.ylabel('Speed (km/sec)')
plt.legend()

plt.savefig('hubble_fit.png', dpi=200)
plt.show()
Notebook 中保存的图表
<Figure size 1000x800 with 1 Axes>