2

I'm doing a simple bit of maths on a PIC microcontroller, running code in C and using MPLABX and the xc16 compiler. This is the code:

double mydouble = 0.019440;
long long int mypower = 281474976710656;

long long int result = mypower*mydouble;

Printing out 'result' gives me 5,471,873,794,048; while it should give 5,471,873,547,255. Any idea what is causing this problem, and how I can rectify it?

Thanks

edipo99
  • 37
  • 1
  • 4

1 Answers1

2

xc16 handles both double and float as 32-bit data types by default. You need to give the compilation option -fno-short-double to use 64-bit doubles.

You may also be able to just use long double as a data type, but I can't compile at the moment to verify that.

(As a test, 5,471,873,794,048 is also exactly the result you get compiling your sample code on x86 using float instead of double)

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
  • 1
    It's worth noting that log2(281474976710656) is 48, so any FP representation with less than 48 bits of precision cannot represent it exactly. SPFP has 24 and DP 53, so he'll have the same problem again with DP if/when his `mypower` exceeds 2^53 (about 9e15). – Emmet Mar 14 '14 at 18:23
  • @Emmet sorry you've lost me with your acronyms, what are FP and SPFP and DP? It's not happy with long double as a data type, but I'm just changing the compilation options now so I'll let you know how that goes... – edipo99 Mar 14 '14 at 18:45
  • 1
    @edipo99 SPFP == single precision floating point, DP == double precision. – Joachim Isaksson Mar 14 '14 at 18:46
  • 1
    Great success!! Enabling 64-bit doubles in the xc16 compiler fixed the problem for me, didn't have to make any changes to the code at all. Thanks very much @Joachim – edipo99 Mar 14 '14 at 18:50
  • @edipo99: there's a number of different floating-point (FP) precisions: half (16 bits), single (“SP” or “SPFP”, 32bits), double (“DP” or “DPFP”, 64bits), extended (80 bits) and quadruple (128 bits). Most platforms support at least SP and DP, which are by far the most common. – Emmet Mar 14 '14 at 18:54
  • 1
    Good luck. When I programmed PICs, they didn't even have interrupts, much less FPUs :) – Emmet Mar 14 '14 at 19:14