pythonrandomnumpy

generate random numbers truncated to 2 decimal places


I would like to generate uniformly distributed random numbers between 0 and 0.5, but truncated to 2 decimal places.

without the truncation, I know this is done by

import numpy as np
rs = np.random.RandomState(123456)
set = rs.uniform(size=(50,1))*0.5

could anyone help me with suggestions on how to generate random numbers up to 2 d.p. only? Thanks!


Solution

  • A float cannot be truncated (or rounded) to 2 decimal digits, because there are many values with 2 decimal digits that just cannot be represented exactly as an IEEE double.

    If you really want what you say you want, you need to use a type with exact precision, like Decimal.

    Of course there are downsides to doing that—the most obvious one for numpy users being that you will have to use dtype=object, with all of the compactness and performance implications.

    But it's the only way to actually do what you asked for.

    Most likely, what you actually want to do is either Joran Beasley's answer (leave them untruncated, and just round at print-out time) or something similar to Lauritz V. Thaulow's answer (get the closest approximation you can, then use explicit epsilon checks everywhere).

    Alternatively, you can do implicitly fixed-point arithmetic, as David Heffernan suggests in a comment: Generate random integers between 0 and 50, keep them as integers within numpy, and just format them as fixed point decimals and/or convert to Decimal when necessary (e.g., for printing results). This gives you all of the advantages of Decimal without the costs… although it does open an obvious window to create new bugs by forgetting to shift 2 places somewhere.