Generating random number without using built-in functions [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Am on generating snippets for built-in functions to know how they are executed, and is a part of my research also. i successfully completed some string handling functions,split, substring,reverse etc.. but i stuck in random numbers how they ware generated? how the RND or Random functions are work?
Thanks in advance

The most popular current algorithm is probably the Mersenne twister, pseudo-code in the Wikipedia article (and there are many implementations available from Google).
Another well known algorithm is Blum Blum Shub which has a proof that reduces its' security to the computational difficulty of computing modular square roots, a problem whose difficulty is assumed to be equivalent to factoring. However Blum Blum Shub is very slow.
Finally, here is a large list of additional pseudo-random number generators. Which algorithm a particular language uses varies.

Here's two algorithms that I've used most often in some of my projects:
1.Uniform distributed numbers in range between 0 and 1
result = getRidOfIntegerPart(A * prevResult)
Where A is a seed.
Possible implementation(C++):
int main()
{
double A = 12.2345; //seed
double prevResult = 1; //You can assign any value here
double result;
double intPart;
//This will give you 10 uniform distributed numbers
for(unsigned i = 0; i < 10; ++i)
{
double r = A * prevResult;
result = modf(r, &intPart); // To get rid of integer part
prevResult = result;
cout<<"result "<<i<<" = "<<result<<endl;
}
}
2. Normal(Gauss) distribution
Here's an original formula:
http://en.wikipedia.org/wiki/Normal_distribution
But I'm using a bit different simplifed formula:
It says that new normal distributed number obtained from sum of 12 uniform distributed numbers(Sj)
Possible implementation(C++):
class RandomNumberGenerator
{
public:
RandomNumberGenerator()
{
uniformPrevResult = 1;
uniformResult = 0;
uniformIntPart = 0;
}
double generateUniformNumber(double seed)
{
double r = seed * uniformPrevResult;
uniformResult = modf(r, &uniformIntPart); // To get rid of integer part
uniformPrevResult = uniformResult;
return uniformResult;
}
double generateNormalNumber(double seed)
{
double uniformSum = 0;
for(unsigned i = 0; i < 12; ++i)
{
uniformSum += generateUniformNumber(seed);
}
double normalResult = uniformSum - 6;
return normalResult; // 6 is a magic number
}
private:
double uniformPrevResult;
double uniformResult;
double uniformIntPart;
};
int main()
{
const double seed = 12.2345;
RandomNumberGenerator rndGen;
for(unsigned i = 0; i < 100; ++i)
{
double newNormalNumber = rndGen.generateNormalNumber(seed);
cout<<"newNormalNumber = "<<newNormalNumber<<endl;
}
return 0;
}
I hope it'll help you!

The JAva languages uses the algorithm that is documented in java.util.Random. There it also states that all implementations must use this algorithm
seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
return (int)(seed >>> (48 - bits));
Hence it is not true for Java that "which algorithm a particular language uses varies".

Related

Does the number generated by this function obey uniform distribution ? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I have implemented a function Generating numbers in [0,x] by given string :
import org.apache.commons.codec.digest.DigestUtils;
public class BaseUtil {
public static int getIntValue(String stringText, String x) {
var modNum = new BigInteger(x);
String sha256hex = DigestUtils.sha256Hex(stringText);
var result = new BigInteger(sha256hex, 16);
int intValue = result.mod(modNum).intValue();
return intValue;
}
}
Does the return intValue obey uniform distribution in [0,x] for much random string?
Does the method Generating int number in [0,x] by given string follow uniform distribution?
Almost. It is difficult to entirely eliminate non-uniformity ... unless 2256 happens to be evenly divisible by x.
Note that you are actually generating a number in [0,x) ... since the result cannot be x.
You also asked about more efficient implementations than the one in your question.
public class BaseUtil {
public static int getIntValueV1(String stringText, int x) {
if (x <= 0) {
throw new InvalidArgumentException("x must be strictly positive");
}
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(
stringText.getBytes(StandardCharsets.UTF_8));
return new BigInteger(hash).mod(new BigInteger(x)).intValue()
}
public static int getIntValueV2(String stringText, int x) {
if (x <= 0) {
throw new InvalidArgumentException("x must be strictly positive");
}
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(
stringText.getBytes(StandardCharsets.UTF_8));
ByteBuffer buff = new ByteBuffer(hash);
long number = 0;
for (int i = 0; i < 8; i++) {
number = number ^ buff.getLong();
}
return (int)(number % x);
}
}
Preconditions:
Since the result of your method is an int, that implies that x must also be an int.
Since you want numbers in the range [0,x), that implies that x must be greater than zero.
Implementations:
I am using the standard MessageDigest class since it has been in Java SE since Java 5 (if not earlier).
The first version uses BigInteger to minimize the non-uniformity when we reduce the bytes into a number in the range [0, x)
The second version uses long arithmetic to compute the remainder. I think that means that the distribution might be a bit more non-uniform than the first version. (My math skills are too rusty ...) It would also be possible to eliminate the use of ByteBuffer to convert the bytes to a sequence of longs.
I have not benchmarked these versions to see which is faster. But both should be faster than producing an intermediate hexadecimal string and parsing it.
Note that you could probably get away with using a less expensive hashing algorithm, depending on the actual use-case for this generator.

Generating random numbers within a specific range [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 8 years ago.
I've searched high and low for the answer to this and can't see how I'm doing it wrong, I've tried several different ways of coding it but it always goes outside the range I'm looking for. (90 - 180 inclusive).
Can anyone shed some light on the code below???
Random rnd = new Random();
int time = rnd.nextInt(91) + 90;
Thanks for any support offered...
/**
* Randomly generates a number between 90-180 inclusive and sets the random number as an argument to a message-send for each of the
* Runner objects in runnersList.
*/
public void runMarathon()
{
for (Runner r : runnersList)
{
Random rnd = new Random();
int time = rnd.nextInt(91) + 90;
r.setTime(time);
}
}
This function will help you to do what you need
private int randInt(int min, int max) {
return new Random().nextInt((max - min) + 1) + min;
}
just give min and max values as parametres to the function and you will get a random value between the range you specified ;)
A key principal in software development is reuse. So to do this, you can use
"http://commons.apache.org/proper/commons-lang/javadocs/api-3.3/org/apache/commons/lang3/RandomUtils.html#nextInt(int, int)" instead of reinventing the wheel.

Generating a lognormal distribution from an array in Java

I didn't find any help on the subject so I'm posting a new question about it. I have a variable containing three values {min, average, standard dev.}. How do I generate a lognormal distribution of this array that would randomly give me a value of the time from the lognormal distribution. Also If I would run it 1000 times I would want to randomly get a value of the time from the lognormal distribution each of the 1000 times. How would I write this in java code? Also I guess running it 1000 times would give me an average of the average in the array?
First, generate standard normal values and convert them to a normal distribution with given parameters. Finally, raise to exponential to get log-normal distribution with given mean and std dev.
Random rng = new Random(0);
double[] logNormalValues = new double[1000];
for (int i = 0; i < logNormalValues.length; i++) {
double stdNormal = rng.nextGaussian();
double normalValue = stdDev * stdNormal + mean;
logNormalValues[i] = Math.exp(normalValue);
}
or this
public static double LogNormal(double mean, double stddev) {
Random randGen = new Random();
double varx = Math.pow(stddev, 2);
double ess = Math.log(1.0 + (varx/Math.pow(mean,2)));
double mu = Math.log(mean) - (0.5*Math.pow(ess, 2));
return Math.pow(2.71828, (mu+(ess*randGen.nextGaussian() ) ) );
}
you can also get a built in function here. in your above example, you won't actually end up with the stddev and mean noted -- they change when you exp() the values.
https://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/distribution/LogNormalDistribution.html

which of the following is the fastest data type in java? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
In java data types(byte,short,int,float,double,boolean) which is the fastest data type for compilation and computation and why?please list the reason clearly to understand
Why does it matter? Your speed issues are not going to be down to the primitive type you're using, and Premature Optimization Is The Root Of All Evil. I can almost guarantee that the primitive type you're using is not going to affect the speed of your program. Choose your type based on what you need to use it for!
The only performance difference between the types is computing in floating point arithemtics vs. integer arithmetics, where computing in integer is clearly and measurably faster.
The rule of thumb - if your data could be naturally represented as integers (e.g. the number of bananas in the store), go for some of the integer types (byte, short, int, long). If your data are represented as real numbers (the amount of kilograms of bananas you bought), go either for float or double.
Every single type has its specifics, you need to get to know their ranges and if you're allocating millions of them, their memory footprint.
EDIT addressing OP's comment:
Could u please tell me why computing in integer is faster?
First off, I have to admit that what I said is not theoretically true. It all depends on the architecture of the computer you'll be running your code on.
Generally though, the statement holds for current modern PC compatible processors. It all boils down to the inner representation of the numbers (search for Two's complement for integer values and Mantissa and exponent for floats) and the inner mechanics of the processors, their computation units and shortcuts for some of the operations. It's a topic for a few classes at least.
The over-simplification tells that counting with integers is easier as they are stored and processed in a much easier way than floats.
Also don't forget that this will differ on different processors and different architectures.
I wrote a simple test showing my results:
private final static int MAX = 1_000_000_000;
public static void main(String[] args) {
long time; // no see
time = System.currentTimeMillis();
int intnum = 0;
for (int i = 0; i < MAX; i++) {
intnum += i;
}
System.out.println("int:\t" + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
long longnum = 0;
for (int i = 0; i < MAX; i++) {
longnum += i;
}
System.out.println("long:\t" + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
float floatnum = 0;
for (int i = 0; i < MAX; i++) {
floatnum += i;
}
System.out.println("float:\t" + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
double doublenum = 0;
for (int i = 0; i < MAX; i++) {
doublenum += i;
}
System.out.println("double:\t" + (System.currentTimeMillis() - time));
// just to use the values, don't pay attention to the results
System.out.println();
System.out.println(intnum);
System.out.println(longnum);
System.out.println(floatnum);
System.out.println(doublenum);
}
The results on my 32-bit processor:
int: 578 ms
long: 1578 ms
float: 3156 ms
double: 3172 ms
While benchmarks like this are hard to get right (and I didn't even try too much), this one fairly precisely describes my real world experience.
Integer is the fastest, then long, then floating point types.
If I had a 64-bit processor, OS and JVM, int and long would probably be on the same level (just like float and double are on my PC).

Solve an Integral in Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I need to develop a program in Java to solve some integrals. Integrals like this:
I've looked for some functions to do this, in java.Math but I didn't find anything.
Has anyone an idea to get a solution for this? (Maybe some extra libraries or something like that).
The Wikipedia article on Numerical Integration has a section on methods for one-dimensional integrals.
You should have no problem implementing the "trapezoidal" or "rectangle" rule.
The Apache Commons Math library contains, in the Numerical Analysis section, four different numerical integrators:
Romberg's method
Simpson's method
trapezoid method
Legendre-Gauss method
Take a look at JScience
Check out Simpson's Rule on Wikipedia.
/*------------------------------------------------------------------------------------------------------
* Small program that numerically calculates an integral according to
* Simpson's algorithm. Before executing it, you must enter:
* - the expression of the function f: line 12;
* - the lower and upper limits b of the integral: lines 39 and 40;
* - the number of measurements n (n is integer !!!): line 41.
*------------------------------------------------------------------------------------------------------*/
// Class function: Defines Simpson's rule
class Function{
// Define the function to integrate
double f (double x) {
return Math.Cos(x);
}
// Simpson's method for integral calculus
// a = lower bound
// b = upper bound of integration
// n = number of passes (higher = less margin of error, but takes longer)
double IntSimpson(double a, double b,int n){
int i,z;
double h,s;
n=n+n;
s = f(a)*f(b);
h = (b-a)/n;
z = 4;
for(i = 1; i<n; i++){
s = s + z * f(a+i*h);
z = 6 - z;
}
return (s * h)/3;
}
}
class integration{
// Class result: calculates the integral and displays the result.
public static void main(String args[]){
// Call class function
Function function;
function = new Function();
// ENTER the desired values of a, b and n !!!
double a = ???? ;
double b = ???? ;
int n = ???? ;
// Applies simpson method to function
double result = function.IntSimpson(a,b,n);
// Show results
System.out.println("Integral is: " + result);
}
}

Categories

Resources