C - Double Accuracy Summation

I have a problem with double format precision .


Example example:

double K=0, L=0, M=0;
scanf("%lf %lf %lf", &K, &L, &M);
if((K+L) <= M) printf("Incorrect input");
else printf("Right, K=%f, L=%f, M=%f", K, L, M);

My test input:

K = 0.1, L = 0.2, M = 0.3 → Condition, but goes into the 'else' operator .


How can I fix this difference? Is there any other summation method?

-2
source share
3 answers

Double Precision IEEE 754 (, Intel ) 0.1 + 0.2 == 0.30000000000000004:-) 0.30000000000000004 != 0.3 ( , double s, 0.1, 0.2 0.3 "" . , , , 0,1, 0,2 0,3)

, : http://pages.cs.wisc.edu/~rkennedy/exact-float

, , . Delphi, double Single Delphi , , C Intel ( double float C)

, http://ideone.com/WEL7h

#include <stdio.h>

int main()
{
    double d1 = (0.1 + 0.2);
    double d2 = 0.3;

    printf("%.20e\n%.20e", d1, d2);

    return 0;
}

:
3.00000000000000044409e-01
2.99999999999999988898e-01

(, . 0.1 + 0.2 0,3)

+5

, . :

int i = 1; // this is and always will be 1
float j = 0.03 // this gets stored at least on my machine as something like 0.029999999

? , 0,1 0,2? ! , , , , .

. - :

float a = 0.3f;
float b = 0.301f;
float threshold = 1e-6;

if( abs(a-b) < threshold )
  return true;
else
  return false;
+1

There are infinitely many real numbers between any two different real numbers. If we could represent each of them, we would need infinite memory. Since we only have finite memory, floating point numbers need only be stored with finite precision. Up to this final accuracy, it might be false that 0.1 + 0.2 <0.3.

Now you really need to read that on the other end of the excellent link provided by Paul R.

0
source

All Articles