python - Find root of a function in a given interval -


i trying find root of function between [0, pi/2], algorithms in scipy have condition : f(a) , f(b) must have opposite signs. in case f(0)*f(pi/2) > 0 there solution, precise 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) 

based on comments , on @mike graham's answer, can check change of signs are. given y = dg(x, psi, gamma):

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

will return positions had change of sign. can iterative process find roots numerically error tolerance need:

import numpy np 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 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) inf, sup in inf_sup]) 

Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -