gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:13:03 27 4
gpt4 key购买 nike

我想创建一个随机数生成代码,输入“计数”数,即它在程序中被调用的次数。我想要做的是对于函数的偶数次调用,我想创建 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com