• Matthew (unregistered)

    int getRandomNumber() { return "moo"; }

  • Jeremy (unregistered)

    So some tests on this code. (converted to php) Average length from getRandomNumberOfDigits: 37 Execution time for 1000 iterations: .3 seconds

    And just using rand(0, rand(0, 100)) Average length: 50 Execution time for 1000 iterations: .009 seconds

    On top of that I seriously doubt they actually use a 10^rand(0, 100) number, but rather trim it...

    Epic Fail!

  • Ted from Accounting (unregistered)
  • (cs) in reply to Derek
    Derek:
    KattMan:
    I know I can get even more randomer.

    Let rand return a number between 2 and 9. Multiply by 9. Add the digits of the result together. Subtract 5.

    This should be as random as I need to get and as everyone knows, a formula is better than just calling rand().

    that always equals 4. Why not just use xkcd's version, it's less wordy, but has the same result.

    Because xkcd's isn't a formula, mine has to be better!

  • max (unregistered) in reply to yer mom
    yer mom:
    My two dice must be loaded! I get seven way more often than any other number :o

    This is actually way more insightful than most people might know. The Math.random() method already generates the maximum amount of entropy in its output that it can (entropy you can think of as being a measure of randomness). By distilling a sequence of random numbers into digits, you are reducing the possible outputs from billions and billions to ten. You're reducing the ideal entropy of the function (just looking purely at the output size), so necessarily the actual entropy cannot be any greater than that (think of it sorta like the laws of thermodynamics but with bits).

    So... in short... I REALLY hope that the comment at the top about making Math.random() more random isn't what they actually thought, because the output of this function is way less random than Math.random().

    Truly, the real wtf is that they already knew about Math.random() and didn't use it. If you're doing something crypto-wise you should just use one of the well-established crypto methods like blum-blum-shubb.

    Sorry about the super verbose comment. As a crypto programmer, I just thought I'd weigh in.

    Cheers!

    • max
  • (cs) in reply to gblues
    Irish I were drunk too. Rowr.
    random_comment()
  • Tony (unregistered)

    Obviously the numbers will be even more random if you randomize the digit array first. For example:

     ... digits = { '5','9','2','1','8','4','7','3','0','6' };
  • Mike (unregistered)

    Reminds me of this XKCD snippet: http://xkcd.com/221/

  • JDM (unregistered) in reply to MAV
    MAV:
    Wonder what they're doing that needs super-extra-ultra random numbers?

    Generating unique IDs, obviously :D

  • aHa (unregistered) in reply to MAV

    lolz... going by the comments, the readers of this site dont always understand the WTFs

  • (cs) in reply to Mike
    Mike:
    Reminds me of this XKCD snippet: http://xkcd.com/221/

    Wow, I can't believe no one posted that before you.

    Oh wait like 3 people did.

  • (cs)

    Playing with the density of values when it comes to 500000 run of that super function gives nice results. Here is the density curve: [image]

    Now a slight zoom around zero, see the nice curious peaks? Well at least the got a somehow fractal function. smaller peaks are around big peaks, with smaller peaks around them, etc. A shame it stops after 100 iterations :D. Wait, it's exactly the maximum number of digits :p! [image]

    That sure is so much better than what you get out of Math.random(), isn't it? That variations in the density is probably so bad (probably due to my naive way of calculating it, which is perfectly correct for non random generator using 100 digits in string :p! [image]

    The calculation code, for the fun :D (Yes, i know it's a wtf, the randomizer deserves it!)

            int MAX = 500000;
            double[] datas = new double[MAX];
            Randomizer rnd = new Randomizer();
            for (int i=0; i < MAX; i++){
                datas[i]=rnd.random();
            }
            java.util.Arrays.sort(datas);
            for (int i=0; i< MAX;){
                int j = i;
                while (j<MAX && (datas[j]==datas[i] || (j-i)<50)) //arbitrary defined precision, minium elements to calculate a density
                    j++;
                if (j>=MAX || (datas[j]==datas[i]))
                    break;
                int count = j-i+1;
                double mean = 0.0;
                for (j=i;j<i+count;j++)
                    mean+=datas[j];
                mean/=count;
                double density = count/(datas[i+count-1]-datas[i])/MAX;
                System.out.println(i+"\t"+mean+"\t"+density);
                i+=count;
            }
    </pre>
    
  • CTS (unregistered) in reply to akatherder

    On many systems this isn't true. Salting the RNG is a better idea, and most systems do have that function.

  • Foo (unregistered)

    Maybe digits change somehow on different machines, locations, times (like air pressure in different locations) or other unknown dimensions. So it might make sense to keep the set of numbers as characters. Thanks, that one made my day! ;)

  • Yuyo (unregistered)

    Maybe a disclaimer, "This is also extremely slow and idiotic," would make it a little better for those who use the class and just have the javadoc available.

  • (cs)

    It would have been easier to simply return the number of "The real WTF.." comments on TheDailyWTF for the day.

  • Erik (unregistered)

    Those plots generated by this wonderful function remind me a bit of an old CD Walkman I had. It was an MP3 model, one of the first, and it cost me quite a bit at the time. I would have approximately 120 songs to a CD, and they were typically albums, so 10 folders of about 12 songs each. When this was the case, the shuffle feature seemed to work just fine, but I discovered something sort of weird about it later. I had a CD with about 100 tracks, but one folder only had about 5 and the other the remaining 95.

    Those 5 tracks played WAY more often than they ought to, and I realized that the damn thing was randomly selecting a folder THEN randomly selecting a track. Those 5 songs then had a 50% chance of being played vs. the other 95! I'd have a 10% chance of hearing one of the first folder's songs, and a just-over 0.5% chance of hearing the other 95!

    All I can say is... good job Sony!

  • Kivi (unregistered) in reply to tchize
    tchize:
    Playing with the density of values when it comes to 500000 run of that super function gives nice results. (density curves and calculation code omitted)

    tchize, this is fabulous.

  • (cs) in reply to Kivi
    Kivi:
    tchize:
    Playing with the density of values when it comes to 500000 run of that super function gives nice results. (density curves and calculation code omitted)

    tchize, this is fabulous.

    Ironically, I hope :D

  • (cs)

    On first reading this, I thought "salt!" (Amongst several other four-letter words.)

    There is a certain beauty in it, however, and for once on TDWTF it has very little to do with the code. Read the comments:

    /**

    • We all know that random number generators aren't truly random.
    • This class generates random numbers a bit more randomly. */ C-style comment, proposing a lemma that is (in practice) indefensible; followed by an indefensible conclusion.

    // Allow this to be instantiated in parallel in multiple threads C++-style comment, ignoring the obvious distinction between "instantiated" and "used." Putting my cone-head hat on, I might want to question why there's no "serialize" here.

    Putting my OMFGWTF hat on, I'm no longer sure that I care.

  • Jake Cohen (unregistered)

    The problem with most RNGs is that they are based on a mathematical formula.

    In a truly random number generator, the probability of any number being returned is exactly the same as the probability of any other number being returned, every time it is invoked.

    For a pseudo-RNG based on mathematical transformation of the previous value, the probability is skewed because they simply won't return the same value twice in a row. This means that given prng(N) = k, the probability that prng(N+1) = k is zero, which is against the definition of being truly random.

    Using atmospheric noise (hardware-based) is probably as close as you can get to truly random, but even that doesn't necessarily create a perfectly even distribution of probability across all its possible values. It just makes it non-deterministic in terms of the state of the software using it.

  • Steve (unregistered)

    For the first time in a long time, I uttered an audible "WTF" when reading that code.

    Of course, that's the whole idea here, isn't it?

  • Babs (unregistered) in reply to MAV

    Oh, I dunno, wasting time and billing hours to the clods who outsourced the work to them in the first place?

  • vvv (unregistered)

    a brilliant logic really - to guess the number one would need to guess a number of times to guess a number. Too bad that logic can't replace common sense and good education, ie. one that at least includes math.

  • Robin Goodfellow (unregistered)

    The WTF here is that this code is actually way less random than even a poor random number generator. Consider that in any given range of numbers up to X digits long there are far more numbers of higher digits than there are of lower digits. For example, there are only 10 1-digit numbers, but there are 90 2-digit numbers. This algorithm, however, gives equal probability to producing numbers of any given length up to the maximum number of digits. Meaning there is an equal chance of producing a 1-digit number as there is of producing a 10-digit number. Which is not ideal. If this algorithm were actually used in a high security environment it would represent a severe vulnerability.

  • letatio (unregistered)

    Noooo!!!! Somone leaked my RSA hash random function!!!! ahhhhhhhhhhhhhhhhhhhhhhhhhhh

  • Phantom Watson (unregistered)

    "in it's entirety"? Tsk, tsk.

  • (cs) in reply to Erik
    Erik:
    <snip stuff about lack of randomness on Sony CD player> All I can say is... good job Sony!

    Well, at least that explains the root-kit thing.... Sort of.

  • (cs) in reply to MAV
    MAV:
    Wonder what they're doing that needs super-extra-ultra random numbers?

    Super extra ultra random security algorithms of course.

  • AdT (unregistered)

    This code is not so bad. It could be improved, of course. For one, the number of decimal points should be randomized as well. One is so very predictable.

    Second, it should throw random exceptions with randomized lorem ipsum error messages to throw off malicious callers.

    Third, the number system should be randomized, using a random alphabet and a random parse function instead of Double.parseDouble. This parse function should pretend to parse the input, but may randomly return something else entirely, like the above mentioned 999999. The caller can never be sure what's actually returned. You cannot be too paranoid after all.

    And now for something completely different...

    Melchett: Now, Field Marshal Haig has formulated a brilliant tactical plan to ensure final victory in the field

    Blackadder: Would this brilliant plan involve us climbing over the top of our trenches and walking, very slowly towards the enemy?

    Darling: How did you know that Blackadder? It's classified information

    Blackadder: It's the same plan we used last time, and the seventeen times before that

    Melchett: E-e-exactly! And that is what is so brilliant about it. It will catch the watchful Hun totally off guard. Doing exactly what we've done eighteen times before will be the last thing they expect us to do this time.

  • China (unregistered)

    Saw this in a C++ cookbook once:

    1. generate lots of random numbers (e.g. 1000)
    2. put those random numbers into an array
    3. when you need a random number 3.1) generate a random number in the range 0-array.size 3.2) use the number in the array as your random number, scaling as necessary 3.3) generate a new random number for that place in the array

    Use the same singleton random number generator for all steps - takes advantage of 'random number generators get more random over time'.

    Discuss.

  • Not very random at all (unregistered) in reply to Erik

    Jukebox in a pub played the least-played tracks when nobody put any money in - sort of a punishment for not enriching the jukebox company. Those were the 3 most played songs on the machine.

  • Some guy (unregistered)

    A secondary WTF is inefficient object/memory usage. Why isn't he passing the StringBuilder object to the private methods?!

  • dusoft (unregistered) in reply to MAV

    that's randomly secret.

  • wtfpimp (unregistered)

    Haha... the best part is where they go (rand * 100) * rand thereby totally ruining an equal distribution. Fools!

  • James (unregistered)

    Way back, many years ago, a friend of mine in college was stumped on a multiple choice test. So, he pulled out his dice bag, snagged a d4, and randomly answered some questions.

  • Cris (unregistered)

    Have they heard of /dev/urandom?

  • Richard Neill (unregistered)

    Well, it does do at least 2 slightly "useful" things:

    (1)It doesn't actually do any real harm by discarding entropy.

    (2)It changes the distribution from which the random numbers are drawn, from linear to (truncated) logarithmic.

  • iMalc (unregistered)

    Truly astounding!

    Quadratic distribution of the number of digits??? Where do people come up with this stuff...

  • iMalc (unregistered) in reply to Richard Neill
    Richard Neill:
    Well, it does do at least 2 slightly "useful" things:

    (1)It doesn't actually do any real harm by discarding entropy.

    (2)It changes the distribution from which the random numbers are drawn, from linear to (truncated) logarithmic.

    Wrong. It does harm by shortening the length of the period until repetition of the pseudo random number sequence.

  • Bozo (unregistered) in reply to APH

    Shes friggin hot eh

    (don't tell my gf i just said that)

    :]

  • Bozo (unregistered) in reply to Bozo
    Bozo:
    Shes friggin hot eh

    (don't tell my gf i just said that)

    :]

    the irish i were drunk chick i mean ;]

  • Raw (unregistered) in reply to snoofle
    Hi there - OP here. I can't believe nobody mentioned that no routine that depends upon a random number generator can ever really be any more random than the underlying generator being used. In other words, assuming that the routine is implemented perfectly (as many have pointed out, it's not), it can never be any more random than: Math.random()

    Actually, it can, and this algorithm actually does it, in a extremely backwards way.

    What am I talking about?

    Well, most random number generators I've seen in various languages have a limited resolution. Just because they generate a random number with a bunch of decimals does not mean that they are able to generate every number in that interval. Sure, if you are just goint to scale it up to 1-100, it's no problem, but once you try to scale it up to, say 1-1000 000, you'll notice that, no matter how long you run them, some results will never, ever show up. In some cases, it's even noticable in a scale of 1-10 000 or less.

    OK, I admit, I've not tried it to the point of "never ever", but close enough. In most cases, you can even see patterns where these "holes" are going to appear. For instance, in some archaic version of C, getting random X and Y coordinates and plotting them on a white screen as black pixels generated a black screen with thin white stripes going diagonally down the screen.

    If you need such a resolution, another algorithm is needed. One variant is the one used here, to piece it together from random digits, as that only relies on having a resolution capable of handling ten cases.

    Another, variant, which is faster and simpler, but not guaranteed to be perfect, is to add a bunch of random numbers and wrap if they overflow. This can be made less likely to have holes by adding gradually smaller numbers, thus using the sufficient resolution of a smaller span to plug the holes. This algorith still can't guarantee an even distribution of all results, but at least all results are likely to appear in the resulting data set if run long enough.

    In other words, the thought behind the code in this WTF is sound, but the implementation of it is effed up.

  • Tiran Kenja (unregistered)

    Hmm.

    I suppose java.security.SecureRandom wasn't random enough either.

    Maybe it's time to build an external USB random generator. I'm thinking something that actually throws a dice and reads the output ;) Anyone who REALLY wants random numbers would have to get one.

  • N Morrison (unregistered)

    The greatest WTF in this is that the code author doesn't know that attempts to create more random numbers almost always result in numbers that are less random - unless you are Knuth. Similarly, attempts by the untrained to write sort routines usually result in a bad bubble sort.

  • Jos (unregistered)

    I know how to make this really random! Let a 2 year old (or similar, like a monkey wih darts) shuffle the array with digits! Now THAT would really achieve randomness...

  • (cs)

    I'm tired of these novice approaches to random number generation. Here's how you do it:

    1. get a (pseudo)random number.
    2. Multiply by the number of degrees of the angle that Venus , Hermes and Earth form at that moment. Needless to say we're talking about the angle at the Earth node of the triangle.
    3. Subtract the the number of geese presently in flight in your country's air space.
    4. Add the number of milliliters of gas present in Bill Gates' lower intestine.
    5. Divide by the distance from your PC (front left-hand corner of case) to Neil Armstrong's footprint on the moon (toes). Distance to be measured in number of Hindenberg zeppelin lengths (pre-crash).
    6. Add the chances of you marrying a supermodel.
    7. Multiply by the number of Google hits for the word "Nazi".
    8. Random number!!

    Amateurs...

  • Anonymous (unregistered) in reply to bramster
    bramster:
    I like to sort my random numbers.
    And don't forget to use the "random sort" algorithm:
    void sort(List numbers) {
        do shuffle(numbers);
        while (!sorted(numbers));
    }
    
    void shuffle(List numbers) {
        // typical algorithm to shuffle the list of numbers,
        // calling rand() to make it result random
    }
    
    boolean sorted(List numbers) {
        // check if the list of numbers is in sorted order;
        // if so, return true; else return false
    }
    

    :D

  • Anonymous (unregistered) in reply to yer mom
    yer mom:
    /**
     * We all know that random number generators aren't truly random.
     * This function generates random numbers a bit more randomly by using a hardware source.
     */
    int random() {
        FILE* fp;
        char count;
        float final = 0;
    
    Well... leaving out the =0 part would make the result more arbitrary (but not more random)...
    yer mom:
        char i;
    
    fp = fopen("/dev/null", "r"); /* open hardware source */
    count = fgetc(fp); /* more randomly */
    for (i = 0; i < count; i++) {
        final *= ((float)fgetc(fp)) / 255.0;
    };
    

    };

    Um... with a compiler that doen't warn you against missing return statements, you'll get quite arbitrary (but not random) return values from this function.

  • Anonymous (unregistered) in reply to kw
    kw:
    So, there is a 1 in 100 chance that the value left of the '.' is 0, and there is a 1 in 100 chance that the value left of the '.' will range between 1*10^100 to 9.999...*10^10 ?

    Does true randomness typically lean towards smaller values?

    But random =/=> uniform distribution!

    What do you mean "true randomness"? Guassian noise (as you would get with any physical measurement) is not "true randomness"?

Leave a comment on “Random Stupidity”

Log In or post as a guest

Replying to comment #:

« Return to Article