非线性方程组函数返回值打印时产生误差的原因

2024-04-25 08:47:20 发布

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

我使用fsolve来解方程,但是当我再次将解放入KMV()函数时,它会引发一个异常。我想不通。。。你知道吗

def KMV(x, *args):
    valueToEquity = float(x[0])
    volOfValue = float(x[1])
    equityToDebt, volOfEquity, riskFreeRate, TimeToMaturity = args
    d1 = (np.log(equityToDebt * equityToDebt) + (riskFreeRate + 0.5 *    volOfEquity**0.5)
      * TimeToMaturity) / (volOfEquity * TimeToMaturity**0.5)
    d2 = (np.log(abs(equityToDebt * equityToDebt)) + (riskFreeRate - 0.5 * volOfEquity**0.5)
      * TimeToMaturity) / (volOfEquity * TimeToMaturity**0.5)
    f1 = valueToEquity * norm.cdf(d1) - np.exp(-riskFreeRate * TimeToMaturity) * norm.cdf(d2) / equityToDebt - 1
    f2 = norm.cdf(d1) * valueToEquity * volOfValue - volOfEquity
    return f1, f2



def solver():
    equityToDebt = 1
    volOfEquity = 0.2
    riskFreeRate = 0.03
    TimeToMaturity = 1
    args = equityToDebt, volOfEquity, riskFreeRate, TimeToMaturity
    x0 = [1, 0.2]
    sol = fsolve(KMV, x0, args=args)
    print(sol)

我得到的解决办法是

[ 1.29409904  0.17217742]

但是,如果我使用以下代码:

print(KMV(sol, args=args))

例外情况如下:

    print(KMV(sol, args = args))
TypeError: KMV() got an unexpected keyword argument 'args'

然后我换了另一种方式来调用KMV():

print(KMV(sol, args))

另一个例外是:

ValueError: need more than 1 value to unpack

Tags: normdefnpargsd1printcdfsol
2条回答

如果在KVM的声明中从args中删除前导的*,则可以这样调用它,但如果这样做,其他代码将失败。*args表示可变函数,即具有可变参数数的函数。你知道吗

如果您也想传递关键字,那么就传递一个字典,通常称为kwargs。请注意,它们的左右顺序非常关键。下面是一个简单的例子:

def KMV(x, *args, **kwargs):
   if 'args' in kwargs:
      args = kwargs['args'],
   return args

args = 1,2,3,4
sol = 42
print(KMV(sol, args))
print(KMV(sol, args = args))

看看这个快速提醒。。。你知道吗

def func(arg1):
    print(arg1)

func('hello') # output 'hello'

def func(*args):
    # you can call this function with as much arguments as you want !
    # type(args) == tuple
    print(args)

func('some', 'args', 5) # output ('some', 'args', 5)

def func(required_arg, optional_arg=False, other_optional_arg='something'):
    print(required_arg, optional_arg, other_optional_arg)

    # so, say you just want to specify the value of other_optional_arg, and let optional_arg have its default value (here False)
    # with python, you can do this

func('the value for the required arg', other_optional_arg='My super great value') # output ('the value for the required arg', False, 'My super great value')

def func(**kwargs):
    # type(kwargs) = dict
    print(kwargs )

func(arg1='hello', arg2='world', arg3='!') # output {'arg3': '!', 'arg2': 'world', 'arg1': 'hello'}

相关问题 更多 >