Double precision

I have a code and I don't understand it. I am developing an application whose accuracy is very important. but this is not important for .NET why? I dont know.

double value = 3.5;
MessageBox.Show((value + 1 * Math.Pow(10, -20)).ToString());

      

but the message box displays: 3.5 Please help me, thanks.

0


a source to share


5 answers


You can have precision, but it depends on what else you want to do. If you put the following in your console application:

double a = 1e-20;
Console.WriteLine(" a  = {0}", a);
Console.WriteLine("1+a = {0}", 1+a);

decimal b = 1e-20M;
Console.WriteLine(" b  = {0}", b);
Console.WriteLine("1+b = {0}", 1+b);

      

You'll get

 a  = 1E-20
1+a = 1
 b  = 0,00000000000000000001
1+b = 1,00000000000000000001

      



But note that the function Pow

, like almost everything in the Math class, only accepts doubles:

double Pow(double x, double y);

      

So you cannot take the sine of a decimal (otherwise, converting it to double)

Also see this question .

+1


a source


The precision Double

is 15 digits (17 digits inside). The value you calculate with Math.Pow

is correct, but when you add it to value

, it is too small to matter.

Edit: A
decimal number can handle this precision, but not calculate. If you want this precision, you need to do the calculation and then convert each value to Decimal

before adding them together:



double value = 3.5;
double small = Math.Pow(10, -20);

Decimal result = (Decimal)value + (Decimal)small;

MessageBox.Show(result.ToString());

      

+2


a source


If you are doing anything where precision is very important, you need to be aware of the floating point limitations. Good reference David Goldberg "What Every Computer Scientist Should Know About Floating Point Arithmetic" .

You may find that floating point does not give you enough precision and you need to work with decimal. They are, however, always much slower than floating point - a tradeoff between precision and speed.

+2


a source


Or use Decimal and not double.

+1


a source


Double precision means that it can contain 15-16 digits. 3.5 + 1e-20 = 21 digits. It cannot be represented in a double way. You can use another type such as decimal.

0


a source







All Articles