使用numpy中的python数值解算器求解方程

sta*_*uds 28 equation numpy solver python-2.7

我有一个等式,如下:

R - ((1.0 - np.exp(-tau))/(1.0 - np.exp(-a*tau))) = 0.

我想tau用numpy中可用的数值解算器在这个等式中求解.最好的方法是什么?

对于该公式的不同实现,该等式中的值Ra该等式的值不同,但是当要针对tau求解时,将其固定在特定值.

nib*_*bot 43

在传统的数学符号中,你的等式是

$$ R =\frac {1  -  e ^ { - \tau}} {1  -  e ^ { -  a\cdot\tau}} $$

SciPy fsolve函数搜索给定表达式等于零的点(表达式的"零"或"根").您需要提供fsolve一个"接近"您所需解决方案的初始猜测.找到这样一个初始猜测的好方法是只绘制表达式并寻找过零点.

#!/usr/bin/python

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

# Define the expression whose roots we want to find

a = 0.5
R = 1.6

func = lambda tau : R - ((1.0 - np.exp(-tau))/(1.0 - np.exp(-a*tau))) 

# Plot it

tau = np.linspace(-0.5, 1.5, 201)

plt.plot(tau, func(tau))
plt.xlabel("tau")
plt.ylabel("expression value")
plt.grid()
plt.show()

# Use the numerical solver to find the roots

tau_initial_guess = 0.5
tau_solution = fsolve(func, tau_initial_guess)

print "The solution is tau = %f" % tau_solution
print "at which the value of the expression is %f" % func(tau_solution)
Run Code Online (Sandbox Code Playgroud)


beh*_*uri 11

您可以将等式重写为

EQ

  • 对于整数a和非零,R您将a在复杂空间中获得解;
  • 有分析解决方案a=0,1,...4(见这里);

因此,一般来说,您可能有一个,多个或没有解决方案,其中一些或全部可能是复杂的值.您可以轻松地抛出scipy.root这个等式,但没有数值方法可以保证找到所有解.

要在复杂的空间中解决:

import numpy as np
from scipy.optimize import root

def poly(xs, R, a):
    x = complex(*xs)
    err = R * x - x + 1 - R
    return [err.real, err.imag]

root(poly, x0=[0, 0], args=(1.2, 6))
Run Code Online (Sandbox Code Playgroud)