简体   繁体   English

如何存储这些值?

[英]How can I store these values?

I'm learning how to code in Python and I have this problem: I want to store the output values of a function (function2) that depends on another function (Function1).我正在学习如何用 Python 编写代码,但我遇到了这个问题:我想存储依赖于另一个函数 (Function1) 的函数 (function2) 的输出值。 I want to store them in order to compute its mean, variance, etc. So far I have made the code that I show below:我想存储它们以计算其均值、方差等。到目前为止,我已经编写了如下所示的代码:

def Function1 (So,K,r,sigma,n):
    payoff = np.zeros(n)
    S = np.zeros(n)
    z = np.random.normal(0,1,n)
    S = So*np.exp((r-sigma**2/2)+sigma*z)
    payoff = np.maximum(S-K,0)
    return(np.exp(-r) * np.mean(payoff))

def Function2 (i, n): 
    for i in range (1,i+1):
        print (np.mean(Function1 (100, 100, 0.15, 0.1, n,)))

Function2(5, 100)
14.539482557181971 
15.231691857185726
14.694893237950245
15.258305904856567
15.502879596134308

I would like some help.我想要一些帮助。 Thank you in advance.先感谢您。

try this.尝试这个。

def Function2 (i, n): 
    results = [] # create an array to store stuff in
    for i in range (1,i+1):
        results.append(Function1 (100, 100, 0.15, 0.1, n,)) #add results to array
        print (np.mean(results[-1])) # print the mean of the last element in the array

It also looks as if you have a type on the for i in range(1,i+1) , I believe that should be for n in range看起来好像你在for i in range(1,i+1)上有一个类型,我相信应该是for n in range

You can use a recursive function or a generator to do that.您可以使用递归函数或生成器来做到这一点。 I'd personally prefer a generator function.我个人更喜欢生成器功能。

def function2(i, n):
    for i in range(1, i+1):
        yield (np.mean(Function1 (100, 100, 0.15, 0.1, n,)))

results = []
for val in function2(i, n):
    results.append(val)

I don't think you really need a func2 , as func2 is just being used to call func1 over a range of values.我不认为您真的需要func2 ,因为func2只是用于在一系列值上调用func1 You can scratch func2 altogether.您可以完全func2

You can store the return values in a list using list comprehension like below.您可以使用如下所示的列表理解将返回值存储在列表中。

results = [np.mean(Function1 (100, 100, 0.15, 0.1, n,) for n in range(n, n+1)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM