如何找到函数$ f(\ beta)= \ gamma + [1-e ^ {-j \ beta}] / [1-e ^ {(-j + 1)\ beta}] $的根,使用python

时间:2018-07-19 11:48:37

标签: python python-3.x computation

我有以下方程式,无法为$\beta$找到闭式解,因此我想通过计算来求解$\beta$

$$\gamma = \frac{1-e^{-jT\beta}}{1-e^{-(j+1)T\beta}}$$

enter image description here

变量$\gamma$, $j$$T$是已知的。不幸的是,我对等式的根括号不了解。

python中是否有一种算法可以在不知道方括号的情况下求解根?

1 个答案:

答案 0 :(得分:1)

Scipy提供了几种用于根查找算法的选项:https://docs.scipy.org/doc/scipy-0.13.0/reference/optimize.html#root-finding

这些算法倾向于想要可能解的边界或导数。在这种情况下,边界似乎不那么麻烦:)

编辑:重新阅读您的问题后,听起来好像您没有上限和下限的估算值。在这种情况下,我建议使用牛顿方法(scipy.optim.newton,在这种情况下,您必须(手动或使用sympy)来计算导数。

import matplotlib
matplotlib.use('Agg')

import numpy as np
from scipy.optimize import brentq
import matplotlib.pyplot as plt

def gamma_func(beta, j, T):
    return (1-np.exp(-j*T*beta)) / (1-np.exp(-(j+1)*T*beta))

# Subtract gamma from both sides so that we have f(beta,...) = 0.
# Also, set beta, the independent variable, to the first
# argument for compatibility with solver
def f(beta, gamma, j, T):
    return gamma_func(beta, j, T) - gamma


# Parameters
gamma = 0.5
j = 2.3
T = 1.5

# Lower and upper bounds for solution
beta_low = -3
beta_high = 3

# Error tolerance for solution
tol = 1e-4

# True solution
beta_star = brentq(f, beta_low, beta_high, args=(gamma, j, T), xtol=tol)


# Plot the solution
plt.figure()
plt.clf()
beta_arr = np.linspace(-10, 10, 1001)
gamma_arr = gamma_func(beta_arr, j, T)
plt.plot(beta_arr, gamma_arr)
plt.plot(beta_star, gamma_func(beta_star, j, T), 'o')
plt.savefig('gamma_plot.png')

# Print the solution
print("beta_star = {:.3f}".format(beta_star))
print("gamma(beta_star) = {:.3f}".format(gamma_func(beta_star, j, T)))

beta_gamma_plot

beta_star = -0.357
gamma(beta_star) = 0.500

请参阅其他求解器的文档,包括多维求解器。

祝你好运!

橄榄