【问题标题】:create a function for chi_square为 chi_square 创建一个函数
【发布时间】:2019-03-14 02:59:24
【问题描述】:

我需要输入 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.append(sum) 中的 1 是从哪里来的?发布完整代码。
  • 你的代码也没有缩进,这在python中是无效的语法
  • 不要将变量命名为与内置函数相同的名称,在这种情况下为 sum
  • chi_square=sum((ydata[i]-model_function(xdata[i], a_opt, b_opt)-p_sigma)/v 您在这一行中缺少一个)。然后,您使用数字 1 作为变量并尝试附加到它。那也错了
  • 我刚从1改成chi,程序还是没有运行

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


【解决方案1】:

到目前为止,此代码示例中存在缩进、缺少 1 个括号变量命名问题

来自

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)

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

【讨论】:

  • 修复缩进后,你认为1.append(sum)会起作用吗?
  • 对不起,我刚刚改了,但它仍然提醒我有一个无效的语法
  • 我没有看到代码的另一面,但在您的示例中,这是问题之一。
  • @ZengClockwise:1 是一个数字。您不能将其用作变量,这意味着您不能附加到它
  • 是的,这是我在您的问题中评论的另一个问题
猜你喜欢
  • 1970-01-01
  • 2019-11-01
  • 2014-04-16
  • 1970-01-01
  • 1970-01-01
  • 2023-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多