Python Forum
Finding all roots of a function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Finding all roots of a function
#1
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
Reply
#2
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.
Reply
#3
(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.
Reply
#4
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/referen...ot-finding
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Finding global extrema of oscillating function JoeRogan 0 1,617 Dec-22-2020, 01:49 AM
Last Post: JoeRogan
  pip unistall in alternate roots confminn 0 1,421 Aug-21-2020, 08:03 PM
Last Post: confminn
  Square and Cube roots. jarrod0987 2 5,339 Apr-13-2018, 09:30 PM
Last Post: casevh

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020