BAEL-4405 Probability in Java
This commit is contained in:
parent
621301b713
commit
9c0eba409e
@ -0,0 +1,17 @@
|
|||||||
|
package com.baeldung.probability;
|
||||||
|
|
||||||
|
import org.apache.commons.math3.distribution.NormalDistribution;
|
||||||
|
|
||||||
|
public class MaleHeightGenerator {
|
||||||
|
private static final double MEAN_HEIGHT = 176.02;
|
||||||
|
private static final double STANDARD_DEVIATION = 7.11;
|
||||||
|
private static NormalDistribution distribution = new NormalDistribution(MEAN_HEIGHT, STANDARD_DEVIATION);
|
||||||
|
|
||||||
|
public static double generateNormalHeight() {
|
||||||
|
return distribution.sample();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static double probabilityOfHeightBetween(double heightLowerExclusive, double heightUpperInclusive) {
|
||||||
|
return distribution.probability(heightLowerExclusive, heightUpperInclusive);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,19 @@
|
|||||||
|
package com.baeldung.probability;
|
||||||
|
|
||||||
|
import io.vavr.Lazy;
|
||||||
|
|
||||||
|
import java.util.SplittableRandom;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
|
public class RandomInvoker {
|
||||||
|
private final Lazy<SplittableRandom> random = Lazy.of(SplittableRandom::new);
|
||||||
|
|
||||||
|
public <T> T withProbability(Supplier<T> supplier1, Supplier<T> supplier2, int probability) {
|
||||||
|
SplittableRandom random = this.random.get();
|
||||||
|
if (random.nextInt(1, 101) <= probability) {
|
||||||
|
return supplier1.get();
|
||||||
|
} else {
|
||||||
|
return supplier2.get();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,24 @@
|
|||||||
|
package com.baeldung.probability;
|
||||||
|
|
||||||
|
import org.assertj.core.data.Offset;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
public class RandomInvokerUnitTest {
|
||||||
|
@Test
|
||||||
|
public void givenProbability_whenInvoked_invokeWithProbability() {
|
||||||
|
RandomInvoker randomInvoker = new RandomInvoker();
|
||||||
|
|
||||||
|
int numberOfSamples = 1_000_000;
|
||||||
|
int probability = 10;
|
||||||
|
int howManyTimesInvoked = Stream.generate(() -> randomInvoker.withProbability(() -> 1, () -> 0, probability))
|
||||||
|
.limit(numberOfSamples)
|
||||||
|
.mapToInt(e -> e).sum();
|
||||||
|
int monteCarloProbability = (howManyTimesInvoked * 100) / numberOfSamples;
|
||||||
|
|
||||||
|
assertThat(monteCarloProbability).isCloseTo(probability, Offset.offset(1));
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user