sungfive
sungfive

Reputation: 51

Update variable every time I run the function

As the title says, I want to update a specific variable of a function and use it as input of the same function. Trying to explain better:

double pi_control(double x, double integral_x, double dt) {
    integral_x = (x * dt) + integral_x;
    return integral_x;
}

x and dt are given variable (x = 3.0, dt = 0.01). integral_x (whose initial value is 0.0) after running pi_control is 0.03. I want to run pi_control one more time, how can I override integral_x initial value and use 0.03 instead?

EDIT:

Full pi_control function

double pi_control(double x, double &integral_x, double kp, double ki, double dt) {
    integral_x = (x * dt) + integral_x;
    double u = - kp * x - ki * integral_x;
    return u;

}

Upvotes: 0

Views: 549

Answers (3)

Daniel Langr
Daniel Langr

Reputation: 23497

I would prefer simply

integral_x = pi_control(x, integral_x, dt);

with

double pi_control(double x, double integral_x, double dt)
{
  return x * dt + integral_x;
}

There is no confusing mixing of pass-by-value and pass-by-reference parameters, and a caller can additionally decide whether they want to update integral_x or not.

I guess the performance would be the same, especially when the function can be inlined (a compiler can see it's definition during translation).

UPDATE

You changed the question considerably, but anyway, this solution is still possible:

std::pair<double, double> pi_control(double x, double integral_x, double kp, double ki, double dt)
{
  integral_x = (x * dt) + integral_x;
  double u = - kp * x - ki * integral_x;
  return {u, integral_x};
}

with

std::tie(u, integral_x) = pi_control(x, integral_x, kp, ki, dt);

Upvotes: 1

G.M.
G.M.

Reputation: 12879

Why not just return the new value of integral_x (note that as shown your function is declared to return a double but has no return statement -- that's undefined behaviour).

double pi_control (double x, double integral_x, double dt)
{
    integral_x = (x * dt) + integral_x;
    return integral_x;
}

Upvotes: 1

Botje
Botje

Reputation: 30817

Change the signature to take integral_x by reference:

double pi_control(double x, double &integral_x, double dt) { ... }

Now any changes made to the integral_x variable inside the function are reflected in the variable you pass in.

Upvotes: 5

Related Questions