python : How to store a value generated in a function for the second call of that function

标签 python

我想创建一个随机数生成代码,输入“count”数字,即在程序中调用它的次数。我想要做的是,对于函数的偶数次调用,我想创建 2 个随机数,即“y1 ,y2”,但是 我只想输出 y1 并 保存 y2函数的下一次调用。因此,在奇数次调用时,函数将直接输出上一次调用的 y2 。感谢帮助。到目前为止的代码:

import random
import math

def gaussianRandom ( count):
 count += 1
 if count%2 == 0:
  while (1):
   x1 = random.uniform(-1, 1)
   x2 = random.uniform(-1, 1)
   r = x1**2 + x2**2     
   if (r < 1):
    break

  y1 = x1 * math.sqrt( (-2 * math.log(r)) / r )
  y2 = x2 * math.sqrt( (-2 * math.log(r)) / r )

return y1

最佳答案

函数可以有属性。

import random
import math

def gaussianRandom ( count):
    count += 1
    if count%2 == 0:
        while (1):
            x1 = random.uniform(-1, 1)
            x2 = random.uniform(-1, 1)
            r = x1**2 + x2**2
            if (r < 1):
                break

    y1 = x1 * math.sqrt( (-2 * math.log(r)) / r )
    gaussianRandom.y2 = x2 * math.sqrt( (-2 * math.log(r)) / r )

    print(gaussianRandom.y2)
    return y1

gaussianRandom.y2 = 99
print "y2", gaussianRandom(3)
print gaussianRandom(3)
print gaussianRandom(3)

y2 0.919282832355

-0.0887376744533

y2 -1.71553385287

0.422645022058

y2 -0.0668389339817

0.600351205084

关于 python : How to store a value generated in a function for the second call of that function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26482397/

相关文章:

python - 在 Python 中将二进制表示形式转换为带符号的 64 位整数

python - 在循环结果集时插入行

Python如何将单引号转双引号格式化为json字符串

Python 重新 : Storing multiple matches in variables

python - Keras 在激活函数之前检索节点的值

python - 使用 easy_install 安装 Mechanize

python - 如何使用python在pygame中定义快进按钮?

python - 谷歌colab,无法 pickle 我的defaultdict - recursionerror

python - 如何在模型文件中建立 django 模型应定义为 NOT NULL?

python - Linux 服务器上的 PyMongo 和 Flask