Finding the solution of a summation of exponentials

一曲冷凌霜 提交于 2019-12-11 07:21:33

问题


I'm trying to solve numerically this equation in Python (numpy/scipy, everything is available)

In this formula K is a constant, f and g are two terms those depends on the E counter (this is a discrete representation of an integral) where x is the variable I'm looking for.

As an example, with E being 3 terms that'd be:

also f(E) and g(E) are known.

I read about using "fsolve" from numpy, although I can't understand how to automatically generate a function that's a summation of terms. I may do it manually but being 50 terms that'd take a while, also I'd love to learn something new.


回答1:


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))

Finding multiple roots

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)


来源:https://stackoverflow.com/questions/54258368/finding-the-solution-of-a-summation-of-exponentials

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!