Python 为chi_square创建一个函数

Python 为chi_square创建一个函数,python,python-3.x,python-2.7,python-requests,Python,Python 3.x,Python 2.7,Python Requests,我需要输入chi_square函数,但我被卡住了,因为它在运行时总是显示有无效语法,我想知道应该如何编写脚本?如何输入“v” 谢谢 在卡方方程出现之前,我的代码是正常的,我想知道应该如何修复它?到目前为止,在这个代码示例中,您有一个缩进,一个缺少的括号,以及变量命名问题 从 到 变量不能用数字命名。例如1,2,3。它们必须以字符串-a1、alfa、betta或s_t、_s.开头。1从何而来。追加(sum)?发布完整代码。您的代码也没有缩进,这在python中是无效的语法,您的变量名称与内置函数

我需要输入chi_square函数,但我被卡住了,因为它在运行时总是显示有无效语法,我想知道应该如何编写脚本?如何输入“v”

谢谢


在卡方方程出现之前,我的代码是正常的,我想知道应该如何修复它?

到目前为止,在这个代码示例中,您有一个缩进,一个缺少的括号,以及变量命名问题


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

1从何而来。追加(sum)?发布完整代码。您的代码也没有缩进,这在python中是无效的语法,您的变量名称与内置函数不同,
sum
在本例中
chi_square=sum((ydata[i]-model_函数(xdata[i],a_opt,b_opt)-p_sigma)/v
您在这行中缺少一个
。然后,您使用一个数字
1
作为变量,并尝试附加到它。这是错误的。我刚从1改为chi,但程序仍然无法运行。在修复缩进后,您认为
1.append(sum)
可以工作吗?很抱歉,我刚刚更改了它,但它仍然提醒我,有一个无效的syntax尚未看到代码的另一面,但在您的示例中,这是问题之一。@Zengclock:
1
是一个数字。你不能用它作为变量,这意味着你不能附加到它。是的,这是另一个问题,正如我在你的问题中所评论的
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)
for i in range(len(xdata)):
sum=sum((ydata[i]-model_function(xdata[i], a_opt, b_opt))
1.append(sum)
for i in range(len(xdata)):
    sum=sum((ydata[i]-model_function(xdata[i], a_opt, b_opt)) )
    a.append(sum)