#include <stdio.h>
#include <stdint.h>
double n0 = 0.5;
double n1 = -0.5;
//special number, should round to zero
double n2 = 0.49999999999999994;
double n3 = -0.49999999999999994;
int32_t round_naive( double n ) {
return n + 0.5;
}
int32_t round_less_naive( double n ) {
return n > 0.0 ? n + 0.5 : n - 0.5;
}
int32_t round_my_try( double n ){
int32_t n2 = (int32_t)( n * 2.0 ); // double it
int bit = n2 & 0x1; // extract the half-bit
bit = n2 >> 31 ? -bit : bit; // check sign
return n2/2 + bit; // adjust
}
void test( double n ) {
printf( "round_naive ( %.17f ) -> %d\n", n
, round_naive
( n
) ); printf( "round_less_naive ( %.17f ) -> %d\n", n
, round_less_naive
( n
) ); printf( "round_my_try ( %.17f ) -> %d\n\n", n
, round_my_try
( n
) ); }
int main(void) {
test( n0 );
test( n1 );
test( n2 );
test( n3 );
return 0;
}
ICAgICNpbmNsdWRlIDxzdGRpby5oPgogICAgI2luY2x1ZGUgPHN0ZGludC5oPgogICAgCiAgICBkb3VibGUgbjAgPSAwLjU7CiAgICBkb3VibGUgbjEgPSAtMC41OwogICAgCiAgICAvL3NwZWNpYWwgbnVtYmVyLCBzaG91bGQgcm91bmQgdG8gemVybwogICAgZG91YmxlIG4yID0gMC40OTk5OTk5OTk5OTk5OTk5NDsKICAgIGRvdWJsZSBuMyA9IC0wLjQ5OTk5OTk5OTk5OTk5OTk0OwogICAgCiAgICBpbnQzMl90IHJvdW5kX25haXZlKCBkb3VibGUgbiApIHsKICAgIAogICAgICByZXR1cm4gbiArIDAuNTsKICAgIH0KICAgIAogICAgaW50MzJfdCByb3VuZF9sZXNzX25haXZlKCBkb3VibGUgbiApIHsKICAgIAogICAgICByZXR1cm4gbiA+IDAuMCA/IG4gKyAwLjUgOiBuIC0gMC41OwogICAgfQogICAgCiAgICBpbnQzMl90IHJvdW5kX215X3RyeSggZG91YmxlIG4gKXsKICAgIAogICAgICBpbnQzMl90IG4yID0gKGludDMyX3QpKCBuICogMi4wICk7IC8vIGRvdWJsZSBpdAogICAgICBpbnQgYml0ID0gbjIgJiAweDE7IC8vIGV4dHJhY3QgdGhlIGhhbGYtYml0CiAgICAgIGJpdCA9IG4yID4+IDMxID8gLWJpdCA6IGJpdDsgLy8gY2hlY2sgc2lnbgogICAgICByZXR1cm4gIG4yLzIgKyBiaXQ7IC8vIGFkanVzdAogICAgfQogICAgCiAgICB2b2lkIHRlc3QoIGRvdWJsZSBuICkgewogICAgCiAgICAgIHByaW50ZiggInJvdW5kX25haXZlICAgICAgKCAlLjE3ZiApIC0+ICVkXG4iLCBuLCByb3VuZF9uYWl2ZSggbiApICk7CiAgICAgIHByaW50ZiggInJvdW5kX2xlc3NfbmFpdmUgKCAlLjE3ZiApIC0+ICVkXG4iLCBuLCByb3VuZF9sZXNzX25haXZlKCBuICkgKTsKICAgICAgcHJpbnRmKCAicm91bmRfbXlfdHJ5ICAgICAoICUuMTdmICkgLT4gJWRcblxuIiwgbiwgcm91bmRfbXlfdHJ5KCBuICkgKTsKICAgIH0KICAgIAogICAgaW50IG1haW4odm9pZCkgewogICAgCiAgICAgIHRlc3QoIG4wICk7CiAgICAgIHRlc3QoIG4xICk7CiAgICAgIHRlc3QoIG4yICk7CiAgICAgIHRlc3QoIG4zICk7CiAgICAKICAgICAgcmV0dXJuIDA7CiAgICB9CiAgICAK