113 points · by burntcaramel · 3y ago · 66 comments
fn main() {
let start = std::time::Instant::now();
let total = (0..=u32::MAX)
.filter(|&x| {
let f = f32::from_bits(x);
0. <= f && f <= 1.
})
.count();
println!("total {total} in {:?}", start.elapsed());
}
total 1065353218 in 1.364751583s
Edit: Apparently if you move the sum to its own function it runs in 500ms. A bit temperamental.Edit 2: it's the size of the sum accumulator that makes it slow. The version above is like `.fold(0usize, |a, _| a + 1)`. When I moved it to another function, I cast the return value to u32, so LLVM saw basically `.fold(0u32, |a, _| a + 1)` and could use u32 throughout. Godbolt says the usize version ends up with floats in xmm* registers on x86, which fit 4 32-bit floats, but the u32 version ends up with floats in ymm* registers (8 32-bit floats) and similar half-as-wide behaviour on ARM.
This is a larger number than the one cited in the post because the latter only includes "normal" numbers. This includes the "denormals" as well.
It's very easy to generalize this to 64 bits, there are 4,607,182,418,800,017,410 of them.
#include <math.h> // nextafterf
#include <stdio.h> // printf
int main()
{
long n = 1;
float f = 0;
while (f <= 1)
{
f = nextafterf(f, 2);
n = n + 1;
}
printf("%ld\n", n);
return 0;
} >>> import struct
>>> count = 0
>>> for i in range(0x1_0000_0000):
... f = struct.unpack('<f', struct.pack('<I', i))[0]
... if 0 <= f <= 1: count += 1
...
>>> count
1065353218
[0] https://randomascii.wordpress.com/2014/01/27/theres-only-fou...pypy never ceases to amaze me for low-effort performance gains on computational stuff.
A naive implementation in C compiled with Apple's clang (-O2) takes 0.62 seconds, of course.
import time, array
n = 0
start_time = time.time()
values = bytearray(b"".join(i.to_bytes(4, "big") for i in range(2**24)))
for prefix in range(256):
values[::4] = prefix.to_bytes(1, "big") * (2**24)
arr = array.array("f", values)
n += sum(1 for x in arr if 0.0 <= x <= 1.0)
print(f"Found: {n} Time: {time.time() - start_time:.1f} seconds")
It uses an array.array() to convert from a large number of concatenated 4 bytes to floats, rather than going through the struct module one-by-one.Rather than build all 0x1_0000_0000 values in memory, I process 0x100_0000 at a time, and accumulate the partial sums.
On my laptop this reports "Found: 1065353218 Time: 228.5 seconds", so just under 4 minutes.
A slightly improved algorithm in NumPy takes 5.4 seconds.
import time, numpy as np
start_time = time.time()
arr = np.arange(2**24, dtype=np.uint32)
incr = np.full(2**24, 2**24, dtype=arr.dtype)
values = np.frombuffer(arr, np.float32)
n = ((0.0 < values) & (values <= 1.0)).sum()
for i in range(1, 256):
arr += incr
n += ((0.0 < values) & (values <= 1.0)).sum()
print(f"Found: {n} Time: {time.time() - start_time:.1f} seconds") long start = System.currentTimeMillis();
int count = 1;
for (int intBits = Float.floatToIntBits(0.0f); Float.intBitsToFloat(intBits) <= 1.0f; intBits ++) {
count++;
}
System.out.println(count);
System.out.println((System.currentTimeMillis() - start) + "ms"); long start = System.currentTimeMillis();
long count = IntStream.rangeClosed(Float.floatToIntBits(0.0f), Float.floatToIntBits(1.0f)).count();
System.out.println(count);
System.out.println((System.currentTimeMillis() - start) + "ms");
1065353217
0ms int count = 1;
int limit = Float.floatToIntBits(1.0f);
for (int intBits = Float.floatToIntBits(0.0f); intBits <= limit; intBits++) {
count++;
}
it will start out with the same performance as your previous one, and then after a few tries the JVM will optimize it into a constant. 1065353218, 0.91
1065353218, 0.69
1065353218, 0.00
1065353218, 0.64
1065353218, 0.64
1065353218, 0.63
1065353218, 0.66
1065353218, 0.63
1065353218, 0.63
1065353218, 0.00
1065353218, 0.00
1065353218, 0.00
...
1065353218, 0.00
Process finished with exit code 0 ((long) upTo) - from + last;
I would think it just takes less than 1 ms on first execution.https://github.com/openjdk/jdk/blob/caa841d9a52352a975394e55...
Really cool trick!
I can't tell that'd be possible - I see the arguments could be evaluated at compile time, but knowing IntStream.rangeClosed will be evaluated at compile time is a leap, to me.
Did you know before you wrote the code that'd happen? Is it like C? You cross your fingers and hope the compiler unrolls?
Also, in the case of your test, it's not even letting the JIT kick in, but rather using a shortcut to calculate the length of the range.
SELECT sum(reinterpretAsFloat32(number) BETWEEN 0.0 AND 1.0) FROM numbers_mt(0x100000000)
1 row in set. Elapsed: 0.170 sec. Processed 2.39 billion rows, 19.08 GB (14.02 billion rows/s., 112.13 GB/s.) const NaN = $FF shl 23;
var x, t: longint;
f: single absolute x;
begin
t := 0;
x := 0;
repeat
inc(t, ord((x and NaN <> NaN) and (0<=f) and (f<=1)));
inc(x);
until x = 0;
WriteLn('total: ', t);
end.
total: 1065353218 (in ca. 40 seconds)Curious to know the total compile + run time under different compiler optimizations. For code you only need to run once, I don't see how having the compiler unroll the loops actually saves you any time.
The compiler can unroll loops like that to `for (i=0; i < n; i+=8) { acc += 8; }` (ignoring the remainder of n/8), which does 8x fewer compare+conditional jump instructions. It has nothing to do with how many times you’ll be running the code; this kind of optimisation reduces the runtime of any single execution.
I had thought that in cases like this (where the output can already be determined at compile time) the compiler could just run the loop to get the answer, therefore avoiding running it every time the code runs, which was what I was picturing when I wrote my earlier comment.
At least when solving physics problems, you'll frequently scale the equations so the actual values in the problem are around -1..1. Thus having extra precision around -1..1 when solving such problems would be beneficial.
For example, if you're trying to solve the motion of a mass on a spring that gets an initial kick, rather than representing the spring length in meters, you divide by some characteristic length[1] and get a non-dimensional length of order 1. If you want the actual length, you just multiply the non-dimensional length by the characteristic length.
[1]: https://hplgit.github.io/scaling-book/doc/pub/book/html/._sc...
It is indeed, and one of the first things you learn in scientific computing is to make your values fit mostly within [-1, 1].
Floating point numbers have the same precision (relative precision) everywhere.
https://mumble.net/~campbell/2014/04/28/uniform-random-float
and there's working C code too:
[0] https://github.com/camel-cdr/cauldron/blob/main/cauldron/ran...
The generated exponent starts of at the max exponent of a and b, and is logarithmically decremented (I'm not sure if this is the correct word for it, but decremented until a coin flip hits tails, would be a better way to explain it).
So the exponent and the fraction range can't ever get really small, since there is always at least one exponent that accepts the full range of fractions.
Edit: Actually, looking at it again, the second special case doesn't apply to subnormals, so while generating in the range
float x = 2.3509886E-38f; // exp=00000001,frac=11111111111111111111111
float min = nextafterf(nextafterf(x, 0), 0);
float max = nextafterf(nextafterf(x, 1), 1);
works almost instantly (on average 4 iterations), the current code does indeed have a bottle neck for: float x = 1.1754942E-38f; // exp=00000000,frac=11111111111111111111111
float min = nextafterf(nextafterf(x, 0), 0);
float max = nextafterf(nextafterf(x, 1), 1);
It's not insanely-minutes-long-stall-bad, but takes about 0.02 seconds to generate one number in the above range with a good prng (opposed to 2e-08 seconds for the first case)I'll look into fixing this.
Edit 2: I've added a commited a comment about this for now. I wonder why my test suite didn't catch this.
"<=" does not depend on where x came from or what it would have been had something else happened that didn't happen. There's no "maybe."
I'm pretty sure that your definition of an interval is correct even when the set doesn't have a total order, but if we're talking about floats whose values are in [0, 1] in the space of real numbers, that may not include -0.0f, since floating point numbers usually represent one number in a range of real values, and -0.0f represents -epsilon where epsilon is between 0 and the real value of the smallest denorm.
const hash = crypto
.createHmac('SHA256', serverSeed)
.update(`${ clientSeed }:${ nonce }`)
.digest('hex');
const significant = hash.substring(0, 52 / 4);
const integer = parseInt(significant, 16);
const float = integer / (2 * 52);
return { float, hash, };How many floating-point numbers are in the interval [0,1]? - https://news.ycombinator.com/item?id=13759458 - Feb 2017 (153 comments)
or is it 1,065,353,218 (comments) and why the difference?
The commenters counted also subnormals.
Not a graph, but gets much closer to answering this.
https://www.researchgate.net/figure/The-distribution-of-repr...
So you chose to just decide I was being "glib" and slander me before understanding the context? Have a weekend. I think you unironically need to touch grass.
I really hate this website sometimes.