random.java 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package gnu.brl;
  2. // read.java -- procedure to read a BRL expression
  3. // Copyright (C) 2000 Bruce R. Lewis and Eaton Vance Management
  4. // See the file COPYING for license terms.
  5. import kawa.lang.*;
  6. import gnu.mapping.Procedure1;
  7. import gnu.mapping.WrongType;
  8. import gnu.kawa.io.InPort;
  9. import gnu.math.*;
  10. public class random extends Procedure1 {
  11. static java.util.Random prg = new java.util.Random();
  12. public final Object apply1 (Object arg1)
  13. {
  14. IntNum retval = new IntNum();
  15. // When passed an integer N, return an int M s.t. 0 <= M < N.
  16. if (arg1 instanceof IntNum)
  17. {
  18. IntNum.divide(IntNum.valueOfUnsigned(Math.abs(prg.nextLong()) >> 1),
  19. (IntNum) arg1, null, retval, Numeric.FLOOR);
  20. return retval;
  21. }
  22. // InPort, e.g. /dev/random, for initializing generator
  23. if (arg1 instanceof InPort)
  24. try
  25. {
  26. InPort i = (InPort)arg1;
  27. prg.setSeed((long)
  28. i.read()
  29. + i.read() << 8
  30. + i.read() << 16
  31. + i.read() << 24);
  32. i.close();
  33. return retval;
  34. }
  35. catch (java.io.IOException e)
  36. {
  37. throw new GenericError ("I/O exception in brl-random: "
  38. + e.toString ());
  39. }
  40. throw new WrongType (this, 1, arg1, "real");
  41. }
  42. }