使用 scipy.integrate.dblquad 在 Python 中对 x*np.log(x) 进行双重积分 [英] Double integration of x*np.log(x) in Python using scipy.integrate.dblquad
问题描述
下面的代码使用与 scipy.integrate.dblquad
的双重积分来计算 copula 密度函数的微分熵 c*np.log(c)
code>c,它有一个依赖参数,theta
,通常为正.可以在
将 numpy 导入为 np从 scipy 导入集成def copula_entropy(theta):c = lambda v, u: ((1+theta)*(u*v)**(-1-theta)) * (u**(-theta)+ v**(-theta) -1)**(-1/theta-2)返回 -integrate.dblquad(c*np.log(c), 0, 1, lambda u: 0, lambda u: 1)[0]
调用函数
copula_entropy(1)
返回错误
TypeError: ufunc 的循环不支持没有可调用日志方法的函数类型的参数 0
如何使函数起作用?
第一个参数必须是可调用的,所以只需将它包装在 lambda
本身中:
将 numpy 导入为 np从 scipy 导入集成def copula_entropy(theta):c = lambda v, u: ((1+theta)*(u*v)**(-1-theta)) * (u**(-theta)+v**(-theta)-1)**(-1/theta-2)return -integrate.dblquad(lambda u,v: c(v,u)*np.log(c(v,u)), 0, 1, lambda u: 0, lambda u: 1)[0]
(请注意,我还根据您提供的公式更改了 c
的表达式).
The code below uses double integration with scipy.integrate.dblquad
to calculate the differential entropy, c*np.log(c)
, of a copula density function c
, which has one dependence parameter, theta
, usually positive. Formula can be found here.
import numpy as np
from scipy import integrate
def copula_entropy(theta):
c = lambda v, u: ((1+theta)*(u*v)**(-1-theta)) * (u**(-theta)
+ v**(-theta) -1)**(-1/theta-2)
return -integrate.dblquad(c*np.log(c), 0, 1, lambda u: 0, lambda u: 1)[0]
Calling the function with
copula_entropy(1)
returns the error
TypeError: loop of ufunc does not support argument 0 of type function which has no callable log method
How can the function be made to work?
The first argument must be a callable, so just wrap it in a lambda
itself:
import numpy as np
from scipy import integrate
def copula_entropy(theta):
c = lambda v, u: ((1+theta)*(u*v)**(-1-theta)) * (u**(-theta)+v**(-theta)-1)**(-1/theta-2)
return -integrate.dblquad(lambda u,v: c(v,u)*np.log(c(v,u)), 0, 1, lambda u: 0, lambda u: 1)[0]
(Please note that I also changed the expression for c
according to the formula you gave).
这篇关于使用 scipy.integrate.dblquad 在 Python 中对 x*np.log(x) 进行双重积分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!