📅  最后修改于: 2023-12-03 14:57:08.298000             🧑  作者: Mango
自然数平方的平均值是指从1开始,将自然数的平方依次加起来,然后将其平均分配到每个数上。
公式如下所示:
$$ \frac{1^2 + 2^2 + 3^2 + ... + n^2}{n} $$
该任务可以用程序实现,以下是示例代码:
def sum_of_squares(n):
return sum([i*i for i in range(1, n+1)])
def average_of_squares(n):
return sum_of_squares(n) / n
n = 10
average = average_of_squares(n)
print(f"The average of squares up to {n} is {average}")
代码解释:
sum_of_squares(n)
函数用来计算自然数的平方和;average_of_squares(n)
函数用来计算自然数平方的平均值;n
变量指定了自然数的上限,这里设为10;average
变量存储了自然数平方的平均值;print
语句用来输出结果。以上代码输出结果如下:
The average of squares up to 10 is 38.5
如果需要更高的精度,可以使用 Decimal
类型来进行计算。代码示例如下:
from decimal import *
def sum_of_squares(n):
return sum([Decimal(i)**2 for i in range(1, n+1)])
def average_of_squares(n):
return sum_of_squares(n) / Decimal(n)
n = 10
average = average_of_squares(n)
print(f"The average of squares up to {n} is {average}")
输出结果为:
The average of squares up to 10 is 38.5