The statement is incorrect, checked by cout

When I ran this, in main () cout prints 5.395. But claim it failed! This is really stunning, why is this happening?

#include <iostream> #include <cassert> using namespace std; const float A = 1.6; const float C = 1.55; const float G = 2.2; const float T = 1.23; char empty[18]; int arraySize; void copyArray(char sourceArray[], char targetArray[], int size) { for(int i=0;i<size;i++) { targetArray[i] = sourceArray[i]; } } double getAvgDensity(char aminoAcid) { char aminoUpper = toupper(aminoAcid); aminoToArray(aminoUpper); double counter = 0; int codonTotal = arraySize / 3.0; if (arraySize == 0) return 0; else { for (int i = 0; i < arraySize; i++) { counter += charToDouble(empty[i]); } return (counter / codonTotal); } } int main() { cout << getAvgDensity('A') << endl; // prints 5.395 assert(getAvgDensity('A')==5.395); return 0; } 

Edit: thanks for all the answers, I just multiplied by 1000, converted to int, converted back to double and divided by 1000. :)

+4
source share
3 answers

Ah, floating point.

Say, for example, the actual return of getAvgDensity() is 5.395000000000000000000000001 . This is not technically == 5.395 , is it? Of course, printing will discard all these disgusting final decimal numbers, but the meaning remains different.

When working with floats, you must decide for yourself what is an acceptable definition for "equal". Wrap the number manually or compare it with <= / >= and the appropriate error fields.

+10
source

This has already been answered, but I will add two cents. You may find it helpful to make the doubling comparison function if you plan to do this often. The idea is to verify that fabs(ab) < epsilon where epsilon is a small value representing the number of errors that can be tolerated.

 bool is_equal( double a, double b, const double epsilon = 1e-5 ) { double c = a - b; return c < epsilon && -c < epsilon; // or you could use fabs(c) < epsilon } 

Then this is just a case of this:

 assert( is_equal(getAvgDensity('A'), 5.395) ); 
+1
source

The reason is that cout does not print this high precision by default. Try the following:

 int main() { std::cout.precision(25); cout << getAvgDensity('A') << endl; // prints 5.395 assert(getAvgDensity('A')==double(5.395)); return 0; } 
0
source

Source: https://habr.com/ru/post/1468861/


All Articles