Sjs Sjs - 1 year ago 82
Java Question

how does (int)exp.sample() work in the code?

ExponentialDistribution exp = new ExponentialDistribution(4.0);
for(int i = 1; i < 20; i++){
timestamp[i] = (int)exp.sample() + 1+timestamp[i-1];

Here timestamp is an array of integers and a random value is assigned to it with above condition. What does (int)exp.sample() does and how it assigns a random value to i?

Answer Source

From the ExponentialDistribution API:

public double sample()

Generate a random value sampled from this distribution. The default implementation uses the inversion method.

Algorithm Description: this implementation uses the Inversion Method to generate exponentially distributed random values from uniform deviates.

So when you see (int)exp.sample(), we are converting it to this random value it selected. exp is the instance of ExponentialDistribution(4.0) we've created, so exp.sample() calls ExponentialDistribution's sample() method.

Now for the (int).

Placing an Object type or primitive type in parenthesis (int this case (int)) prior to another Object/primitive is called "casting". Casting variables in Java

Pretty much, since sample() returns a double, but timestamp stores ints, we need to switch one of their types (they must match), and it's waaaaay easier to change exp.sample()'s.

So, all in all, this says "Take the object exp, call it's method sample(), and then convert that into an int".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download