python - 如何找到函数 $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中是否有一种算法可以在不知道括号的情况下求解根?
解决方案
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_star = -0.357
gamma(beta_star) = 0.500
请参阅其他求解器的文档,包括多维求解器。
祝你好运!
奥利弗
推荐阅读
- c# - 如何在 C# 中的索引器参数上设置 convertHighWaterMarkToRowVersion?
- kotlin - 为什么要为 ApplicationContext 对象添加注解 @ApplicationContext?
- here-api - 这里批量地理编码 API 停止工作 - HTTP 错误 500
- python - Scrapy Crawler:从页面中抓取列表
- javascript - cubiq - IScroll.js | 我应该在哪个方法生命周期中将自定义事件放入 React JS
- google-play - 我们如何在 Google Play 商店中禁用便利店付款?
- r - 一种计算有效的方法来查找每个 Type 2 行上方和下方的 Type 1 行的 ID?
- javascript - 你可以使用 backdraftjs watchable 让组件完全重新渲染吗?
- verilog - Verilog 给出 x 输出
- qt - 如何从 QListWidgetItem 获取按钮事件