Problem: Double minus another double is returning unaccurate results.
Usual solution: Use big decimal to perform calculations.
I can’t use this because it’s in the middle of a game loop, can only set big decimal with a value when it’s created with new, within a game loop I’m running out of memory.
What solution?
Here’s the code:
public void UpdateStatsBar(double WorldPopulation, double WorldDead)
{
Number = mOriginalPopulation - WorldPopulation;
}
The kind of numbers I’m using go into the billions and go tens of digits deep (averages for stats) example: 1432,323,234.234215232425322342
Assuming you can’t have a decimal number of people live or dead, I would use
long.Can you provide an example of the numbers you are using which are not producing accurate results?
BTW: If you use whole numbers less than nine thousand trillion, even
doublewill produce accurate results.BTW2: If you create
new BigDecimallike mad but don’t retain them you will hurt performance but you won’t run out of memory. If you are running out of memory its not due to use BigDecimal. I suggest you use a memory profiler to find the true cause of the problem.An example
prints number counting with BigDecimal, long and double. The format for double is different but the value is the same.
Even with
-mx2mlimiting the heap to 2 MB it doesn’t run out of memory.