math - high precision division in C -
i want following calculation without losing precision in c.
uint64_t ts_1 = 0x5212cb03ca115ac0; uint64_t ts_2 = 0x5212cb03ca115cc0; uint64_t ts_delta = (ts_2 - ts_1) double scale_factor = ts_delta/(2^32)
i getting value of ts_delta 0x200.
value of scale_factor 15.000000
.basically losing precision during calculation.
how do without losing precision.?
here short self contained example on how trying print.
#include <stdio.h> #include <stdint.h> #include <inttypes.h> int main() { uint64_t ts_1 = 0x5212cb03ca115ac0; uint64_t ts_2 = 0x5212cb03ca115cc0; uint64_t ts_delta = (ts_2 - ts_1); double scale_factor = ((double)ts_delta) / (((uint64_t)1) << 32); printf("ts_delta %"prix64" scale factor %f \n",ts_delta,scale_factor); return 0; }
you're not doing calculation think you're doing. ^
operator in c not perform exponentiation, performs bitwise exclusive or. dividing ts_delta
2 xor 32 == 34
. i'm not sure how got 15.000000
that, should have come out 15.058823529411764
.
the calculation wanted expressed in c this:
double scale_factor = ((double)ts_delta) / (((uint64_t)1) << 32);
edit: other answer: if compiler supports c99's hexadecimal floating-point literals, can write
double scale_factor = ts_delta * 0x1p-32;
written way, no casts necessary, because 1 side of multiplication double
, integer on other side converted match. unfortunately, several compilers have uint64_t
no other features of c99, e.g. recent msvc.
Comments
Post a Comment