# Numerical analysis

`class DumbIntegrator:    """ The dumbest possible numerical integrator """    def __init__(self, m0 = 0):        self.m0 = m0        self.y0 = None    def calculate(self, dt, y):        y0 = self.y0 if self.y0 else y        new_area = dt*((y0 + y)/2)        total_area = self.m0 + new_area        # update state        self.y0 = y        self.m0 = total_area        return total_areaclass DumbDifferentiator:    """ The dumbest possible numerical derivator """    def __init__(self):        self.y0 = None    def calculate(self, dt, y):        y0 = self.y0 if self.y0 else y        rate = (y - y0)/dt        # update state        self.y0 = y        return rate`

# PID regulator

`from .base import BaseModelfrom ..utils.numerical_analysis import DumbDifferentiator, DumbIntegratorclass PID(BaseModel):    """ A class used to model a dumb PID regulator """    def __init__(self, dt, Kp, Ti, Td, error = 0):        # constants        self.dt = dt        self.Kp = [Kp]        self.Ti = [Ti]        self.Td = [Td]        # state variable        self.error = [error]        # inputs        self.PV = [None]        self.SP = [None]        # other        self.I = DumbIntegrator()        self.D = DumbDifferentiator()        self.PG = [0]        self.IG = [0]        self.DG = [0]        # output        self.MV = [0]    def calculate(self, SP, PV, FWD):        """ Calculates the next value and adds it to the memory """        Kp = self.Kp[-1]        Ti = self.Ti[-1]        Td = self.Td[-1]        # error        error = SP - PV        # gains        PG = Kp*error        IG = self.I.calculate(self.dt, error)*Kp/Ti        DG = self.D.calculate(self.dt, error)*Kp*Td        # output        MV = PG + IG + DG + FWD        # update attributes        self.update_attributes(**{            "error": error,            "PG": PG,            "IG": IG,            "DG": DG,            "MV": MV        })        return MV`

# What’s next

--

--

--

## More from Fábio Molinar

Back-End Web developer, Industrial Automation Engineer, Husband & Father.

Love podcasts or audiobooks? Learn on the go with our new app.

## Fábio Molinar

Back-End Web developer, Industrial Automation Engineer, Husband & Father.