Add toString method for Distribution class and unit tests for various distributions

This commit is contained in:
2025-02-12 21:22:26 +01:00
parent f0d9c59350
commit 6b3b5fea2f
2 changed files with 51 additions and 0 deletions

View File

@@ -32,6 +32,36 @@ public interface Distribution {
return sample;
}
/**
* Returns a string representation of the distribution.
* In case the distribution is null, an empty string is returned.
*
* @param distribution The distribution to represent.
* @return A string representation of the distribution.
* @throws IllegalArgumentException if the field cannot be accessed
* @throws IllegalAccessException if the field cannot be accessed
*/
public static String toString(Distribution distribution) throws IllegalArgumentException, IllegalAccessException {
if (distribution == null)
return "";
var builder = new StringBuilder();
var dist = distribution.getClass();
builder.append(dist.getSimpleName()).append('(');
for (var param : dist.getFields()) {
var paramValue = param.get(distribution);
var str = paramValue instanceof Distribution
? toString((Distribution) paramValue)
: paramValue;
builder.append(str).append(", ");
}
builder.delete(builder.length() - 2, builder.length()).append(')');
return builder.toString();
}
/**
* Represents an exponential distribution.
*/

View File

@@ -8,6 +8,27 @@ import net.berack.upo.valpre.rand.Distribution;
public class TestInteractions {
@Test
public void distributionToString() throws Exception {
var exp = new Distribution.Exponential(1.0);
assertEquals("Exponential(1.0)", Distribution.toString(exp));
var uniform = new Distribution.Uniform(0.0, 1.0);
assertEquals("Uniform(0.0, 1.0)", Distribution.toString(uniform));
var erlang = new Distribution.Erlang(2, 1.0);
assertEquals("Erlang(2, 1.0)", Distribution.toString(erlang));
var normal = new Distribution.Normal(3.2, 0.6);
assertEquals("Normal(3.2, 0.6)", Distribution.toString(normal));
var normalBoxMuller = new Distribution.NormalBoxMuller(3.2, 0.6);
assertEquals("NormalBoxMuller(3.2, 0.6)", Distribution.toString(normalBoxMuller));
var unavailable = new Distribution.UnavailableTime(0.1, exp);
assertEquals("UnavailableTime(0.1, Exponential(1.0))", Distribution.toString(unavailable));
}
@Test
public void netToString() {
var net = new Net();