给定两个文本文件,并将“ x”和“ y”作为数组,编写一个子例程,该例程将给出斜率“ m”并截取最小二乘最佳拟合线的“ b”。
x = 1,2,3,4
y = 5,6,7,8
m =(((sum(xy)-sum(x)ybar)/(((sumx ^ 2)-(sum(x)xbar)))
b = ybar-m(xbar)。
xbar和ybar是x和y数组的平均值。
我的老师说,我们不能使用np.loadtxt以外的固有python函数。
除了定义4个数组组合,然后是4个组合中的每个组合的总和,然后找到m,我正在尝试找到一种更有效的方法。
我试图将数组组合的每个和定义为嵌套循环。
import numpy as np
x = np.loadtxt("C:/Users/Bob/Documents/School/Comp Phys/xlsf.dat")
y = np.loadtxt("C:/Users/Bob/Documents/School/Comp Phys/ylsf.dat")
xbar = np.mean(x)
ybar = np.mean(y)
nx = len(x)
ny = len(y)
q = print(xbar)
sum1=[[0 for i in range(nx)] for j in range(ny)]
for i in range (0, nx):
for j in range (0, ny):
sum1[i][j] = x[i] * y[j]
for i in range (ny):
for j in range (nx):
((sum1[i][j]))
sum2=[[0 for q in range(nx)] for r in range(ybar)]
for q in range (0, nx):
for r in range (0, ybar):
sum2[q][r] = x[q] * ybar[r]
for q in range (ybar):
for r in range (nx):
((sum2[q][r]))
Python陷入了sum2部分,并出现以下错误:
sum2 = [[对于q在范围(nx)中为0,对于r在范围(ybar)中]]
TypeError:“ numpy.float64”对象无法解释为整数。
最佳答案
xbar = np.mean(x)
ybar = np.mean(y)
在您的代码中,xbar和ybar是数组的平均值,以浮点数表示(numpy类型为float 64)。
在下面的行中,将for循环使用range(ybar)。
sum2=[[0 for q in range(nx)] for r in range(ybar)]
for q in range (0, nx):
for r in range (0, ybar):
sum2[q][r] = x[q] * ybar[r]
for q in range (ybar):
for r in range (nx):
((sum2[q][r]))
但是,您的for循环不能使用非整数循环,因为它们不能循环(例如4.5次)。您可能需要构建代码以不同的方式计算总和,例如使用不同的变量作为循环范围。
我仍然不确定您要尝试进行哪些计算,但是我已经构造了以下代码,您可以通过这些代码。它很简单,可以按原样执行每个步骤,因此您可以优化代码本身以使其运行更好,但是希望它将为您提供有关如何构建计算的想法。
# sum1 array, x*y
sum1=[[0 for i in range(nx)] for j in range(ny)]
for i in range (0, nx):
for j in range (0, ny):
sum1[i][j] = x[i] * y[j]
# sum2 array, x
# notice that the array sum2 can just be completely replaced by x[]
sum2=[[0 for q in range(nx)] for r in range(ny)]
for q in range (0, nx):
sum2[q][0] = x[q]
# sum3 array, x^2
# same for sum3, we can just replace it with x[]*x[]
sum3 = [[0 for q in range(nx)] for r in range(ny)]
for q in range (0, nx):
sum2[q][0] = x[q]*x[q]
term1 = 0
term2 = 0
term3 = 0
term4 = 0
# sum each 'sum array' and apply them to the term variables
for i in range(nx):
for j in range(ny):
term1 += sum1
term2 += sum2
term3 += sum3
term4 += sum2
term2 = term2 * ybar // we multiply that sum by the coefficients
term4 = term4 * xbar
m = (term1 - term2 ) / (term3 - term4 ) // calculate m
b = ybar - m * xbar // calculate b
关于python - 来自两个阵列的最小二乘最佳拟合线的斜率m,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58089601/