I have used the code provided by Cornstalk in the link:
How to generate a random number in C++?
It works fine if implemented within a function in my class, but I need to get random numbers in another function in that class, so the variable RNDRange (see below) must be defined at class-level. I then need to initialize it as below in function A, so I can call the variable in function B.
std::uniform_int_distribution RNDRange(0, MinimumNumberOfAnimals - 1);
With reference to the code below:
Made
std::mt19937 RandomNumberGenerator;
a class level variable and commented the same within function A. Works fine.
Tried to define RNDRange at class level so I can then initialize it in function A, and call RNDRange(RandomNumberGenerator) in function B. Since I am not able to define RNDRange at class level (don't know how) and then initialize it in function A, calling RNDRange(RandomNumberGenerator) in function B is not possible.
std::mt19937 RandomNumberGenerator; // Mersenne Twister pseudo-random generator of 32-bit numbers with a state size of 19937 bits
RandomNumberGenerator.seed(std::random_device()());
std::uniform_int_distribution<std::mt19937::result_type> RNDRange(0, MinimumNumberOfAnimals - 1); // Seeds a random number generator for the range between zero and MinimumNumberOfAnimals
double MyRnd;
for (int i = 0; i < 10; i++) // tests
{
MyRnd = RNDRange(RandomNumberGenerator);
MyRnd = MyRnd / MinimumNumberOfAnimals;
// Use MyRnd
}
Works fine within function A, but I can't understand how to define RNDRange at class level and then initialize with (0, MinimumNumberOfAnimals - 1) in function A. MinimumNumberOfAnimals is only defined in the constructor of the class.
Related
I am writing a unit test for a function and in the real function I have:
rng = default_rng()
...
... # a little while later
while N<50:
...
idx = rng.integers(100)
How do I mock out either the variable idx or the call to rng.integers? In other words, I'd like to make idx pull from a simple ordered list [0, 1, 2, ...].
Every time I try #mock.patch('numpy.random.default_rng', side_effects=[0, 1, 2, ...]) decorating the test function, the code 'runs' but doesn't do what I am hoping. If I replace the above to 'numpy.random.default_rng.integers I get an error that says default_rng has no attribute integers (I believe bc it is a generator object). I've tried a number of different iterations using #mock.patch.object but still to no avail.
There are some problems with your patching. First, you are obviously using from numpy.random import default_rng, so you have to patch the default_rng instance in your module - see where to patch.
Second, integers is called on the instance of default_rng, not on the class, so you first have to get the instance of the mock, with is done via return_value.
And third: it's called side_effect, not side_effects (though that may just be a typo in your question).
So a working version could look like this (adapted a bit to actually be able to test something):
sut.py
from numpy.random import default_rng
def get_random():
rng = default_rng()
idx = 0
while idx < 50:
idx = rng.integers(100)
return idx
test_sut.py
#mock.patch('sut.default_rng')
def test_get_random(mocked):
mocked.return_value.integers.side_effect = range(60)
assert do_something() == 50
While using a random number generator (RNG) with a given seed several times (ie. each time calling setSeed() with the same seed to start over), I have encountered some deviation in the sequence of numbers generated on each pass. After banging my head against the wall a few times I found the reason to be this:
box2d's World.createBody() calls LongMap.put(), which calls LongMap.push(), which calls MathUtils.random() inside a while loop.
To my knowledge particle effects call MathUtils.random() too.
So how can I trust a sequence of numbers to always repeat itself if LibGDX internally uses the same static RNG instance and therefor could mess up the sequence?
How am I supposed to know exactly where and when MathUtils.random() gets called outside my code?
As noted by #Peter R, one can create one's own RNG which guarantees nothing would interfere with the sequence of numbers.
Either Java's Random can be used:
import java.util.Random;
private Random random = new Random();
or RandomXS128 that is used by MathUtils (which extends Java's Random but is faster):
import com.badlogic.gdx.math.RandomXS128;
private Random random = new RandomXS128();
The convenient wrapper methods (random() signatures) in MathUtils can be used too (copied into one's own class) as per needed, whether static or not. eg:
/** Returns a random number between start (inclusive) and end (inclusive). */
public int random (int start, int end) {
return start + random.nextInt(end - start + 1);
}
/** Returns a random number between start (inclusive) and end (exclusive). */
public float random (float start, float end) {
return start + random.nextFloat() * (end - start);
}
For myself I'm still befuddled as to why MathUtils provides a shared RNG to be used both internally and externally, which makes using it with a seed unsafe, and with no mention of that in the comments.
But the above workaround should be satisfactory to anyone who is not as petty as I am.
I was wondering if you know of any programming language in which we can pass parameters inside method name. I'm guessing this could improve the code readability. I.e.
Lets say I want to multiply to integers in a method. Normally my method declaration would be something like:
function multiply(int a, int b){
return a*b;
}
However, it may be nice to be able to define it this way also:
function multiply (int a) times (int b){
return a*b;
}
This way, we could make a more explicit call in the code by calling:
var c = multiply(4)times(2);
This could have a greater impact on more complicated code and programming syntax.
Do you know if something like this exists?
Of course, there is Smalltalk which is really expressive with its keyword messages...
n := collection size // 2.
head := collection copyFrom: 1 to: n.
Other than that, you will find that in ADA or Python, and probably some others you can prefix each argument with a key (which should match the function parameter names)...
I have a package containing a number of packed-struct typedefs and I am trying to write a CONSTANT function to tell me the maximum bit width of these structs. Each struct has an explicit message_type which is enumerated. I believe the below function I have written should be interpreted by the compiler as constant, but I am getting the error "(vlog-2118) The function 'get_max_message_length' is not a valid constant function" (this is in ModelSim).
Can anyone tell me why this function is not constant? After debugging I have determined that it is the enum method 'next()' that is causing it to be interpreted wrong. Any possible alternate solutions? Thank you in advance!
typedef enum logic [7:0]
{
MESSAGE_TYPE_0=0,
MESSAGE_TYPE_1=1,
MESSAGE_TYPE_2=2
} _MSGTYPE;
function integer get_message_length (_MSGTYPE message_type);
case (message_type)
MESSAGE_TYPE_0: return ($bits(message_0));
MESSAGE_TYPE_1: return ($bits(message_1));
MESSAGE_TYPE_2: return ($bits(message_2));
default: return 0;
endcase
endfunction
function integer get_max_message_length ();
automatic _MSGTYPE largest = largest.first();
automatic _MSGTYPE next = next.first();
next = next.next();
while (next != next.first()) begin
largest = get_message_length(largest) > get_message_length(next) ? largest : next;
next = next.next();
end
return get_message_length(largest);
endfunction
A constant function has certain restrictions - it must be a pure function (i.e. have no side effects and return the same value if called with the same arguments).
This restriction propagates, so your constant function can only call other functions that are also pure functions. The problem you have is that next.next() is not a pure function - it does not return the same value every time you call it.
Sadly the SystemVerilog LRM doesn't appear to define any pure mechanism for accessing enumerated values - for example this would work if it were possible: for (int i=0; i<enum.num(); i++) size=get_message_length(enum.item(i));
Off the top of my head I can't think of a neat way to do this. You could create a localparam which was an array of enum values and iterate over that but you'd have to write out the enum values again.
Let's assume that we have the list of loans user has like below:
loan1
loan2
loan3
...
loan10
And we have the function which can accept from 2 to 10 loans:
function(loans).
For ex., the following is possible:
function(loan1, loan2)
function(loan1, loan3)
function(loan1, loan4)
function(loan1, loan2, loan3)
function(loan1, loan2, loan4)
function(loan1, loan2, loan3, loan4, loan5, loan6, loan7, loan8, loan9, loan10)
How to write the code to pass all possible combinations to that function?
On RosettaCode you have implemented generating combinations in many languages, choose yourself.
Here's how we could do it in ruby :
loans= ['loan1','loan2', ... , 'loan10']
def my_function(loans)
array_of_loan_combinations = (0..arr.length).to_a.combination(2).map{|i,j| arr[i...j]}
array_of_loan_combinations.each do |combination|
//do something
end
end
To call :
my_function(loans);
I have written a class to handle common functions for working with the binomial coefficient, which is the type of problem that your problem falls under. It performs the following tasks:
Outputs all the K-indexes in a nice format for any N choose K to a file. The K-indexes can be substituted with more descriptive strings or letters. This method makes solving this type of problem quite trivial.
Converts the K-indexes to the proper index of an entry in the sorted binomial coefficient table. This technique is much faster than older published techniques that rely on iteration. It does this by using a mathematical property inherent in Pascal's Triangle. My paper talks about this. I believe I am the first to discover and publish this technique, but I could be wrong.
Converts the index in a sorted binomial coefficient table to the corresponding K-indexes. I believe it might be faster than the link you have found.
Uses Mark Dominus method to calculate the binomial coefficient, which is much less likely to overflow and works with larger numbers.
The class is written in .NET C# and provides a way to manage the objects related to the problem (if any) by using a generic list. The constructor of this class takes a bool value called InitTable that when true will create a generic list to hold the objects to be managed. If this value is false, then it will not create the table. The table does not need to be created in order to perform the 4 above methods. Accessor methods are provided to access the table.
There is an associated test class which shows how to use the class and its methods. It has been extensively tested with 2 cases and there are no known bugs.
To read about this class and download the code, see Tablizing The Binomial Coeffieicent.
It should not be hard to convert this class to the language of your choice.
To solve your problem, you might want to write a new loans function that takes as input an array of loan objects and works on those objects with the BinCoeff class. In C#, to obtain the array of loans for each unique combination, something like the following example code could be used:
void LoanCombinations(Loan[] Loans)
{
// The Loans array contains all of the loan objects that need
// to be handled.
int LoansCount = Loans.Length;
// Loop though all possible combinations of loan objects.
// Start with 2 loan objects, then 3, 4, and so forth.
for (int N = 2; N <= N; N++)
{
// Loop thru all the possible groups of combinations.
for (int K = N - 1; K < N; K++)
{
// Create the bin coeff object required to get all
// the combos for this N choose K combination.
BinCoeff<int> BC = new BinCoeff<int>(N, K, false);
int NumCombos = BinCoeff<int>.GetBinCoeff(N, K);
int[] KIndexes = new int[K];
// Loop thru all the combinations for this N choose K.
for (int Combo = 0; Combo < NumCombos; Combo++)
{
// Get the k-indexes for this combination, which in this case
// are the indexes to each loan in Loans.
BC.GetKIndexes(Loop, KIndexes);
// Create a new array of Loan objects that correspond to
// this combination group.
Loan[] ComboLoans = new Loan[K];
for (int Loop = 0; Loop < K; Loop++)
ComboLoans[Loop] = Loans[KIndexes[Loop]];
// Call the ProcessLoans function with the loans to be processed.
ProcessLoans(ComboLoans);
}
}
}
}
I have not tested the above code, but in general it should solve your problem.