0

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

1
  • Do you really want a uniform distribution, or do you want something else? Perhaps you'd prefer the logarithm of the output to be uniformly distributed? Note that that would produce a perhaps-surprising concentration of numbers starting with 1. When it comes to probability, intuition is very frequently wrong. Commented Feb 24, 2014 at 9:15

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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”.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.