Stock initial value is 1 Flow rate is 0.1 Stock1 initial value is 0.
When i run the simulation, i realized that the value of stock get lower than 0 (getting a negative value). How to stop the flow when the value of Stock reaches to zero.
A question that should have a very obvious answer, but no.
First and most important: there is no option that you can set to define 0 as the minimum value of the stock because the flow will continue wanting to take from the stock no matter what, so what you have to do is to change the flow when the stock is 0 (or near 0).
Remember System Dynamics is a continuous simulation technique and since it uses steps it's not perfect... So I will show you 2 possible tricks to do this
Trick 1: This trick will give you an inexact number close to zero, but it's always good enough: Ease, In flow, put the following formula:
stock-(getEngine().getNextStepTime()-time())*0.1<0 ? 0 : 0.1
getEngine().getNextStepTime() is the time in which the next calculation will occur, so getEngine().getNextStepTime()-time()
will tell you the time step for the next iteration (The numerical methods to calculate the steps used by anylogic change for each iteration, so you have to do this). I multiply the time step by 0.1 since that is the flow rate you have chosen. The flow rate is never 0.1, the real value is 0.1*(time Step)/(time Unit). In this case the time unit is 1 second, so I'm dividing by 1, so I don't need to put that division.
The formula finally states that if the next iteration will give you a negative stock, then make the flow rate equal to 0 instead of 0.1
Trick 2:
Use the following configuration:
flow will have flowrate
in the formula
flowRate variable is equal to 0.1
and the event is a conditional event with the following condition:
stock<=0
and the following action:
flowRate=0;
stock1=stock1+stock;
stock=0;
In this case, the stock will be negative for one time step (around 1-10 miliseconds).. and we set up the real values artificially.
(you can combine trick 1 and trick 2 if you want)