3

Possible Duplicates:
Floating point inaccuracy examples
Is JavaScript's Math broken?

I need to convert some data from txt file into double value and I'm using this function for this : atof . The problem is that the value which must be convert is 5.550000 and the atof function return 5.5499999999999998 and this is a problem because I must calculate the GPA with this number and the reault is not precise. This is the function which read the data from the txt file:

void readNext(FILE* file,Lab* lab)
{
    char line[100];
getline(file,line,100);
if (strcmp(line,"") == 0)
{
    lab->is_null = 1;
    return;
}
strcpy(lab->date,line);
getline(file,line,100);
lab->presence = atoi(line);
getline(file,line,100);
strcpy(lab->num_work,line);
getline(file,line,100);
lab->mark_work = atof(line);
getline(file,line,100);
lab->test_work = atof(line);
getline(file,line,100);
lab->current = atof(line);
getline(file,line,100);
lab->status_work = atoi(line);
getline(file,line,100);
}
Community
  • 1
  • 1
Jordan Borisov
  • 1,603
  • 6
  • 34
  • 69
  • 5
    [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html) – pmg May 31 '11 at 20:57

3 Answers3

3

See this StackOverflow article.

Floats will have issues representing exact values as you want without some additional work. You'll face two issues (described in the linked post) - actual rounding and formatting.

Community
  • 1
  • 1
DaveE
  • 3,579
  • 28
  • 31
2

Short answer: atof("5.55") will never return an precise (meaning exact) representation of this decimal fraction, because there exists no exact binary floating point representation of this number, it's an infinite binary fraction.

For a long answer see http://www.math.umd.edu/~jkolesar/mait613/floating_point_math.pdf .

Gunther Piez
  • 29,760
  • 6
  • 71
  • 103
2

drhirsch is correct - 5.55 cannot be exactly represented in binary floating point (in the same way that 1 ÷ 7 cannot be exactly represented in decimal).

However, for your purposes, this shouldn't be a problem, because a float definitely can store 5.55 accurate to three places, which is the number you have. This just means that you need to use the correct format when printing - in this case, %.3g. When you calculate the GPA, your calculations will still be accurate to three places, because the calculation of an average doesn't cause catastrophic cancellation.

Community
  • 1
  • 1
caf
  • 233,326
  • 40
  • 323
  • 462