Search code examples
pythonscipynonlinear-functions

Solving an equation with scipy's fsolve


I'm trying to solve the equation f(x) = x-sin(x) -n*t -m0

In this equation, n and m0 are attributes, defined in my class. Further, t is a constant integer in the equation, but it has to change each time.

I've solved the equation so i get a 'new equation'. I've imported scipy.optimize

def f(x, self):
    return (x - math.sin(x) -self.M0 - self.n*t)

def test(self,t):
    return fsolve(self.f, 1, args=(t))

Any corrections and suggestions to make it work?


Solution

  • I can see at least two problems: you've mixed up the order of arguments to f, and you're not giving f access to t. Something like this should work:

    import math
    from scipy.optimize import fsolve
    
    class Fred(object):
        M0 = 5.0
        n = 5
    
        def f(self, x, t):
            return (x - math.sin(x) -self.M0 - self.n*t)
    
        def test(self, t):
            return fsolve(self.f, 1, args=(t))
    

    [note that I was lazy and made M0 and n class members]

    which gives:

    >>> fred = Fred()
    >>> fred.test(10)
    array([ 54.25204733])
    >>> import numpy
    >>> [fred.f(x, 10) for x in numpy.linspace(54, 55, 10)]
    [-0.44121095114838482, -0.24158955381855662, -0.049951288133726734,
     0.13271070588400136, 0.30551399241764443, 0.46769772292130796, 
     0.61863201965219616, 0.75782574394219182, 0.88493255340251409, 
     0.99975517335862207]