Change logic from vector <float> to only float - Euler

63 views Asked by At

I have an implementation of Eulers formula for estimating a function. The type is array format is vector but because of a later code the arguments passed need to be normal float. Wondering how to restructure the code here. dydt takes existing formula

void euler(float y0, float a, int n, float dt, std::vector<float>& t, std::vector<float>& y) {
double y_init = y0;
double t_init = 0.0;

for (int i = 0; i <= n; i++) {

   t.push_back(t_init);
   y.push_back(y_init);



double y_p = dydt(y_init, a);

   y_init = y_init + dt * y_p;

   t_init = t_init + dt;


    }

}

It needs to however be something of type:

void euler(float y0, float a, int n, float dt, float t[n], float y[n])

I’m currently stuck with the logic in the for loop with regular arrays. Vectors just make more sense in this case, but because of the function used later, t and y need to be regular float.

1

There are 1 answers

3
Sam Varshavchik On BEST ANSWER

As you know, one of the things that std::vector does is keep track of how many values are in the vector. This is one of the things that a std::vector does for you. This is one of std::vector's deeply-held secrets, but it will happily divulge it to you, simply by asking by the virtue of calling its size(). push_back() automatically increments it for you, and other vector operations also update it accordingly.

By getting rid of vectors and switching to plain arrays this becomes your job.

You will need to declare two variables and initialize them to zero. Perhaps call them

size_t t_size=0, y_size=0;

One for each one of your former vectors. And then simply replace all usage of vectors with your arrays, and implementing the vector equivalent logic accordingly. That's it. Mission accomplished. Call it a day. For example:

t.push_back(t_init);

Now becomes:

t[t_size++]=t_init;

And so on.

Depending on the actual details, this is sufficient to declare and initialize the size values in this function, or pass them in, already initialized, by reference as additional parameters. It is unclear whether this is or is not the case, but this is something that you should be able to figure out yourself.

P.S. One of the things you will also need to figure out is why your program will have mysterious crashes. This is because

for (int i = 0; i <= n; i++)

will iterate n+1 times, instead of n times, and generate n+1 values (you can pick n of 1, here, then see what happens with paper and pencil). Putting n+1 values into an array with only n values will always end in tears.