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.
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 astd::vector
does for you. This is one ofstd::vector
's deeply-held secrets, but it will happily divulge it to you, simply by asking by the virtue of calling itssize()
.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:
Now becomes:
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
will iterate
n+1
times, instead ofn
times, and generaten+1
values (you can pickn
of1
, here, then see what happens with paper and pencil). Puttingn+1
values into an array with onlyn
values will always end in tears.