I'm student from Ariel University in Israel and I'm trying to implement Matlab RAND and RANDN in C# in such way that same input for Matlab and C# (with same seed) , Randn and Rand will give the same result in both languages.
for example:
In Matlab:
rand('seed',123)
disp(rand)
output: 0.0878
In C#:
Console.WriteLine(MyRand(123));
output: 0.0878
I think for implement this kind of functionality, I need to have the source code for RAND and RANDN in Matlab. Does anyone has this code and may share?
Thanks a lot,
Shimon
Doing:
>> s = RandStream.getGlobalStream()
s =
mt19937ar random stream (current global stream)
Seed: 0
NormalTransform: Ziggurat
Your given the random-number-generator algorithm and the transformation used to get normal distributed numbers.
Both are publicly available algorithms.
Google gives you e.g.:
http://www.math.sci.hiroshima-u.ac.jp/~%20m-mat/MT/MT2002/emt19937ar.html
and
http://www.jstatsoft.org/v05/i08/paper
describing both algorithms including reference / example implemenations.
Randn is as far as i know MarsenneTwister. To verify this i would first try to use the MarsenneTwister from Apache and check for similar results: http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/random/MersenneTwister.html
If so: Search for any implementation. This algorithm should be documented.
But seriously, if you type
edit rand.m
into the Matlab command window, and
edit randn.m
I think you will get as much information as the Mathworks publish about those functions. This information points towards the algorithms used and, for rand an implementation too.
As your question only mentions obtaining the same results, I would recommend one of the following:
Generate a lot of random numbers, then use them one by one in both programming languages.
Implement your own (simple) random generator in both languages.
Related
In my project i face a scenario where i have a function with numerous inputs. At a certain point i am provided with an result and i need to find one combination of inputs that generates that result.
Here is some pseudocode that illustrates the problem:
Double y = f(x_0,..., x_n)
I am provided with y and i need to find any combination that fits the input.
I tried several things on paper that could generate something, but my each parameter has a range of 6.5 x 10^9 possible values - so i would like to get an optimal execution time.
Can someone name an algorithm or a topic that will be useful for me so i can read up on how other people solved simmilar problems.
I was thinking along the lines of creating a vector from the inputs and judjing how good that vektor fits the problem. This sounds awful lot like an NN, but there is no training phase available.
Edit:
Thank you all for the feedback. The comments sum up the Problems i have and i will try something along the lines of hill climbing.
The general case for your problem might be impossible to solve, but for some cases there are numerical methods that can help you solve your problem.
For example, in 1D space, if you can find a number that is smaller then y and one that is higher then y - you can use the numerical method regula-falsi in order to numerically find the "root" (which is y in your case, by simply invoking the method onf(x) -y).
Other numerical method to find roots is newton-raphson
I admit, I am not familiar with how to apply these methods on multi dimensional space - but it could be a starter. I'd search the literature for these if I were you.
Note: using such a method almost always requires some knowledge on the function.
Another possible solution is to take g(X) = |f(X) - y)|, and use some heuristical algorithms in order to find a minimal value of g. The problem with heuristical methods is they will get you "close enough" - but seldom will get you exactly to the target (unless the function is convex)
Some optimizations algorithms are: Genethic Algorithm, Hill Climbing, Gradient Descent (where you can numerically find the gradient)
I have created a simple RBF network with a gaussian function by using,
RBFNetwork newNetwork = new RBFNetwork(28,14,1,RBFEnum.Gaussian);
I need to create a RBF Network with back propagation having 28 inputs and only one output giving 0 or 1 as a result.
I could not proceed further in training it with data sets.
Help needed.
I think your answer lies here..
http://massapi.com/class/org/encog/neural/rbf/RBFNetwork.java.html
Hope this helps You..Though it is in java u can understand the logic behind it
I think you should use EncogUtility.TrainConsole(), EncogUtility.TrainToError() or EncogUtility.TrainDialog() methods, if you don't want to make your own stopping strategy.
See EncogUtility for Javadocs, C# ones are close to. The only thing is that it uses not SCG internally but ResilientPropagation.
To construct a dataset you must have double[][] inputs and double[][] desired outputs of the same size and in the same order. Then the code looks so:
var trainingSet = new BasicMLDataSet(inputs, outputs);
EncogUtility.TrainConsole(network, trainingSet, 10 /*minutes training*/);
occupy a method made in migrating Visual Fox Pro emigrarlo to C #, the problem I have is how to know if the method in Visual Fox Pro:
Rand(intValue)
method is equal to dotNet:
Random r = new Random (intValue);
r.Next return ();
assuming that intValue = 971 the result generated in dotNET is 2027119, but I need to be equal to that return FoxPro.
Primary question:
how I can make sure I get the same result?
Secondary question:
Do you know of any online tool fox pro to prove that this method gives me result Rand ()?
Primary question: how I can make sure I get the same result?
So you want to guarantee that you get the same result... from two different random number generators... right.
intValue in your FoxPro example is a seed value. Why in the world would you need to guarantee that the two libraries use the same random number generator (HINT: They almost certainly do not). Seriously, if you are after random numbers, what difference does it make?
If you want a known series of numbers then you really don't want a random number at all. This boggles my mind. If your code is setup to expect a certain string of values from a random number generator then there is a bigger problem. You may as well just generate a map using the numbers from FoxPro and get the numbers from there.
The only way you will achieve this is create a Visual FoxPro COM object with a method that takes a seed value and returns the random number generated, then use that via COM Interop in C#.
There is NO WAY TO MAKE NATIVE C# DO THIS. So stop asking.
I'm not sure why you would want to do that but here is a Visual FoxPro Toolkit for .NET http://foxcentral.net/microsoft/vfptoolkitnet.htm its possible it might have the same rand generator function.
What you ask IS possible. You just can't use the generators provided to you by Foxpro and the .NET framework.
Most "random" number generators just generate sequence of numbers that "look" or "feel" random. They work like this (very simplified): Start with a "seed" value, apply a transform and generate a value, then apply the transform to this value and get next. Repeat as needed. The transform is such that you can expect the values to be uniformly distributed within a given segment, usually [0,1). I can explain this further, but there is plenty of literature around. Search for it.
Now, obviously, if you provide any given generator with the same seed, you will get the same sequence over and over again.
So, to obtain the result you want, you need to implement your own pseudo-random number generator in both VFP and C#. Keep in mind that there are things like difference in precision that could make successive calls to the generator, diverge.
Anyway, you will need an algorithm. Go here: use of D.Knuth pseudo-random generator
Hope this is still useful.
You can't. You are setting a seed value, but the chance that .NET and FoxPro is using exactly the same method to generate Random numbers is close to zero. But question is, why would you want this? Random is supposed to be random.
I have a set of values and I need to get the lambda for a Box-Cox equation. It's a normal curve (gaussian distribution). Does anyone know how to get optimal value for lambda in R, C#, MATLAB, or python or perl?
In R: package geoR, boxcox.fit
boxcox in the MASS package
Scipy has a lot of good curve fitting modules. There is a cookbook recipe for Linear Regression. If you need something more complex, there is an optimize package.
I'm surprised the following packages are not listed in any of answers:
You can use boxcax from scipy.stats in Python or in R you can use Boxcox in Caret package. You can read more about resolving skewness for predictive modeling in this post.
If your data is Gaussian (as you state in your question), then the optimal value of lambda is 1, i.e. it doesn't need to be transformed.
Perl's PDL has a gaussian fit routine. PDL is a lot like Matlab except with the power of programming in Perl.
I know that the Random class can generate pseudo-random numbers but is there a way to generate truly random numbers?
The answer here has two main sides to it. There are some quite important subtleties to which you should pay due attention...
The Easy Way (for simplicity & practicality)
The RNGCryptoServiceProvider, which is part of the Crypto API in the BCL, should do the job for you. It's still technically a pseudo-random number generated, but the quality of "randomness" is much higher - suitable for cryptographic purposes, as the name might suggest.
There are other crypographic APIs with high quality pseudo random generaters available too. Algorithms such as the Mersenne twister are quite popular.
Comparing this to the Random class in the BCL, it is significantly better. If you plot the numbers generated by Random on a graph, for example, you should be able to recognise patterns, which is a strong sign of weakness. This is largely due to the fact that the algorithm simply uses a seeded lookup table of fixed size.
The Hard Way (for high quality theoretical randomness)
To generate truly random numbers, you need to make use of some natural phenomenon, such as nuclear decay, microscopic temperature fluctuations (CPU temperature is a comparatively conveient source), to name a few. This however is much more difficult and requires additional hardware, of course. I suspect the practical solution (RNGCryptoServiceProvider or such) should do the job perfectly well for you.
Now, note that if you really do require truly random numbers, you could use a service such as Random.org, which generates numbers with very high randomness/entropy (based on atmospheric noise). Data is freely available for download. This may nonetheless be unnecessarily complicated for your situation, although it certainly gives you data suitable for scientific study and whatnot.
The choice is yours in the end, but at least you should now be able to make an informative decision, being aware of the various types and levels of RNGs.
short answer: It is not directly possible to generate TRULY RANDOM NUMBERS using only C# (i.e. using only a purely mathematical construction).
long(er) answer: Only by means of employing an external device capable of generating "randomness" such as a white noise generator or similar - and capturing the output of that device as a seed for a pseudo random number generator (PRG). That part could be accomplished using C#.
True random numbers can only be generated if there is a truly random physical input device that provides the seed for the random function.
Whether anything physical and truly random exists is still debated (and likely will be for a long time) by the science community.
Psuedo-random number generators are the next best thing and the best are very difficult to predict.
As John von Neumann joked, "Anyone who considers arithmetical methods of producing random digits is, of course, in a state of sin."
The thread is old and answered, but i thought I'd proceed anyway. It's for completeness and people should know some things about Random in c#.
As for truly random, the best you can ever hope to do is use a "secure Pseudo Random Generator" like salsa20 or RC4 (sort of, sometimes). They pass a barrage of tests where "efficient" adversaries try to distinguish them from random. This comes with certain costs and is probably unnecessary for most uses.
The random class in c# is pretty good most of the time, it has a statically distribution that looks random. However the default seed for random() is the system time. So if you take lots of randoms at the "same time" they are taken with the same seed and will be the same ("random" is completely deterministic, don't let it fool you). Similar system time seeds also may produce similar numbers because of random class's shortcomings.
The way to deal with this is to set you own seeds, like
Random random = new Random((int)DateTime.Now.Ticks & (0x0000FFFF + x));
where x is some value you increment if you've created a loop to get a bunch of random numbers, say.
Also with c# random extensionsto your new variable like NextDouble() can be helpful in manipulating the random numbers, in this case crow-baring them into interval (0,1) to become unif(0,1), which happens is a distribution you can plug into stat formulas to create all the distributions in statistics.
Take a look at using an algorithm like Yarrow or Fortuna with entropy accumulation. The point with these algorithms is that they keep track of entropy as a measure of theoretical information content available for predicting future numbers by knowing the past numbers and the algorithms used to produce them; and they use cryptographic techniques to fold new entropy sources into the number generator.
You'll still need an external source of random data (e.g. hardware source of random numbers), whether that's time of keystrokes, or mouse movement, or hard disk access times, or CPU temperature, or webcam data, or stock prices, or whatever -- but in any case, you keep mixing this information into the entropy pools, so that even if the truly random data is slow or low quality, it's enough to keep things going in an unpredictable fashion.
I was debating building a random number generator based off twitter or one of the other social networking sites. Basically use the api to pull recent posts and then use that to seed a high quality pseudo random number generator. It probably isn't any more effective than randomizing off the timer but seemed like fun. Besides it seems like the best use for most of the stuff people post to twitter.
I always liked this idea, for the retro 60s look:
Lavarand
There is no "true" random in computers, everything is based on something else. For some (feasible) ways to generate pseudorandom data, try something such as a pool of the HD temp, CPU temp, network usage (packets/second) and possibly hits/second to the webserver.
Just to clarify everyone saying that there is no True RNG available in C# or on your computer is mistaken. A multi-core processor is inherently a True RNG. Very simply by taking advantage of processor spin you can generate bools that have no discernible pattern. From there you can generate whatever number range you want by using the bools as bits and constructing the number by adding the bits together.
Yes this is magnitudes slower than a purely mathematical solution but a purely mathematical solution will always have a pattern.
public static bool GenerateBoolean()
{
var gen1 = 0;
var gen2 = 0;
Task.Run(() =>
{
while (gen1 < 1 || gen2 < 1)
Interlocked.Increment(ref gen1);
});
while (gen1 < 1 || gen2 < 1)
Interlocked.Increment(ref gen2);
return (gen1 + gen2) % 2 == 0;
}
There is no way to generate truly random numbers with a computer. True randomness requires an external source that monitors some natural phenomenon.
That said, if you don't have access to such a source of truly random numbers you could use a "poor man's" process like this:
Create a long array (10000 or more items?) of numbers
Populate the array with current time-seeded random numbers the standard way
When a random number is required, generate a random index into the array and return the number contained at that position
Create a new, current time-seeded random number at the array index to replace the number used
This two-step process should improve the randomness of your results somewhat without the need for external input.
Here's a sample library that implements the above-described algorithm in C++: http://www.boost.org/doc/libs/1_39_0/libs/random/random-generators.html
This code will return you a random number between min and max:
private static readonly Random random = new Random();
private static readonly object syncLock = new object();
public int RandomNumber(int min, int max)
{
lock (syncLock)
{ // synchronize
return random.Next(min, max);
}
}
Usage:
int randomNumber = RandomNumber(0, 10); // a random number between 1 and 10