Python Forum
Finding all roots of a function - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Finding all roots of a function (/thread-33326.html)



Finding all roots of a function - thonpy - Apr-15-2021

I have written the following snippet of code:

import numpy as np
import math as m
import cmath as cm
from scipy.optimize import minimize, root_scalar

def omega(args,x):
    
    N,p=args
    w=new_target(N,p) #an array
    
    old_spectrum=np.zeros(N)
    for i in range(N-1):
        old_spectrum[i]=N
    old_spectrum[N-1]=0
    
    sigma=0
    for i in range(N):
        sigma+=(w[i]*w[i])/(old_spectrum[i]-x)
    return 1+sigma

def omega_prime(args,x):
    
    N,p=args
    w=new_target(N,p)
    
    old_spectrum=np.zeros(N)
    for i in range(N-1):
        old_spectrum[i]=N
    old_spectrum[N-1]=0
    
    sigma=0
    for i in range(N):
        sigma+=(w[i]*w[i])/(old_spectrum[i]-x)*(old_spectrum[i]-x)
    return sigma

def new_spectrum(N,p,x0):

    roots=root_scalar(omega,fprime=omega_prime,args=(N,p),method='newton',x0=x0)
    return roots
that is meant to find the roots of a function omega(x) (there should be exactly N of them). However, calling for example

new_spectrum(3,1,0.1)
returns the error
Error:
TypeError: omega() takes 2 positional arguments but 3 were given
which I do not know how to fix. Any tips? Huh


RE: Finding all roots of a function - bowlofred - Apr-15-2021

I believe the solver function always passes the variable to be solved first and then any additional args. So instead of calling your function as omega((N, p), x), it is calling it as omega(x, N, p). 3 variables instead of 2, and the to-be-solved variable in the first position.


RE: Finding all roots of a function - thonpy - Apr-15-2021

(Apr-15-2021, 08:33 PM)bowlofred Wrote: I believe the solver function always passes the variable to be solved first and then any additional args. So instead of calling your function as omega((N, p), x), it is calling it as omega(x, N, p). 3 variables instead of 2, and the to-be-solved variable in the first position.

Thank you, I fixed it Smile btw, do you have any idea how to extend the solver so that it doesn't stop once a root is found? Since I know there are N of them, ideally it would not stop until all N are found.


RE: Finding all roots of a function - bowlofred - Apr-16-2021

Call the solver from another initial location or over a different interval. It only finds a "local" root. It won't abandon one convergent root to see if it can find another farther away. https://docs.scipy.org/doc/scipy/reference/optimize.html#root-finding