Closed Otanikotani closed 7 years ago
Yes, this is an effect of rounding nobody was paying attention to earlier. Not sure what is an expected behaviour here, but I could imagine it might affect testing of marginal values.
@daivanov May I ask you why implementation
new Random().nextInt((max - min) + 1) + min;
Is not used? Why is it important to add and substract 0.5?
And why should it be used? ;)
I did a quick profiling and your code takes 43703 ms per billion iterations, and current implementation does it in 20566 ms, which is 53% faster.
Well, did you always create a new instance of Random?
Sure, because it was part of the question.
Benchmark:
public class Randoms {
@Benchmark
public Integer current() {
return PodamUtils.getIntegerInRange(0, 1000);
}
@Benchmark
public Integer rangeFromSo() {
return PodamUtils.getIntegerRangeDefaultVersionFromStackOverflow(0, 1000);
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(Randoms.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
}
Results:
Benchmark Mode Cnt Score Error Units
Randoms.current thrpt 20 35493740.187 ± 304428.342 ops/s
Randoms.rangeFromSo thrpt 20 75697058.949 ± 554676.207 ops/s
Where methods are like this:
public static int getIntegerInRange(int minValue, int maxValue) {
return (int) (getDoubleInRange(minValue - 0.5, maxValue + 0.5 - (1 / Integer.MAX_VALUE)) + 0.5);
}
public static int getIntegerRangeDefaultVersionFromStackOverflow(int minValue, int maxValue) {
return RNG.nextInt((maxValue - minValue) + 1) + minValue;
}
and RNG is static final variable.
But why would you measure performance for code which is not optimized? Of course it would lose if you create an instance every time. The point of that version was to show that it is simply more readable without casts, division and strange values like 0.5.
And can you do this for long?
It is possible to do without implementing your own version in Java 7 or using apache commons math.
But you also should tell why things should be done. People should know motivational part of the proposal.
I will resolve this issue, if you don't mind.
Yea, sure, it is all only speculative, I don't think that normalized distribution or performance of random generator is that important anyway.
The distribution is not normal, now it is uniform. Performance is of course important, but it's not easy to improve it.
Released in Podam 7.0.5
Code, it simply counts frequencies of random values from 0 to 2 inclusively.
Result:
Is it expected behaviour? For range from 0 to 10 same code generates:
Which looks a little bit weird and not fair!