Bug 29597 - log expression returns different results when casting
Summary: log expression returns different results when casting
Status: RESOLVED DUPLICATE of bug 323
Alias: None
Product: gcc
Classification: Unclassified
Component: c++ (show other bugs)
Version: 4.1.0
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2006-10-25 21:58 UTC by brad
Modified: 2006-10-26 06:39 UTC (History)
43 users (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description brad 2006-10-25 21:58:38 UTC
The following code should return the base2 logarithm of 64 (ie 6)

double d = log(64.0) / log(2.0);
int i = (int)d;
cout << i;

And indeed it does output "6". However, if you attempt to cast it on the same line, then it returns 5.

int i2 = (int)( log(64.0) / log(2.0) );
int i3 = static_cast<int>( log(64.0) / log(2.0) );
cout << i2 << i3;

This outputs "55" instead of the expected "66". Visual Studio 2003 outputs "66".

gcc 4.1.0, Suse Linux 10.1.
Comment 1 Andrew Pinski 2006-10-25 22:05:04 UTC
This comes from precission of the floating point.

*** This bug has been marked as a duplicate of 323 ***
Comment 2 Wolfgang Bangerth 2006-10-26 06:39:14 UTC
To be more concrete: (int)(expression) rounds down. So if your quotient
of logarithms happens to be computed to 5.999999999999999, then you
will get a result of 5 after casting to int. You should round results,
not just cast them.

W.