unwanted proximity in dividing two float numbers
Mar 11, 2016 at 11:11pm UTC
Hello,
I was writing a parser from strings to positive float numbers.
While debugging the part of the code that deals with the fraction, I saw that the result of 4/100.0 is 0.3999999 rather than 0.04, which obviously ruins the parser.
Could anyone please explain why it happens and how do I solve this problem?
The code I added describe only handling the fraction part of the number:
1 2 3 4 5
newFractionToBeAdded = (str[i]-'0' /divisor);
result += newFractionToBeAdded;
divisor = divisor*10.0;
Mar 11, 2016 at 11:30pm UTC
It seems you misplaced a parenthesis: (str[i]-'0' )/divisor
I don't have enough context to see any other errors.
Mar 11, 2016 at 11:54pm UTC
Tried it with the parenthesis, it doesn't seem to be the problem, still returns 0.03999999.
Here's the full code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
float toNum(char * str){
int flag = 0;
int len = strlen(str);
int i=0;
float result=0;
float divisor = 10.0;
float newFractionToBeAdded = 0;
do {
if (str[i] == '.' ){
flag = 1;
i++;
continue ;
}
if (flag==0){
result = (result*10) + str[i]-'0' ;
i++;
}else {
newFractionToBeAdded = ((str[i]-'0' )/divisor);
result += newFractionToBeAdded;
divisor = divisor*10.0;
i++;
}
}
while (len>i);
return result;
}
Mar 12, 2016 at 3:08pm UTC
Looks like it is simply the properties of floating point numbers which are important, rather than a problem with the code.
1 2 3 4 5 6 7 8 9 10 11
int main()
{
char decimal[] = "0.04" ;
float test = 0.04;
cout.precision(10);
cout << "toNum(decimal) " << toNum(decimal) << '\n' ;
cout << "test " << test << '\n' ;
cout << "difference " << (test - toNum(decimal)) << '\n' ;
}
Output:
toNum(decimal) 0.03999999911
test 0.03999999911
difference 0
Changing everything from
float
to
double
won't make the problem go away, but it gives a few more decimal places before things are visibly awry:
toNum(decimal) 0.040000000000000000833
test 0.040000000000000000833
difference 0
Mar 12, 2016 at 9:51pm UTC
Chervil - That does the work! :)
Thank you!
Topic archived. No new replies allowed.