What is the most efficient way to generate a random binary object given a number of bits? I understand that the crypto:rand_bytes function would be an option, but the bit count must not necessarily be a multiply of 8.
rand_bits(Bits) ->
Bytes = (Bits + 7) div 8,
<<Result:Bits/bits, _/bits>> = crypto:rand_bytes(Bytes),
Result.
One way that you will be able to do it is:
<<(rand:uniform(MaxNum)):(rand:uniform(MaxBits))>>
Or same way if you wish to use the crypto module:
<<(crypto:rand_uniform(MinNum, MaxNum)):(crypto:rand_uniform(MinBits, MaxBits))>>
Related
There is a variable first_variable which is always a mod of some number, mod_value.
In every step first_variable is multiplied with some number second_variable.
And the range of all three variables is from 1 to 10^18.
For that I build a formula,
first_variable = ((first_variable%mod_value)*(second_variable%mod_value))%mod_value
But this gives a wrong answer,
For example, If first_variable and second_variable is (10^18)-1 and mod_value = 10^18
Please suggest me method, so that first_variable will always give right answer.
Seems you are using a runtime where arithmetic is implemented using 64-bit integers. You can check this using multipliers like 2^32: if their product is 0, my guess is true. In that case, you should switch to an arbitrary long arithmetic implementation, or at least one that is much longer than the current one. E.g. Python supports integers up to 2^1016 (256^127), same for Erlang.
I've seen in comments you use C++. If so, look for GMP library and analogs. Or, if 128 bits is enough, modern GCC support it through own library.
This is basically overflows, so you should either use different value for mod_value (up to 10^9) or limit the range for first value and second value.
Your number is O(10^36) which is O(2^108) which cannot fit in any primitive data type in languages like java or C++. Use BigInt in C++ or Java or use numpy in python to get over it.
I have an array of 10 elements. How do I output these in random order without repeating.
For a testbench, use the OSVVM random library to generate random indexes into your array. Or you could shuffle it (using the Fischer-Yates Algorithm in concert with the random library).
If it's something you need to synthesize, then put the array into a RAM block, and generate random addresses (for example using a linear feedback shift register).
Be aware that none of these is properly random, only pseudo-random. If you're attempting anything remotely cryptographic, they are unlikely to be what your want.
For testbenches, OSVVM's RandomPkg makes this easy.
library osvvm ;
use osvvm.RandomPkg.all ;
...
RandProc : process
variable RV : RandomPtype ;
variable IndexVals : integer_vector(0 to 9) := (others => integer'low) ;
begin
for i in IndexVals'range loop
-- min max ExcludeList
IndexVals(i) := RV.RandInt( 0, 9, IndexVals) ;
end loop ;
The problem gets more interesting if successive randomly generated permutations of 10 elements need to be different from the previous one. For that I would use the coverage model. Although, 10 is around the maximum number of permutations I would want to do this way though as there are n! permutations and the coverage model will require storage for each permutation generated.
A good way to get close to randomness is by using a linear feedback shift register.
http://en.wikipedia.org/wiki/Linear_feedback_shift_register
If this is for simulation only, you can use the uniform procedure from ieee.math_real to get a real number between 0 and 1, and scale it to the index range of your array.
I want to represent 10000 bits of information.(Each can be either one or zero). Is there any way I can do this?
Wikipedia explains a bit hack to achieve this. But then it asks me to have a number that's as large as 2^10000 for storing 10000 bits.
Is there some way that's tractable even for storing large number of bits?
As wikipedia explains, a bit field is an appropriate choice here. a bit field that can hold 10,000 bits has 2^10000 states.
A good choice for doing this (given that integers are 32/64 bits) is a bit vector, which is asked about and explained in excruciating detail here:
bit vector implementation of set in Programming Pearls, 2nd Edition
The general idea is that you use an array of integers which are used as bit fields.
You can make bool take 1 bit for example if you have a bunch of them eg. in a struct, like this:
struct A
{
bool a:1, b:1, c:1, d:1, e:1;
};
Above method won't be useful if the number of variables are large. So instead create an array of integers of size 10000/4*8. It will create exactly 10000 bits. Now you can access each bit by using offset and << or >>(like for accessing 55th bit, use floor(55/4*8) and >>55%32. you can reach that bit).
In C++ you can do this very simply, using one of two standard library containers:
std::vector<bool>
This specialization of a standard vector acts (almost) like any other vector, but compresses its contents to one bit per element. Aside from enjoying that fact, you can just treat it like a vector:
// Create a vector of 10000 booleans
std::vector<bool> lots_of_bits(10000);
// Set all the odd ones to true
for (int i = 1; i < lots_of_bits.size(); i += 2) {
lots_of_bits[i] = true;
}
// Add another 100 trues at the end
for (int j = 0; j < 100; ++j) {
lots_of_bits.push_back(true);
}
// etc.
std::bitset<N>
The "new, improved" bit vector which does not pretend to be a standard container. In particular, it's of fixed size and you need to know the size at compile time. That can be a bit restrictive, but it's otherwise a pretty useful class. Like std::vector<bool>, it implements the [] operator for getting and setting individual bits. It also supports the bitwise logical operators &, |, '^' and ~ (and, or, xor and not), as well as left and right bitshifts, and some other utilities.
Is your concern that accessing bit number n requires shifting n times? If so, you can make the problem tractable by dividing your 10,000 bits into 10,000 / 8 buckets using an array of characters (assuming C or C++ here). Now you can access bit number n by figuring out what bucket that bit is in (n / 8) and then what position within the bucket (n % 8). Then you just do the masking. No extra storage required (except the padding at the end, so a few extra bits if you don't have a perfect multiple of 32 bits).
I need a random number generation algorithm that generates a random number for a specific input. But it will generate the same number every time it gets the same input. If this kind of algorithm available in the internet or i have to build one. If exists and any one knows that please let me know. (c, c++ , java, c# or any pseudo code will help much)
Thanks in advance.
You may want to look at the built in Java class Random. The description fits what you want.
Usually the standard implementation of random number generator depends on seed value.
You can use standard random with seed value set to some hash function of your input.
C# example:
string input = "Foo";
Random rnd = new Random(input.GetHashCode());
int random = rnd.Next();
I would use a hash function like SHA or MD5, this will generate the same output for a given input every time.
An example to generate a hash in java is here.
The Mersenne Twister algorithm is a good predictable random number generator. There are implementations in most languages.
How about..
public int getRandonNumber()
{
// decided by a roll of a dice. Can't get fairer than that!
return 4;
}
Or did you want a random number each time?
:-)
Some code like this should work for you:
MIN_VALUE + ((MAX_VALUE - MIN_VALUE +1) * RANDOM_INPUT / (MAX_VALUE + 1))
MIN_VALUE - Lower Bound
MAX_VALUE - Upper Bound
RANDOM_INPUT - Input Number
All pseudo-random number generators (which is what most RNGs on computers are) will generate the same sequence of numbers from a starting input, the seed. So you can use whatever RNG is available in your programming language of choice.
Given that you want one sample from a given seed, I'd steer clear of Mersenne Twister and other complex RNGs that have good statistical properties since you don't need it. You could use a simple LCG, or you could use a hash function like MD5. One problem with LCG is that often for a small seed the next value is always in the same region since the modulo doesn't apply, so if your input value is typically small I'd use MD5 for example.
How do I quickly generate a random prime number, that is for sure 1024 bit long?
Generate 1024 random bits. Use a random source that is strong enough for your intended purpose.
Set the highest and lowest bits to 1. This makes sure there are no leading zeros (the prime candidate is big enough) and it is not an even number (definitely not prime).
Test for primality. If it's not a prime, go back to 1.
Alternatively, use a library function that generates primes for you.
Use a library function, such as OpenSSL. There's no need to write this yourself.
Example: http://ardoino.com/7-maths-openssl-primes-random/
The above link doesn't work so you can use this archive link.
1024 is a lot.
Are you sure a probabilistic prime won't do?
Probabilistic prime generator is part of JDK
You do not specify a context/language/platform.. if you'd like to use unix/linux-like system and shell, you might consider a solution involving OpenSSL version >= 1.0.0:
$ openssl prime -generate -bits 1024
140750877582727333214379261853877378646889234118675380673028200387281415297520423589261211081966230040412916644372766351028035798201654335110081318739796178745233127842988596480299276295476504358587725867882394416543075082108266054273016211760684113070285409887820598314292803190900634009988950624354964653677
If you got the same result, something is very wrong with the universe.
Add -hex option if you like hexadecimal system.
To trade memory for speed you could just generate them and store them in a list and then randomly pick one.
Edit:
Naturally you can't generate them all so the best you could achieve is pseudo randomness at a high memory cost. Also this isn't good if you want it for security.
In PARI/GP:
randomprime([2^1023,2^1024])
If you'd like to do this in 'library mode'
#include <pari/pari.h>
// ...
randomprime(mkvec2(int2u(1023), int2u(1024)))