Skip to main content
 首页 » 编程设计

python之在给定区间内求函数的根

2024年11月01日8傻小

我试图在 [0, pi/2] 之间找到一个函数的根,scipy 中的所有算法都有这个条件:f(a) 和f(b) 必须有相反的符号。 在我的例子中,f(0)*f(pi/2) > 0 是否有任何解决方案,我确切地说我不需要 [0, pi/2] 之外的解决方案>.

函数:

def dG(thetaf,psi,gamma) : 
   return 0.35*((cos(psi))**2)*(2*sin(3*thetaf/2+2*gamma)+(1+4*sin(gamma)**2)*sin(thetaf/2)-‌​sin(3*thetaf/2))+(sin(psi)**2)*sin(thetaf/2) 

请您参考如下方法:

根据评论和@Mike Graham 的回答,您可以做一些事情来检查符号的变化位置。给定 y = dG(x, psi, gamma):

x[y[:-1]*y[1:] < 0] 

将返回您更改符号的位置。您可以通过迭代过程以数字方式找到根,直到达到您需要的容错度:

import numpy as np 
from numpy import sin, cos 
 
def find_roots(f, a, b, args=[], errTOL=1e-6): 
    err = 1.e6 
    x = np.linspace(a, b, 100) 
    while True: 
        y = f(x, *args) 
        pos = y[:-1]*y[1:] < 0 
        if not np.any(pos): 
            print('No roots in this interval') 
            return roots 
        err = np.abs(y[pos]).max() 
        if err <= errTOL: 
            roots = 0.5*x[:-1][pos] + 0.5*x[1:][pos] 
            return roots 
        inf_sup = zip(x[:-1][pos], x[1:][pos]) 
        x = np.hstack([np.linspace(inf, sup, 10) for inf, sup in inf_sup])