Just started learning C#. I plan to use it for heavy math simulations, including numerical solving. The problem is I get precision loss when adding and subtracting double
's, as well as when comparing. Code and what it returns (in comments) is below:
namespace ex3
{
class Program
{
static void Main(string[] args)
{
double x = 1e-20, foo = 4.0;
Console.WriteLine((x + foo)); // prints 4
Console.WriteLine((x - foo)); // prints -4
Console.WriteLine((x + foo)==foo); // prints True BUT THIS IS FALSE!!!
}
}
}
Would appreciate any help and clarifications!
What puzzles me is that (x + foo)==foo
returns True
.
The most commonly used double precision format stores the number with 53 bits of precision. This gives approximately 16 decimal digits of precision. You may find that long double gives more precision, but there is no guarantee that that is any larger than double .
Master C and Embedded C Programming- Learn as you go To compare two floating point or double values, we have to consider the precision in to the comparison. For example, if two numbers are 3.1428 and 3.1415, then they are same up to the precision 0.01, but after that, like 0.001 they are not same.
double has 2x more precision than float. float is a 32-bit IEEE 754 single precision Floating Point Number – 1 bit for the sign, 8 bits for the exponent, and 23* for the value. float has 7 decimal digits of precision.
Since the precision of float is less than the double therefore after a certain point(23 in float and 52 in double) it would truncate the result. Hence, after promotion of float into double(at the time of comparison) compiler will pad the remaining bits with zeroes.
Take a look at the MSDN reference for double
: https://msdn.microsoft.com/en-AU/library/678hzkk9.aspx
It states that a double
has a precision of 15 to 16 digits.
But the difference, in terms of digits, between 1e-20
and 4.0
is 20 digits. The mere act of trying to add or subtract 1e-20
to or from 4.0
simply means that the 1e-20
is lost because it cannot fit within the 15 to 16 digits of precision.
So, as far as double
is concerned, 4.0 + 1e-20 == 4.0
and 4.0 - 1e-20 == 4.0
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With