首页 > 解决方案 > 在python中反转一个函数而不求解它

问题描述

我有一个计算偏斜高斯的累积分布函数(cdf)的函数,如下所示。

from scipy import specials

def cdf(x,location,scale,a):
    temp = (x-location)/abs(scale)
    return 0.5*(1+special.erf(temp/np.sqrt(2))) - 2.0*special.owens_t(temp,a)

如何x(准确地)找到 cdf 为 99.9987 的值。我当前的方法结合使用linspace两个限制,计算 linspace 数组的 cdf 并找到最接近 99.9987 的值。但是,由于 cdf 不是线性函数,这种方法不是很健壮并且容易中断。

标签: pythonfunctionnumpyscipy

解决方案


您可以使用scipy 提出的标量求根求解器之一(例如参见二分法):

import numpy as np
from scipy.optimize import root_scalar
from scipy import special

def cdf(x, location, scale, a):
    temp = (x - location)/abs(scale)
    return 0.5*(1 + special.erf(temp/np.sqrt(2))) - 2.0*special.owens_t(temp, a)

# Root finding
location, scale, a = 50, 2, 5
target = 0.999987
sol = root_scalar(lambda x, *args: cdf(x, *args) - target,
                  bracket=(-6*scale + location, 6*scale + location),
                  args=(location, scale, a))

print(sol.flag)

# Graph
x = np.linspace(-6*scale + location, 6*scale + location, 123)
y = cdf(x, location, scale, a)

plt.plot(x, y);
plt.plot(sol.root, target, '.r');
plt.xlabel('x'); plt.ylabel('cdf');

这使:

结果图


推荐阅读