I am modelling a system which contains a specific amount of energy between 0 and 1. This is stored in a double called storedEnergy
.
storedEnergy
should count from 0.0 to 1.0 over 21 minutes, but instead counts to 1.0000000000000004
Every iteration storedEnergy
increases by onStoredEnergyIncreasePerMinute
which is calculated like this:
onSlackMinutesIncreasePerMinute = (double) time1to0Energy / (double) time0to1Energy;
onStoredEnergyIncreasePerMinute = 1d / (double) time0to1Energy;
offSlackMinutesDecreasePerMinute = 1d;
offStoredEnergyDecreasePerMinute = 1d / (double) time1to0Energy;
Here is the stored energy increasing:
while (storedEnergy < target) {
storedEnergy += onStoredEnergyIncreasePerMinute;
}
A similar thing happens with slack minutes: there are 24.999999999999993 at 1.0 energy, when there should be 25 at 1.0
It may be relevant to mention that I will then count back down to 0 using offStoredEnergyDecreasePerMinute
for 25 minutes
I don't know why this is happening (though I presume it's something to do with doubles not being able to represent fractions properly), or what I should do to resolve it. Do I have to use some sort of fraction class?