Home > database >  How can I choose function with class fuction?
How can I choose function with class fuction?

Time:11-23

class ODEsolver():
    def __init__(self):
        self.init=self
  def Euler(self, fcn, x0, y0, xend, h):
    estimate=[y0]
    z=y0
    b=0
    t=x0   
    while(t<xend):
      slope1=fnc(bisection(t,301,1200,10**-4))
      y=z slope1*h/8
      t =h
      z=y
      estimate.append(y)
    return estimate

    def Heun(self, fcn, x0, y0, xend, h):
    def RungeKutta(self,fcn,x0,y0,xend,h):

    def solve(self,which, fcn, x0, y0, xend, h):
        if which==0:
            self.Euler(fcn,x0,y0,xend,h)
        elif which==1:
            self.Heun(fcn,x0,y0,xend,h)
        else:
            self.RungeKutta(fcn,x0,y0,xend,h)

I'm trying to choose function and get return as list([]). But e=r.solve(0,diff,0,1200,6000,30) returns NONE. How can I get right return from this code?

*I simplified other functions such as Heun,RungeKutta because I noticed the problem is in r.solve() because simply calling function like r.Euler worked well.

CodePudding user response:

You can use getattr.

Like this:

def solve(self, which, fcn, x0, y0, xend, h):
    fn = getattr(self, which)
    return fn(fcn, x0, y0, xend, h)

... and then pass the desired method name as the argument:

solver = ODEsolver()
return solver.solve('Euler', 42, 42, 42, 42, 100500)

CodePudding user response:

You aren't returning. You just invoked the Euler, Heun and RungeKutta functions. You have to return the answers, try to store the answer in a variable and return it on the end of the function, like this:

def solve(self,which, fcn, x0, y0, xend, h):
  if which==0:
    answer = self.Euler(fcn,x0,y0,xend,h)
  elif which==1:
    answer = self.Heun(fcn,x0,y0,xend,h)
  else:
    answer = self.RungeKutta(fcn,x0,y0,xend,h)
  return answer
  • Related