user3116130
user3116130

Reputation: 65

Generate random scientific notation float in python

I want to generate random floats printed in scientific notation, between x and y.

I tried this :

'%.2E' % random.uniform(1.0e5,3.0e10)

But this keeps generating numbers between 1.0e8 and 3.0e10 and never below ! Is there any other way ? I want the generated numbers to be not concentrated only in the upper limit of the domain !

Thank you

Upvotes: 0

Views: 659

Answers (2)

poke
poke

Reputation: 387637

As Tim already said, the probability for a random number between 1e8 and 1e10 is a lot bigger than those between 1e5 and 1e8, so it’s just that your sample does not contain those—which is absolutely possible.

A simple test can prove that:

>>> [random.uniform(1.0e5, 3.0e10) < 1e8 for _ in range(10000)].count(True)
33

So there are indeed numbers below 1e8; it’s just that there are very few, less than one percent.

Now, depending on what you are up to, you might just be interested in generating “nice-looking” scientific notations, without the numbers being actually uniformly distributed. In that case, you could get two random numbers, one which determines the coefficient, and one that determines the exponent:

'{:.2e}'.format(random.uniform(1.0, 3.0) * 10 ** random.randint(5, 10))

As said, this will not yield uniformly distributed random numbers; so depending on your application this might not help at all. But at least the numbers will “look more random”.

Upvotes: 3

Tim Pietzcker
Tim Pietzcker

Reputation: 336138

Rest assured that there will be numbers in the correct range.

Just think about it. How many numbers (let's take integers for simplification) are there between 105 and 108?

How many are there between 108 and 3*1010? Hint: About 300 times as many.

Upvotes: 5

Related Questions