Math error
Description
.1025 * 540 should equal 55.35, but instead it equals 55.3499999...
// Assert.AreEqual failed. Expected:<55.35>. Actual:<55.349999999999994>. Assert.AreEqual(55.35, .1025 * 540);
Reproduction Steps
Create a new unit test project in .Net 6.0.
Add the statement above to the generated code initial test case.
Run the test.
Expected behavior
.1025 * 540 should equal 55.35.
Actual behavior
.1025 * 540 equals 55.349999999999994
Regression?
In .Net 4.8, the test failed but the actual numbers were the same, probably just a type casting problem. So in .Net 4.8, .1025 * 540 equals 55.35.
Known Workarounds
I found this error by trouble shooting a larger calculation. The solution was simply to round the calculation twice. In this case, you could round the calculation once.
This passes:
Assert.AreEqual(55.35, Math.Round(.1025 * 540, 2));
Configuration
.Net versions: .Net 5.0, .Net 6.0.
OS, architecture: Windows 10 Pro x64, Windows Server 2016 Datacenter x64
This problem first occurred on the server (Windows Server 2016), and I was able to duplicate it on my development machine (Windows 10 Pro).
Other information
No response
I couldn't figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label.
Due to the limited precision of floating-point numbers and rounding errors, $0.125 \times 540$ and $55.35$ have a different binary representation. You can see it if you run the following code:
var x1 = 0.125 * 540;
var x2 = 55.35;
Console.WriteLine(BitConverter.DoubleToUInt64Bits(x1)); // 4634450307168862208
Console.WriteLine(BitConverter.DoubleToUInt64Bits(x2)); // 4632986637289966797
Because they are different numbers under the hood, they are not considered equal by the == operator. This behavior is by design. Closing.
Hi Teo,
Please understand that this issue creates real world calculation errors where there should be none. So while it might be by design that the binary representation is different and floating point numbers don't have sufficient precision, that design results in real problems with end-user code. .1025 * 540 equals 55.35 under any real world scenario. How many decimal points or what type the final number is cast into doesn't matter. In other words, the problem isn't that the .1025 * 540 is not considered equal by the == operator or that the test case fails as a result. The real problem is that under .Net 6, .1025 * 540 equals 55.349999999999994 when it should equal 55.35000000000.
In .Net 4.8, the test failed also, but the numbers were the same: 55.35 and 55.35, probably because they were different types. In .Net 4.8, the calculation of, in my case, sales taxes was correct. In .Net 5.0/6.0, the calculation of sales taxes is off. That is a problem that should not occur.
Yes, I can fix this particular manifestation of this issue through rounding (in my case, twice), but how many other problems are there which we are missing because of it?
I urge you to look at the implementation of the .Net 4.8 calculation to see if it can be used in .Net 6.0+ so that the actual numbers match.
Thank you.
If you are dealing with money you should use the decimal type. It will not exhibit such issues.
The vast majority of programming languages and computer systems exhibit this same behavior because it is part of IEEE754, and .NET follows along. It's a practical tradeoff between precision and performance/speed and can't just be "fixed".
Yes, I can fix this particular manifestation of this issue through rounding (in my case, twice), but how many other problems are there which we are missing because of it?
I urge you to look at the implementation of the .Net 4.8 calculation to see if it can be used in .Net 6.0+ so that the actual numbers match.
@JDGoldman the .NET Framework implementation has many examples of such results, just different ones. It is fundamentally not possible to “fix” floating point math in the way you would like. At least .NET is now IEEE754 compliant so it will give the same results as other standards compliant implementations.
As much as it appears that we introduced a bug here, the bug is in your code. If you are dealing with money you should not use floating point math. Either use integers (eg to count cents) or use decimal.
This describes the problem: https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency#3730040
As teo indicated, this is by design and is how floating-point operations work in every major programming language in the world. This is because most programming languages (and hardware) implement the IEEE 754 specification and expose the binary floating-point types.
The IEEE 754 binary floating-point types are represented using a base-2 numbering system. This means that it can exactly represent multiples of powers of 2. This means that it cannot exactly represent values that are not a multiple of a power of two, such as 0.1.
- Since computers are
binarybased (evenInt32is binary based, hence its MaxValue being(2^31) - 1) this allowsfloatanddoubleto be incredibly fast (sometimes even faster than integer arithmetic).
This is the same as a base-10 numbering system only being able to represent multiples of powers of 10. This means that it cannot represent something like 1 / 3 exactly, because it is an infinitely repeating value.
decimalbased number support exists in .NET via theSystem.Decimaltype and thedecimalkeyword in C#. It is, however, much slower in comparison since it is dealing with data in a "non-native" format compared to the computer.
Whenever you type a literal, such as 0.1025, the language must take this "decimal-based string" and convert it to the nearest representable binary-based float. This results in inaccuracies that creep in.
For example:
0.1025is actually0.10249999999999999389377336456163902767002582550048828125- it is
2^-56 * 7_385_903_388_887_613
- it is
540is exactly540- it is
2^-43 * 4_749_890_231_992_320
- it is
55.35is actually55.35000000000000142108547152020037174224853515625- it is
2^-47 * 7_789_819_980_467_405
- it is
(0.1025 * 540)is actually55.349999999999994315658113919198513031005859375- it is
2^-47 * 7_789_819_980_467_404(note how it is 1 less)
- it is
The last result is because while 0.1025 * 540 is 55.35 and would round to the nearest representable value as 55.35000000000000142108547152020037174224853515625; the actual values are 0.10249999999999999389377336456163902767002582550048828125 * 540 which computes 55.349999999999996702637616863285074941813945770263671875, which is closer to 55.349999999999994315658113919198513031005859375
In .Net 4.8, the test failed also, but the numbers were the same: 55.35 and 55.35
This is because .NET Framework had a different formatting algorithm and incorrectly displayed 55.349999999999994315658113919198513031005859375 as 55.35. This was a bug and was fixed in .NET Core 3.1 (https://devblogs.microsoft.com/dotnet/floating-point-parsing-and-formatting-improvements-in-net-core-3-0/).
The actual result computed between .NET Framework and .NET [Core] is identical, both result in a double with the bitwise value of 0x404B_ACCC_CCCC_CCCC
If you are doing something, like working with currency, where the results must be "exact", you should use decimal. It is slower, but computes results closer to how most users expect math to work.
Noting, however, that computers in general don't exactly follow normal math. In normal math, you can easily represent repeating fractions or irrational values using symbols or other data. For a computer to represent such information you need very complex (and very slow) data structures.
Computers have "finite" space and so even ((1m / 3m) * 3m) != 1m. Because decimal cannot exactly represent thirds and so you end up with 0.9999999999999999999999999999m instead. You must account for some level of rounding error no matter what you do with computers.
Thank you for your feedback and explanation. I will try to use the decimal type or rounding to "fix" this issue going forward.