From 725b65e460925aeda3dc2c0f34132348e05caaad Mon Sep 17 00:00:00 2001 From: jkauttio Date: Wed, 27 May 2015 11:01:18 +0000 Subject: [PATCH] Implement randomUniform and fix randomNumber in internal solver refs #5878 git-svn-id: https://www.simantics.org/svn/simantics/sysdyn/trunk@31359 ac1ea38d-2e2b-0410-8846-a27921b304fc --- .../semantum/sysdyn/solver/Environment.java | 44 ++++++++++++++++--- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Environment.java b/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Environment.java index f4f5c294..0f6fc0d3 100644 --- a/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Environment.java +++ b/fi.semantum.sysdyn.solver/src/fi/semantum/sysdyn/solver/Environment.java @@ -21,6 +21,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; +import java.util.Random; import java.util.Set; import java.util.TreeMap; @@ -70,6 +71,16 @@ abstract class Fn1 implements Fn { } +abstract class FnRandom extends Fn1 { + + protected Random random = null; + + public FnRandom(int pCount) { + super(pCount); + } + +} + final public class Environment implements IEnvironment, ISystem { final Map named = new HashMap(); @@ -625,15 +636,38 @@ final public class Environment implements IEnvironment, ISystem { } }); - model.functions.put("randomNumber", new Fn1(2) { + model.functions.put("randomNumber", new FnRandom(2) { @Override public Object evaluate(IEnvironment environment, int argc) { - @SuppressWarnings("unused") Double seed = (Double)environment.getValue(0); - @SuppressWarnings("unused") - Double time = (Double)environment.getValue(1); - return Math.random(); + + if (random == null) { + random = new Random(Double.doubleToLongBits(seed)); + } + + return random.nextDouble(); + } + + }); + model.functions.put("randomUniform", new FnRandom(4) { + + @Override + public Object evaluate(IEnvironment environment, int argc) { + Double min = (Double)environment.getValue(0); + Double max = (Double)environment.getValue(1); + Double seed = (Double)environment.getValue(2); + + // the fourth parameter should be "time" and is only necessary + // because sysdyn treats all functions as side-effect-free and + // does not evaluate a function "needlessly" if the parameters + // do not change. the parameter does not actually do anything + // though so we can safely ignore it here + + if (random == null) { + random = new Random(Double.doubleToLongBits(seed)); + } + return random.nextDouble() * (max - min) + min; } }); -- 2.47.1