我正在尝试使用python计算平方和的总和。我知道TSS的公式是:在这里输入图片描述
我创建了一个代码来做这件事:
from statistics import mean
x = ([3,1,3,1,3,13])
def tss(a):
m = mean(a)
for i in a:
i += ((i-m)**2)
return (i)
print(tss(x))问题是:它一直返回给我94,但我知道正确答案是102。我不知道我做错了什么。有人能帮我吗? 1:https://i.stack.imgur.com/Alx6r.png
发布于 2021-10-02 23:09:15
i在每次循环时都会重置。因此,在最后一次循环中,您的函数将擦除所有先前的和,将i设置为13,然后将13与平均值之间的差值的平方添加到i (现在是13),返回94。您需要一个不同的变量来跟踪和,这样它就不会在每次循环中丢失。您需要:
from statistics import mean
x = ([3,1,3,1,3,13])
def tss(a):
m = mean(a)
n = 0
for i in a:
n += ((i-m)**2)
return (n)
print(tss(x))
'''
@mateen's answer is more pythonic and will perform better than a loop, but I don't think you'll get the understanding from it. Welcome to python!发布于 2021-10-02 23:09:26
如果不使用numpy:
def tss(xs):
m = sum(xs) / len(xs)
return sum((x - m)**2 for x in xs)使用numpy:
import numpy as np
def tss(x):
return ((x - np.mean(x))**2).sum()发布于 2021-10-02 23:32:01
如果您想保留您的初始脚本,只需执行以下操作:
from statistics import mean
x = ([3, 1, 3, 1, 3, 13])
def tss(a):
total = 0
for i in a:
total = total + ((i-mean(a))**2)
return totalhttps://stackoverflow.com/questions/69420861
复制相似问题