为chi_square

时间:2018-10-09 10:47:57

标签: python python-3.x python-2.7 python-requests

我需要输入chi_square函数并被卡住,因为它在运行它时始终显示存在无效的语法,不知道我该如何编写脚本?以及如何输入“ v”?

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

data = np.loadtxt("214 ohm.txt", skiprows=1)

xdata = [row[0] for row in data ]#x represents current unit is "V"
ydata = [row[1] for row in data]#y represents voltage unit is "mA"

percision_error_V =  np.array(xdata) * 0.0025 #we are using last digit of reading and multiply by measured voltage
accuracy_error_V = 0.01#we are using DC Vlotage, so use the error it provided online
erry = []

for i in range(len(percision_error_V)):
#to compare percision_error and accuracy_error for Voltage and use the larger one
erry.append(max(percision_error_V[i], accuracy_error_V))

def model_function (x, a, b):
    return a*x + b

p0 = [0 , 0.]#214ohm is measured by ohmeter

p_opt , p_cov = curve_fit ( model_function ,
                           xdata , ydata , p0,
                           erry , True )
print(erry)


a_opt = p_opt[0]
b_opt = p_opt[1]
print(p_cov)
print("diagonal of P-cov is",np.diag(p_cov))

print("a_opt, b_opt is ",a_opt, b_opt)
xhat = np.arange(0, 16, 0.1)

plt.plot(xhat, model_function(xhat, a_opt, b_opt), 'r-', label="model function")

plt.errorbar(xdata, ydata,np.array(erry),linestyle="",marker='s', label="error bar")
plt.legend()
plt.ylabel('Current (mA)')
plt.xlabel('Voltage(V)')
plt.title("Voltage vs. Current with 220ohm Resistor")
plt.show()

p_sigma = np.sqrt(np.diag(p_cov))
print("p_sigma is" ,p_sigma)
for i in range(len(xdata)):
    sum=sum((ydata[i]-model_function(xdata[i], a_opt, b_opt))
    chi.append(sum)

this is the required function I'm supposed to put on python

谢谢

在卡方方程式之前,我的代码还可以,我想知道该如何解决?

1 个答案:

答案 0 :(得分:1)

到目前为止,在此代码示例中,您有缩进,1个括号缺失变量命名问题。

for i in range(len(xdata)):
sum=sum((ydata[i]-model_function(xdata[i], a_opt, b_opt))
1.append(sum)

TO

for i in range(len(xdata)):
    sum=sum((ydata[i]-model_function(xdata[i], a_opt, b_opt)) )
    a.append(sum)

变量不能用数字命名。例如。 1,2,3。它们必须以字符串开头-a1,alfa,betta或s_t,_s。