Hi there, I'm writing a program that should calculate the energy of a system. There are three subroutines written, which one is used depends on a random number that is generated. Basically I want the energy of the system to be updated each time one of these subroutines is carried out. What I'm having trouble with is figuring out a way that the variable "energy_box" is updated and printed on screen. Here is one of these subroutines:
So the general idea is that this "energy_box" is updated each time one of these subroutines runs. I have "return energy_box" in each of them. At the moment when I print to screen I simply get 0's. I know the way I'm attempting to do it at the moment is seriously flawed so any suggestions of a better way to do it would be much appreciated.
Everything here works apart from energy_box (which returns only 0's). I've checked what values of energy_box are being produced in the subroutines and they seem fine...
I've checked what values of energy_box are being produced in the subroutines and they seem fine...
This seem to imply that you work out the value of energy_box in several functions - is it being returned by these functions or otherwise changed via a reference or pointer?
The variable energy_box is local to the function posted above, so it is not the same as energy_box declared elsewhere, because it goes out of scope at the end of the function.
I think the problem is that I want the value of energy_box to be updated each time one of the subroutines runs, but I have only declared it locally in each subroutine.
Would a better way to do it be to declare three separate variables (e.g energy_box1, energy_box2 etc) - so one for each subroutine, return them, and then sum them outside of the functions?
You could declare energy_box in main(), then send it to the functions as a reference. That way when you modify the value of it in the function, you are changing it in main as well, because it is actually the same variable. Technically the variable occupies the same memory address. That is the whole idea of references and pointers. References are safer than pointers, so are preferred.
Read up about it all in the articles & reference section on this page at the top left.
If you have several of these and want to sum them, just return them from the functions as you are now, but sum them using a variable in main.
1 2
SumEnergyBox += MCmove() // I didn't show the args
You could store the separate energies in a container like vector or whatever one suits best: stack, list. map, set etc. Then you have potential do do other calcs if needed.