我正在尝试用Python在数字上求解此方程(numpy / scipy,一切可用)
在此公式中, K 是一个常数, f 和 g 是两个依赖于E计数器的术语(这是一个离散表示)整数),其中 x 是我要查找的变量。
例如,以 E 为3个术语,即:
f(E)和 g(E)也是已知的。
我从numpy上读到有关使用“ fsolve”的信息,尽管我不明白如何自动生成作为项总和的函数。我可能会手动完成,但是要花50个学期才能用完一段时间,所以我也想学习一些新知识。
答案 0 :(得分:3)
You can use scipy.optimize.fsolve
where the function is constructed using numpy.sum
:
import numpy as np
import scipy.optimize
np.random.seed(123)
f = np.random.uniform(size=50)
g = np.random.uniform(size=f.size)
K = np.sum(f * np.exp(-g*np.pi))
def func(x, f, g, K):
return np.sum(f * np.exp(-g*x), axis=0) - K
# The argument to the function is an array itself,
# so we need to introduce extra dimensions for f, g.
res = scipy.optimize.fsolve(func, x0=1, args=(f[:, None], g[:, None], K))
Note that for your specific function you can also assist the algorithm by providing the derivative of the function:
def derivative(x, f, g, K):
return np.sum(-g*f * np.exp(-g*x), axis=0)
res = scipy.optimize.fsolve(func, fprime=derivative,
x0=1, args=(f[:, None], g[:, None], K))
You can vectorize the procedure in a sense that the function accepts N inputs (for example for each of the rows) and produces N outputs (again one for each row). Hence the inputs and outputs are independent of each other and the corresponding jacobian is a diagonal matrix. Here's some sample code:
import numpy as np
import scipy.optimize
np.random.seed(123)
image = np.random.uniform(size=(4000, 3000, 2))
f, g = image[:, :, 0], image[:, :, 1]
x_original = np.random.uniform(size=image.shape[0]) # Compute for each of the rows.
K = np.sum(f * np.exp(-g * x_original[:, None]), axis=1)
def func(x, f, g, K):
return np.sum(f * np.exp(-g*x[:, None]), axis=1) - K
def derivative(x, f, g, K):
return np.diag(np.sum(-g*f * np.exp(-g*x[:, None]), axis=1))
res = scipy.optimize.fsolve(func, fprime=derivative,
x0=0.5*np.ones(x_original.shape), args=(f, g, K))
assert np.allclose(res, x_original)