Is there some way with a Printf format string to say this:
Printf.sprintf "%03d_%03d_%03d" millions thousands units
But, without having to compute millions, thousands and units (as I naively implemented)?
I.e. I would like to have a ‘_’ to separate every three digits starting from the right.
Yes, it is documented in the manual:
Indeed: OCaml library : Printf
d, i: convert an integer argument to signed decimal. The flag # adds underscores to large values for readability.
I never spotted it in the manual; probably because there is not the keywork “financial”.
I didn’t know this ! It’s a pity it doesn’t work for floats.
Same, it’s cool. However floats also have their own hidden gem, for
those who don’t know: exact printing in hexadecimal!
# Printf.printf "%h\n" 42.1;;
If only this was supported in more languages…
This was already specified in C99 with the format specifier
%a, some 15 years before OCaml’s implementation…
We do have something like this in OCaml
I wonder if fixed point arithmetic would go significantly faster than regular floats.
I wonder if this would be useful for scientific calculations (like Molecular Dynamics).
A very good reference for throughput and latencies of CPU instructions is this document:
Based on this data, I would say that in the general case (64 bits) it would be slower:
- Integer division usually takes more cycles than float division
- There is no equivalent of fused multiply-add with integers
- It will require a conversion to float call high-performance libraries like BLAS
- In OCaml, there is a special treatment for float arrays to improve performance.
For memory-bound algorithms, if a fixed-point format with a reduced number of bits can be used without loss of precision, it could be beneficial by increasing the memory throughput.