Maximum coverage for loops; bit reversing integars

So I was live-plotting some results from a simulation code (written in C), which was producing results for an input parameter (in this case Temperature), over a range generated by a for loop. Pretty standard computational physics. It was clearly suboptimal watching the new dataset arrive in small, fine, increments from zero upwards; the obvious thing was to change the discretisation of the for loop & make it more coarse. Yet, surely there is some way to get better coverage of the dataset, like a ‘streaming’ JPEG or GIF arriving with increasing discretisations of the blockiness?

What about some mathematical function that would jump around the space with good coverage? A pseudo-random number generator with a fixed period? Some mathematical function that would map an ascending series of integers into spatial coverage? Modulus arithmetic on some prime or co-prome addition?

How about reversing the binary digits in an incrementing integer? So instead of going 0,1,2,3…254,255; you would bounce around the number line: 0,128,64,192,32,160 … 127,255. So it’s sort of doing a binary split of the unoccupied locations on the number line at each step. You get maximum coverage, with increasing levels of fidelity, ending up with a complete (but missorted) dataset.

So with a Bit Twiddling hack found via Stackoverflow (http://graphics.stanford.edu/~seander/bithacks.html#ReverseByteWith64BitsDiv), the totally crazy bit-shifting code (for a byte, so covering 256 values) looks like: https://gist.github.com/jarvist/368622717a5d3bcadfc0

It’s pretty low level (in Python or similar, you could reorder a list, and iterate over that instead), but the result is nice! It’s almost so useful that perhaps one should write it into a mini function or macro…

Avatar
Jarvist Moore Frost
Electronic structure theory