1

I have the following statement select random() * 999 + 111 from generate_series(1,10)

which results in:

690,046183290426
983,732229881454
1091,53674799064
659,380498787854
398,545482470188
775,65887248842
1044,79942638567
173,288027528208
584,690435883589
522,077123570256

as you see; Two values are over 999!

This one works fine: select random() * 9 + 1 from generate_series(1,10)

My system is: PostgreSQL 9.3.5 on x86_64-unknown-linux-gnu, compiled by gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2, 64-bit

Is that a bug?

1
  • what a stupid: random() * (9999-1111) + 1111 Commented Dec 29, 2014 at 6:12

2 Answers 2

3

No, it's not a bug. The expression random() * 999 gives you a number from 0 to 999 inclusive.

Adding one to that will give you a number 1 through 1000. Adding 111 will give you a number 111 through 1110. So, in addition to seeing some values over a thousand, you'll also see none under a hundred and eleven.

Your mistake appears to have been assuming that, when you use 999 instead of 9, you have to add 111 instead of 1. That's not the case. To get a number 1 through 1000, you need:

random() * 999 + 1
Sign up to request clarification or add additional context in comments.

Comments

0

No, this isn't a bug.

random generates a number in the range [0.0, 1.0]. Multiply this by 999, you get a number in the range [0.0, 999.0]. Add 111 and you have a number in the range [111.0, 1110.0].

In fact, given an even distribution by random, there's roughly a 11% chance of getting a number larger than 999. The result you're describing isn't only possible, it's expected.

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.