Fast multiplication/division by 2 for floats and doubles (C/C++)

This is one of those highly-application specific things. It may help in some cases and not in others. (In the vast majority of cases, a straight-forward multiplication is still best.) The “intuitive” way of doing this is just to extract the bits into a 64-bit integer and add the shift value directly into the exponent. … Read more

Division of integers returns 0

You should cast before you divide, but also you were missing a subquery to get the total count from the table. Here’s the sample. select random_int, count(random_int) as Count, cast(count(random_int) as decimal(7,2)) / cast((select count(random_int) from test) as decimal(7,2)) as Percent from test group by random_int order by random_int;

Why does integer division code give the wrong answer? [duplicate]

You’re dividing integers, which means that you’re using integer division. In integer division the fractional part of the result is thrown away. Try the following: float res = (float) quantity / standard; ^^^^^^^ The above forces the numerator to be treated as a float which in turn promotes the denominator to float as well, and … Read more

Is integer division always equal to the floor of regular division?

The reason the quotients in your test case are not equal is that in the math.floor(a/b) case, the result is calculated with floating point arithmetic (IEEE-754 64-bit), which means there is a maximum precision. The quotient you have there is larger than the 253 limit above which floating point is no longer accurate up to … Read more

Is divmod() faster than using the % and // operators?

To measure is to know (all timings on a Macbook Pro 2.8Ghz i7): >>> import sys, timeit >>> sys.version_info sys.version_info(major=2, minor=7, micro=12, releaselevel=”final”, serial=0) >>> timeit.timeit(‘divmod(n, d)’, ‘n, d = 42, 7’) 0.1473848819732666 >>> timeit.timeit(‘n // d, n % d’, ‘n, d = 42, 7’) 0.10324406623840332 The divmod() function is at a disadvantage here because … Read more

Should I bit-shift to divide by 2 in Java? [duplicate]

Unless you’re working in a shop and a codebase where bit-shifting is common then, IMHO, you’re risking obfuscation. Yes, the expressions may be logically equivalent but: A n00b might get confused by the alternate syntax An old guy who hasn’t had to do any bit-shifting since college, like myself, might get confused If you bit … Read more

tech