【问题标题】:Summing values from an iterated function in order to average the total对迭代函数的值求和以平均总和
【发布时间】:2016-02-07 08:48:27
【问题描述】:

我的代码如下。

import random
times_to_repeat = 10**6
circle_radius = 1
times_to_iterate = 100

def in_circle(x, y):
    return x**2 + y**2 < circle_radius**2

def pi_approximator():
    points_in_circle = 0
    for a in range(times_to_repeat):
        x = random.random()
        y = random.random()
        if in_circle(x, y):
            points_in_circle += 1
    pi_approx = (points_in_circle / times_to_repeat) * 4
    print(pi_approx)

def pi_iterator():
    for b in range(times_to_iterate):
        pi_calculator()

pi_iterator()

目的是使用围绕圆的随机生成的点创建 pi 的近似值。

我已经把它记下来了,但我试图通过多次迭代函数然后对其进行平均来使其更精确。

我找到了大量有关如何汇总您手动创建的列表的信息,但我很难找到有关如何将函数中的值相加的任何信息。

我想要的输出是从pi_iterated() 中获取值,将它们加在一起,然后除以times_to_iterate,以便在我的所有迭代中获得pi 的平均近似值。

我已经尝试了一些方法,但它们大多只是在黑暗中拍摄,而且都失败了,所以我认为将它们包含在我的代码中没有任何意义。

如果他们需要,我可以向人们提供我所做的失败尝试。

【问题讨论】:

  • 不应该是pi_calculatorpi_approximator

标签: python python-3.x sum iteration pi


【解决方案1】:

在 pi_approx 计算中使用 float 来获得正确的值,您必须保存该值而不仅仅是打印。因此,您可以将其退回并将其存储在列表中。该列表给出的平均值将是您想要的输出

def pi_approximator():
    ...
    ...
    pi_approx = (float(points_in_circle) / times_to_repeat) * 4
    return (pi_approx)

def pi_iterator():
    result = []
    for b in range(times_to_iterate):
        result.append(pi_approximator())
    print float(sum(result))/len(result)
pi_iterator()

【讨论】:

  • 问题被标记为python-3.x,因此不需要float
猜你喜欢
  • 2016-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多