How to generate a random number within a range in D - random

How do i generate a random number within a range in D?
int number = randomNumber(0,1);
Something like this. So number would be equal to either 0 or 1.

int number = uniform!"[]"(0,1);
http://dlang.org/phobos/std_random.html#.uniform

Related

Why use modulo instead of division for generating a random number within a range

I understand that random number generators use the modulo operator to generate a random number within a range. What I am curious is why is it better to use that than division. For example, I could generate a random number in the range of min to max by using the equation:
(max-min) * random_number/maximum_possible_number + min
where maximum_possible_number is the largest possible number that can be represented.
This works because random_number/maximum_possible_number generates a number between 0 and 1. When that's multiplied by max-min it is a number between min and max.
Why is using a modulo algorithm better than this algorithm?
Edit:
To test this algorithm I wrote the following Matlab code to randomly generate 10000 numbers between 0 and 1 bit by bit and plot them:
clear all;
numBits = 32;
numbersToGenerate = 10000;
% Generate 10000 random numbers between 0 and 1
for i = 1:numbersToGenerate
bits = randi([0 1], numBits, 1);
s = 0;
maxNumber = 0;
for bit = 1:numBits
s = s + bits(bit)*2^bit;
maxNumber = maxNumber + 2^bit;
end
number(i) = s/maxNumber;
end
% Break into sections and count numbers within each section
size = .01;
for s = 0:size:1-size
sections(int8(s/size)+1) = sum(number>s & number<s+size);
end
plot (0:size:1-size, sections);
xlabel('Number');
ylabel('Count');
The output looks like this:
Edit2:
(To give a more detailed explanation about what is happening in my code). I generate 10000 random numbers. This is done by generating 32 bits using the randi() function (for each number). While this is being done the largest possible number is also generating (32 1's in a row). Then the random number is calculated by dividing the random 32 bits by the largest possible number (32 bits of 1).

Generate numbers where Each pair of adjacent digits also occurs in the original number

I would like to output all similar numbers of a number, where:
Each pair of adjacent digits also occurs in the original number.
The new numbers has the same number of digits as the original
The order in which the numbers are generated doesn't matter
For example suppose I'm given a number 12314, then I have the pairs 12,23,31,14
I should generate [12314,31231,12312,23123].
If I'm given numbers like 52 or 11111 then I should get only 52/11111 respectively.
I have already written code that generates the pairs [12,23,31,14], and generate all possible permutations of this list of pairs. However, the permutations produce numbers that are longer than the original, and many of these permutations are invalid. For example, when 1214 appears in the permutation, the permutation is not valid since "21" is not in the original number.
I'd like to know how to proceed. It looks very inefficient to filter out the invalid ones from all permutations.
You could use recursion to generate the required numbers.
The idea is to maintain only valid numbers at any stage and to display when the original length and length of your number are equal.
// pairs[i][j] is true if j is immediately after i in the original number
bool pairs[10][10];
// curr_num is a valid number according to the constraint given
// curr_len is the number of digits in curr_num
// length is the number of digits in the number given
void generate(int curr_num, int curr_len, int length){
if(cur_len == length){
display curr_num;
} else {
// extract last digit & check what digits can follow that
int last = curr_num % 10;
for(int i = 0 ; i <= 9 ; i++)
if(pairs[last][i])
generate(curr_num * 10 + i , curr_len + 1, length);
}
}
for(digit in original_number)
generate(digit, 1, length);
You could optimize the code by making pairs an adjacency list than an adjacency matrix.

How to generate a random number from a random bit generator and guarantee termination?

Assuming I have a function that returns a random bit, is it possible to write a function that uniformly generates a random number within a certain range and always terminates?
I know how to do this so that it should (and probably will) terminate. I was just wondering if it's possible to write one that is guaranteed to terminate (and it doesn't have to be particularly efficient. What complexity would it have?
Here is a code for the not always terminating version
int random(int n)
{
while(true)
{
int r = 0;
for (int i = 0; i < ceil(log(n)); i++)
{
r = r<<1;
r = r|getRandomBit();
}
if(r<n)
{
return r;
}
}
}
I think this will work:
Suppose you want to generate a number in the range [a,b]
Generate a fraction r in range [0,1} using a binary radix. That means generate a number of form 0.x1x2x3.... where every x is either a 0 or 1 using your random function.
Once you have that, you can easily generate a number in the range [0,b-a], by computing ceil(r*(b-a)), and then simply add a to get a number in range [a,b]
If the size of the range isn't a power of 2, you can't get an exactly uniform distribution except through what amounts to rejection sampling. You can get as close as you like to uniform, however, by sampling once from a large range, and dividing the smaller range into it.
For instance, while you can't uniformly sample between 1 and 10, you can quite easily sample between 1 and 1024 by picking 10 random bits, and figure out some way of equitably dividing that into 10 intervals of about the same size.
Choosing additional bits has the effect of halving the largest error (from true uniformity) you have to see in your choices... so the error decreases exponentially as you choose more bits.

Mathematically create a positive or negative one using a random number function

If I am in a coding language where I can create a random number for a given range (i.e. 0 to 50, or -30 to 751, etc.) How can I mathematically create a +1 or -1 (not a +1, 0, or -1) using only math and the random function.. no if statements.
Easy. random(0,1) * 2 - 1 will do it.
You could just get a random number and divide by the absolute value of itself. Something like the following in C#:
Random r = new Random();
int iNum;
int result;
iNum = r.Next(-30, 50); //put whatever range you want in here from negative to positive
result = iNum / (int)Math.Abs(iNum);

How to get a random number in pascal?

I want to get a random number in pascal from between a range. Basically something like this:
r = random(100,200);
The above code would then have a random number between 100 and 200.
Any ideas?
The built in pascal function only lets you get a number from between 0-your range, while i need to specify the minimum number to return
Just get a random number with the correct range (ie 100 to 200 would be range 100) then add the starting value to it
So: random(100) + 100 for your example
As already pointed out, you should use
myrandomnumber := random(span) + basenumber;
However, to get better quality random numbers, you should call
randomize();
once, on start of your application, to initialize the random number generator.
Couldn't you just declare a starting variable and an end variable and pass random those? e.g.
var
varMyRandomNumber, x, y := extended;
begin
x := 100;
y := 200;
varMyRandomNumber := random(x,y);
ShowMessage(IntToStr(varMyRandomNumber));
end;
?
There's a good example here of using a for loop to set starting and end values : http://www.freepascal.org/docs-html/rtl/system/random.html
Use RandomRange or RandomFrom:
function RandomRange(const aFrom: Integer; const aTo: Integer): Integer;
RandomFrom returns a random element from the array AValues. The return value has the same type as the type of the array elements.
first of all, i recommend you to use Randomize at the beginning of the program (it changes the algorithm of selecting the number).
To get a random number between some two numbers you need this:
Result:=Min+random(10000)mod max + 1;
I don't remember the maximum value for random, so you can change it (it don't changes anything).
By using 'mod' you get module from division Random and max. +1 is needed, because you never get the number that = max, only the number that =max-1, so you need to write +1.
Good luck!
You can make it like
Int:=Random(100);
it give's 100 random numbers.
then when you display it or use it just add 101 to that integer so its between 100 and 200

Resources