- Home /
Calculation error when multiplying a float
I am making a bank system and I found some issues about the interest calculation. If you try **Debug.Log(100000 1.05f - 100000);*, you will get a result 4999.992. Does everyone has idea how to solve this error?
Below are some of the wrong output:
Debug.Log(100000 * 1.05f - 100000); //Output: 4999.992
Debug.Log(100000 * 1.06f - 100000); //Output: 5999.992
Debug.Log(100000 * 1.07f - 100000); //Output: 7000.008
Answer by SamKim99 · Jun 21, 2020 at 03:01 PM
I think it is caused by Resolution of Float.
In computer, we should represent the numbers with bits, 0 and 1. So, the values we can get after some calculations might be an approximated values.
There can be countless ways to represent floating points. In fact, you can make your own method. Therefore, we need a standard method. Most of programming languages use IEEE Standard for Floating-Point Arithmetic (IEEE 754) to represent it. It represent the floating points with 1 sign bit, 8 exponent bits, 23 fractions.
So... it is long long way to get that point, you can use more precise data type, which might be decimal or double!
Double
class Program
{
static void Main(string[] args)
{
Console.WriteLine(100000 * (double)1.05 - 100000);
}
}
Result
Decimal
class Program
{
static void Main(string[] args)
{
Console.WriteLine(100000 * (decimal)1.05 - 100000);
}
}
Result
Right. For everyone wondering why this happens I can recommend watching this Computerphile video on floating point numbers. I've also made this table for 32 bit floating point numbers to see what the smallest representable change would be at a certain interval.
Thank you very much both! Did learn something today!
Your answer
Follow this Question
Related Questions
Are OnGUI calculations cached? 1 Answer
How to save run-time variables to dictionary? 1 Answer
How can I dynamically change the percentage value so that it always adds up to 100%? 1 Answer
Multiplying quaternions and Multiplying quaternion with Vector3 3 Answers
What do I add to this script, so if you clicked the button ex. 30 times, a gui.box will appear? 1 Answer