Showing posts with label BASIC. Show all posts
Showing posts with label BASIC. Show all posts

Tuesday, February 12, 2013

HOWTO Make a Quick and Dirty (Pseudo)Random Number Generator

If you ever need to build your own quick and dirty (pseudo-)random number generator it actually isn't that hard. This generator is used in various real-world systems:
  • Visual Basic (to version 6)
  • A few ANSI C implementations, including glibc
  • Java's Random library
The implementation will iterate over all numbers [0,m) when using proper a, m ,c's. 1

Implementation

#include <stdio.h>
#include <unistd.h>

const long m = 4294967296; // 2 ^ 32
const long a = 1103515245;
const long c = 12345;

long lastX = 0;

long nrandom() {
lastX = (a * lastX + c) % m;
return lastX;
}

void seed(int num)
{
lastX = num;
}

int main()
{
int i;

seed(getpid());

for(i = 0; i < 1000; i++)
printf("%li\n", nrandom());
}
Note that this implementation only generates m pseudorandom numbers, in this case 4,294,967,296; so if you need more, you'll want to use a different algorithm.

  1. These conditions require some discrete mathematics that are too long to go in to here; it involves coprime numbers and recurrence relations. (Please point out if I've missed some simple explaination in the comments, I'm fairly new to this!)

Saturday, February 26, 2011

TI BASIC

I just dug out my old TI-83 Plus and was poking around the PRGM menu and found a few old programs that I had made.  Most of them were little helper programs that I created while the teacher was lecturing in my tenth grade pre-calculus class (I didn't take calculus until three years later, by then most of it was gone).

I had learned BASIC two years prior to learning TIBASIC, in an old math textbook that a teacher of mine had collected.  My original programs were written on a sheet of lined paper, and did simple things like solve triangles.  I was unable to find an suitable interpreter as BASIC had taken its leave years prior, I was simply born about ten years too late.

A freshman in that class (who was a genius and later became a dear friend of mine), was very patient in teaching me the essentials of the language, I started off with a few simple things such as making the program distributed by the teacher to solve quadratic equations run twice as fast.  I also made a minesweeper, but that seems to have disappeared off the calculator.  Later on I also made PONG, but this too has gone (PONG ran very slowly, but none-the-less worked).  There was another game I made that made you race around the screen attempting to collect items...

Anyhow that is enough reminiscing for today :)