0

My code:

$random_number = mt_rand(1,100);

if ($random_number <= 10){
    header('Location: http://www.site1.com');
} else {
    header('Location: http://www.site2.com');
}

exit;

Needless to say, it seems to work if you have a lot of traffic, but when you are down to around 1000 uniques a day, the percentage hovers around 35 to 40%.

Rizier123
  • 58,877
  • 16
  • 101
  • 156
NiteRain
  • 663
  • 8
  • 14
  • 7
    Random numbers very seldom behave the way you expect. – Marc B Aug 14 '12 at 21:25
  • @MarcB I see what you did there! :) – Daniel Figueroa Aug 14 '12 at 21:26
  • according to your code, users should only be redirected (on an average of) 9% of the time due to the `<` which really should be a `<=`. although, tbh, why aren't you just selecting a random number 1 through 10 and checking it against the number 1? – jeremy Aug 14 '12 at 21:29
  • 2
    Why don't you just store a counter on the webserver? The counter could be stored in a file, database, memcached, redis, or whatever floats your boat. Just count to 10, redirect, and reset the counter afterwards. – Rem.co Aug 14 '12 at 21:30
  • @Nile, Actually, the real code is <= 10. – NiteRain Aug 15 '12 at 00:14
  • @RemcoOverdijk, you believe the percentage would be better if I made it 10% over a range of 1, 10? – NiteRain Aug 15 '12 at 00:15
  • @NiteRain, No, I'm trying to tell you that random numbers are, well.. random. So there's no reliable way of getting 10% out of any range of RANDOM numbers. Random numbers are not evenly (or even merely so) distributed in any way so for your purposes it is explicitly wrong to use them or rely on them. What I was trying to say is that you have to count the actual visitors and store the count on the server. If count < 10, redirect to site B; If count == 10, redirect to site A, reset counter to 0 and store it. – Rem.co Aug 15 '12 at 00:25
  • @NiteRain you obviously edited it. – jeremy Aug 16 '12 at 01:07

2 Answers2

1

For a more accurate distribution of traffic use a load balancer or increment a counter in your code.

Here is a nice article on why mt_rand isn't so random

Martin
  • 6,632
  • 4
  • 25
  • 28
  • That article says that they're it's random enough for cryptographic use. Cryptographers aren't worried about the distribution of the data, but how easy it is to predict the sequence. It should be good enough for monte carlo use like this. – Barmar Aug 14 '12 at 21:40
  • The link is broken – Abraham Jan 27 '23 at 14:29
0

If you're looking to do some A/B testing, there's a better way than blindly choosing at random and it's not really more complex.

Sean McSomething
  • 6,376
  • 2
  • 23
  • 28
  • 1
    @aug - Looks like it's gone for good. It was a link to an article about the "Multi-armed Bandit" - https://support.google.com/analytics/answer/2844870?hl=en is the best replacement I can find in 5 minutes of searching. – Sean McSomething Jan 29 '16 at 09:22