Saybia
Saybia

Reputation: 3

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?

Upvotes: 0

Views: 15713

Answers (3)

DSM
DSM

Reputation: 353569

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]

Upvotes: 4

NPE
NPE

Reputation: 500923

You need to define f() like so:

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

In other words:

  1. self comes first (it always does);
  2. then comes the current value of x;
  3. then come the arguments you supply to fsolve().

Upvotes: 0

duffymo
duffymo

Reputation: 309008

You're using a root finding algorithm of some kind. There are several in common use, so it'd be helpful to know which one.

You need to know three things:

  1. The algorithm you're using
  2. The equation you're finding the roots for
  3. The initial guess and range over which you're looking

You need to know that some combinations may not have any roots.

Visualizing the functions of interest can be helpful. You have two: a linear function and a sinusiod. If you were to plot the two, which sets of constants would give you intersections? The intersection is the root you're looking for.

Upvotes: 0

Related Questions