Jump to content

A simple random number generator based on "Middle Square" method.


TheDcoder
 Share

Recommended Posts

Hello! :bye:

After watching a whole day of "Journey into cryptography" at Khan Academy, I have got to know the secrets behind some sneaky things! :P. This is one of em', A PRNG (Pseudo Random Number Generator). Its features (atleast what I believe) are:

  1. Simple, short and crappy.
  2. Great for beginners who are baffled by the mechanics of random number generation in computers!
  3. Support for custom seeds! :P
  4. EIGHT DIGITS OF RANDOMNESS!!! :shocked:
  5. Unlike all other PRNGs, This one is predictable :sorcerer:
  6. 1000 possible PRNs when using @MSEC as the seed.
  7. No option for min or max, the min is 10000000 and the max is 99999999.
  8. The Unlicensed 196px-PD-icon.svg.png.
#cs LICENSE
This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <http://unlicense.org/>
#ce LICENSE

; #FUNCTION# ====================================================================================================================
; Name ..........: MiddleSquareRandom
; Description ...: Pseudo-random number generator based on the infamous "Middle Sqaure" method.
; Syntax ........: MiddleSquareRandom([$iSeed = @MSEC])
; Parameters ....: $iSeed               - [optional] A seed for generation of the random number. Default is @MSEC.
; Return values .: A pseudorandom 8 digit integer.
; Author ........: John von Neumann
; Modified ......: Damon Harris (TheDcoder) - Conversion into AutoIt and simplification + further crappification.
; Remarks .......: Fun Fact - The output is based on the $iSeed passed, Same $iSeed = Same pseudo-random number.
; Related .......: Random()
; Link ..........: https://en.wikipedia.org/wiki/Middle-square_method
; Example .......: ConsoleWrite(MiddleSquareRandom() & @CRLF)
; ===============================================================================================================================
Func MiddleSquareRandom($iSeed = @MSEC)
    Local Const $TURNS = 8
    Local $sRandomNumber, $sSeed
    For $iTurn = 1 To $TURNS
        $iSeed = $iSeed * 2
        $sSeed = String($iSeed)
        $sRandomNumber &= StringMid($sSeed, Ceiling(StringLen($iSeed) / 2), 1)
    Next
    Return Int($sRandomNumber)
EndFunc

 

Enjoy your numbers, TD ;).

P.S NEVER USE THIS FUNCTION IN A REAL WORLD IMPLEMENTATION OF SOMETHING WHICH USES RANDOM NUMBERS!!! THIS ONE IS VERY UNSUITABLE FOR THAT PURPOSE! READ THE POSTS BELOW FOR MORE INFORMATION.

Edited by TheDcoder
Added P.S

EasyCodeIt - A cross-platform AutoIt implementation - Fund the development! (GitHub will double your donations for a limited time)

DcodingTheWeb Forum - Follow for updates and Join for discussion

Link to comment
Share on other sites

That is flawed and terribly weak. Your algorithm isn't even midddle square but middle n*256.

Read up this botleg extract from TAOCP about PRNGs: https://vk.com/doc10903696_194276164?hash=1fc65ed563521b76e6&dl=ebca64d98d089930e0

BTW all serious PRNG are predictable in that there is nothing random in their code. This is even a requirement to assess anything about the algorithm. You'd have a fairly hard time to prove its pseudo-randomness usefulness: when you say it produces 8 random digits (here you mean pseudo-...) at each invokation, realize that this is a bold statement you just can't prove anyhow. Assertion #7 is also plain wrong.

#include <Array.au3>

Local $a[100]
For $i = 0 To UBound($a) - 1
    $a[$i] = MiddleSquareRandom($i)
Next
_ArrayDisplay(_Array1DToHistogram($a))

Func MiddleSquareRandom($iSeed = @MSEC)
    Local Const $TURNS = 8
    Local $sRandomNumber, $sSeed
    For $iTurn = 1 To $TURNS
        $iSeed = $iSeed * 2
        $sSeed = String($iSeed)
        $sRandomNumber &= StringMid($sSeed, Ceiling(StringLen($sSeed) / 2), 1)
    Next
    Return Int($sRandomNumber)
EndFunc

 

Edited by jchd

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

Hmm... Yes, you are correct. That code is flawed and is not even middle square method... As I have expected, I am not good at this!

I will try to wrap my brain around this again, so expect a retouch to the code soon...

EasyCodeIt - A cross-platform AutoIt implementation - Fund the development! (GitHub will double your donations for a limited time)

DcodingTheWeb Forum - Follow for updates and Join for discussion

Link to comment
Share on other sites

Please don't take this bad: I aint bashing you personally, just trying to put facts straight. Take the time to read from the link provided, you'll learn a lot!

Coming up with a robust PRNG is very hard and even brilliant professionnals have been bitten by their invention. Analyzing a PRNG for plausible randomness requires a very strong background in number theory and analysis. Proving anything in this area is utterly difficult and subtle. Cryptographically secure PRNGs are few and the exclusive domain of seasonned specialists.

My best advice is too rely only on methods proven correct (so far) by a large community of mathematicians, just like the implementation of Random() that AutoIt offers. I'm not saying that nobody is entitled to experiment new things, but please don't publish raw code as Example, along with bold, unproven or false statements. And submit your homebrew PRNG to a decent series of standard randomness tests before believing/claiming anything.

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

1 minute ago, jchd said:

Please don't take this bad: I aint bashing you personally, just trying to put facts straight.

No worries :D, I always appreciate input no matter how its presented to me :).

3 minutes ago, jchd said:

Take the time to read from the link provided, you'll learn a lot!

Thanks for the link! but I am not really very serious about this implementation of a PRNG :(, I only did this as an exercise...

I know that this PRNG is highly unsuitable for any real world use... and I am not planning to make it a PRNG which can be used in Cryptographic operations!! I know that its VERY HARD :shocked:. I just submitted this piece of code for someone who is looking to get started.

I have decided to add a big red WARNING message near the code :).

EasyCodeIt - A cross-platform AutoIt implementation - Fund the development! (GitHub will double your donations for a limited time)

DcodingTheWeb Forum - Follow for updates and Join for discussion

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...