Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert is wrong, proven with cout

Tags:

c++

assert

When I run this, in main() the cout prints 5.395. But the assert says it failed!! This is really mind boggling, 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. :)

like image 541
Seb Avatar asked Dec 20 '22 08:12

Seb


1 Answers

Ah, floating point.

Say, for example, the actual return of getAvgDensity() is 5.395000000000000000000000001. It's not technically == 5.395, is it? Printing would, of course, discard all those pesky trailing decimals, but the value remains different.

When working with floats, you have to decide yourself what is an acceptable definition for "equal". Round the number manually, or compare it with <=/>= and suitable error margins.

like image 174
slezica Avatar answered Dec 24 '22 01:12

slezica