首页 > 解决方案 > 如何找到函数 $f(\beta) = \gamma + [1-e^{-j\beta}]/[1-e^{(-j+1)\beta}]$ 的根,使用蟒蛇

问题描述

我有以下等式,我找不到 的封闭形式解决方案$\beta$,因此我想通过计算求解$\beta$

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

在此处输入图像描述

变量$\gamma$, $j$并且$T$是已知的。不幸的是,我不知道方程根的括号。

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

标签: pythonpython-3.xcomputation

解决方案


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

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

祝你好运!

奥利弗


推荐阅读