在给定的时间间隔内查找函数的根 [英] Find root of a function in a given interval

查看:110
本文介绍了在给定的时间间隔内查找函数的根的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to find the root of a function between by [0, pi/2], all algorithms in scipy have this condition : f(a) and f(b) must have opposite signs. In my case f(0)*f(pi/2) > 0 is there any solution, I precise I don't need solution outside [0, pi/2].

函数:

The function:

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)

Based on the comments and on @Mike Graham's answer, you can do something that will check where the change of signs are. Given y = dG(x, psi, gamma):

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

会返回您改变标志的位置。您可以通过一个迭代过程来查找根数,直到您需要的容错:

will return the positions where you had a change of sign. You can an iterative process to find the roots numerically up to the error tolerance that you need:

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])

这篇关于在给定的时间间隔内查找函数的根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆