KHMan
keinh****@gmail*****
Wed Feb 28 22:44:09 JST 2018
On 2/16/2018 5:36 AM, John Beale wrote: > I noticed that I get two different answers when running the same > code (below) with the same compiler (gcc 6.3.0) on the same > machine (Lenovo Thinkpad P71). The difference is that one is MinGW > on Win10, and the other is Ubuntu 16.04 running in VirtualBox, but > both on the same Thinkpad. Maybe it's a 32bit vs 64bit difference? > I wouldn't have guessed that affected the output of basic math > though. I guess there is no guarantee about rounding when > converting double to int. > > Note: this was not an academic exercise, it came from a real > project, a pattern generator that had to fit an integer number of > features into a given space, and it took me by surprise when I got > different results. IMHO a real project should never use such a fragile scheme. Even if you end up fixing this one different result, it will blow up in your face again sometime in the future. This one example matters little because there is a deeper problem. Can you guarantee perfect-as-expected division results for those other platforms? Has this expectation been rigorously tested? Can you depend on this behavior now and in the future? Floating point implementations often have 1 ULP differences or more here and there. Perfection? A big thing to ask for. If the units are fundamentally integers, scale them accordingly and use integers everywhere. Why walk on a tightrope? If fractional results are possible, then massage the end result as needed; a simple double-to-int cast or truncation will not suffice. I'm sure you want your production code in your real project to be robust. > I am using the MINGW32 shell and gcc -v reports (MinGW.org > GCC-6.3.0-1) 6.3.0 > > CODE: SELECT ALL > <https://www.raspberrypi.org/forums/viewtopic.php?f=63&t=205567#> > > |#include <stdio.h> void main() { double a = 4.5; double b = 0.1; > int i = a / b; printf("%d\n",i); }| > > Ubuntu 16.04 on VirtualBox/Win10 result: 45 > Raspberry Pi Raspbian (ARM) result: 45 > Online compiler demo: at www.onlinegdb.com/online_c_compiler > <https://www.onlinegdb.com/online_c_compiler> : 45 > MinGW32 gcc 6.3.0-1 result: 44 -- Cheers, Kein-Hong Man (esq.) Selangor, Malaysia