NIG分布python代码
时间: 2023-10-13 08:15:19 浏览: 85
以下是使用Python实现NIG分布的代码示例:
```python
import numpy as np
from scipy.special import gamma, kv
class NIG:
def __init__(self, alpha, beta, mu, delta):
self.alpha = alpha
self.beta = beta
self.mu = mu
self.delta = delta
def pdf(self, x):
z = np.sqrt(self.alpha**2 - self.beta**2)
sqrt_term = self.alpha * np.sqrt(self.beta / (np.pi * x**3)) * np.exp((self.beta**2 - 2 * self.alpha * x) / (2 * self.delta * x))
cosine_term = np.exp(z * (self.mu - x)) * kv(1, z * np.sqrt(self.delta * x))
return sqrt_term * cosine_term
def cdf(self, x):
z = np.sqrt(self.alpha**2 - self.beta**2)
x_ = np.sqrt(self.delta) * (x - self.mu)
y = np.sqrt(self.delta) * self.beta / z
t = 1 / (1 + x_ / z)
return 0.5 * (1 + np.sign(x_) * (1 - np.exp(-y * t)) / (np.exp(x_ / z) * kv(1, y) * t**2))
def mean(self):
if self.beta > 0:
return self.mu + self.delta * self.beta / self.alpha
else:
return np.inf
def variance(self):
if self.beta > 2 * self.alpha**2:
return np.inf
else:
return self.delta * (self.alpha**2 - self.beta**2) / (self.alpha**2 * (self.beta - 2 * self.alpha**2))
def skewness(self):
if self.beta > 3 * self.alpha**2:
return np.nan
else:
return 3 * self.beta * np.sqrt(self.delta) / (self.alpha * np.sqrt(self.alpha**2 - self.beta**2))
def kurtosis(self):
if self.beta > 4 * self.alpha**2:
return np.nan
else:
return 3 + 4 * (self.delta * self.beta**2 / (self.alpha**2 * (self.beta - 3 * self.alpha**2)) - 1)
def entropy(self):
return np.log(np.sqrt(self.alpha**2 / (self.delta * self.beta)) * gamma(1/2 * (1 + (self.beta**2 / self.alpha**2))) / np.sqrt(np.pi))
def rvs(self, size=1):
gamma_samples = np.random.gamma(shape=self.alpha**2 / self.delta, scale=self.delta, size=size)
normal_samples = np.random.normal(loc=self.mu, scale=np.sqrt(self.delta / self.beta), size=size)
return normal_samples + self.beta / self.alpha * np.sqrt(gamma_samples)
```
上面的代码中,我们定义了一个名为`NIG`的类,它包含了NIG分布的各种方法,例如概率密度函数`pdf`、累积分布函数`cdf`、均值`mean`、方差`variance`、偏度`skewness`、峰度`kurtosis`、熵`entropy`和随机变量生成函数`rvs`。在初始化时,我们需要提供NIG分布的参数,即$\alpha$,$\beta$,$\mu$和$\delta$。
阅读全文