Python的一个函数:映射一个变量

2024-04-20 12:39:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在讨论这个问题:

我有一个函数,它依赖于五(5)个变量才能求解(布莱克-斯科尔斯)。在我解决了这个BS实例的价格后,我想创建一个不同的输入(比如时间)的范围,并将它们与相应的输出(解决方案,所有其他变量保持不变)进行比较。在

所以我希望我能策划

class BS

    def __init__(self, args)
        self.a = float(args[0])
        self.b = float(args[1])
        self.c = float(args[2])
        self.d = float(args[3])
        self.e = float(args[4])
    ...
    ...
    the math
    ...
    ...

现在,我可以创建该类的一个实例,该实例包含从T或time计算价格的方法。在

^{pr2}$

所以,我只需要跑BS价格()可以输出类似

t = range(T-200, T+200, 1)

prices = [BS.price() for x in t]
rhos = [BS.rho() for x in t]
vegas = [BS.vega() for x in t]
parities = [BS.parity() for x in t]


pylab.plot(prices,t)
pylab.plot(rhos,t)
pylab.plot(vegas,t)
pylab.plot(parities,t)

如果价格的唯一变量是时间。有没有更好的方法来观察python的单变量依赖性?我更喜欢R,但这不取决于我。在

谢谢你的帮助!在

编辑:我不知道当时间变量正在进行数学运算时,如何使用列表理解数学.sqrt()和scipy.cdf公司(). 有办法吗?我知道如何根据变量t,一个float来构建函数。如何将值列表输入到数学.sqrt()或scipy.cdf公司()? 谢谢你的帮助!在


Tags: 实例方法函数inselfforbsplot
1条回答
网友
1楼 · 发布于 2024-04-20 12:39:59

I don't know how to use list comprehensions when the time variable is undergoing math operations like math.sqrt() and scipy.cdf(). Is there a way to do this? I know how to build the function relying on variable t, a float. How would I input a list of values into math.sqrt() or scipy.cdf()?

可考虑的选项很少:

  • Python生成器允许您在遍历集合/值列表时动态生成结果。这里有一个很好的讨论:
    http://wiki.python.org/moin/Generators

  • Python的map和reduce函数允许您将函数(例如sqrt)应用于列表中的每个元素,使用reduce,您可以将某些操作的每个结果缩减为一个值(请参见2.1“映射列表”):
    http://www.siafoo.net/article/52

相关问题 更多 >