I am trying to understand floating point arithmetic a little better. Can somebody please help me understand what is going on in the below example?
using System;
public class FloatingPointMadness
{
public static void Main(string[] args)
{
float f = 0.1f;
Console.WriteLine ($"Real value is: {f:F16}");
}
}
I am using .Net Framework 4.7.2. Since the decimal 0.1 cannot be represented exactly with floating point arithmetic, I would expect this to produce something like:
Real value is: 0.1000000014901161
But instead I get:
Real value is: 0.1000000000000000
Online example. If I change to using the .NET 9 compiler, I get what I expect. What is going on here?
I am trying to understand floating point arithmetic a little better. Can somebody please help me understand what is going on in the below example?
using System;
public class FloatingPointMadness
{
public static void Main(string[] args)
{
float f = 0.1f;
Console.WriteLine ($"Real value is: {f:F16}");
}
}
I am using .Net Framework 4.7.2. Since the decimal 0.1 cannot be represented exactly with floating point arithmetic, I would expect this to produce something like:
Real value is: 0.1000000014901161
But instead I get:
Real value is: 0.1000000000000000
Online example. If I change to using the .NET 9 compiler, I get what I expect. What is going on here?
Share Improve this question asked Feb 6 at 17:05 Peter FickPeter Fick 111 silver badge2 bronze badges New contributor Peter Fick is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct. 5 |1 Answer
Reset to default 2It seems there is a parser and formatter compliance between .Net framework and .NET (or .Net Core). .NET uses the standard IEEE 754-2008 it seems.
I've tried your code in .Net framework and .NET (from 3.1 onwards) it behaves as you mentioned.
The reason is already answered in the below stackoverflow question: Rounding issues .Net Core 3.1 vs. .Net Core 2.0/.Net Framework
Hope this helps!
0.1000000014901161
and0.1000000000000000
are not real values. They are merely the string representing data, not the data itself. The data is certain bitmap representing a floating-point object, and it is not a mathematical real number, this is a floating-point number. – Sergey A Kryukov Commented Feb 6 at 17:14I would expect
Why would you expect that? – mjwills Commented Feb 6 at 21:48