@Override
  public void breakBlock(World worldIn, BlockPos pos, IBlockState state) {
    if (worldIn.isRemote) return;

    ArrayList drops = new ArrayList();

    TileEntity teRaw = worldIn.getTileEntity(pos);

    if (teRaw != null && teRaw instanceof TileEntityTreasure) {
      TileEntityTreasure te = (TileEntityTreasure) teRaw;

      for (int i = 0; i < te.getSizeInventory(); i++) {
        ItemStack stack = te.getStackInSlot(i);

        if (stack != null) drops.add(stack.copy());
      }
    }

    for (int i = 0; i < drops.size(); i++) {
      EntityItem item =
          new EntityItem(worldIn, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5);
      item.setVelocity(
          (rand.nextDouble() - 0.5) * 0.25,
          rand.nextDouble() * 0.5 * 0.25,
          (rand.nextDouble() - 0.5) * 0.25);
      worldIn.spawnEntityInWorld(item);
    }
  }
Beispiel #2
0
  @Override
  public Long askPrice(Task task) {

    System.out.println("Ask price");

    long startTime = System.currentTimeMillis();
    long endTime = startTime + timeout_bid;

    Vehicle[] vArray = new Vehicle[agent.vehicles().size()];
    vArray = agent.vehicles().toArray(vArray);

    List<Task> futureTasks = new ArrayList<Task>(currentTasks);
    futureTasks.add(task);

    this.futureSolution =
        CentralizedPlanner.centralizedSolution(vehicles, futureTasks, endTime - 1000);
    double cost = this.futureSolution.computeCost(vArray);

    double marginalCost = Math.abs(cost - currentSolution.computeCost(vArray));

    // ----- STRATEGY --------------

    Random r = new Random();

    double randomRatio = 1 + r.nextDouble();

    if (marginalCost > 1000 && r.nextDouble() > 0.9) marginalCost = 7000;
    if (marginalCost == 0) marginalCost = 50;

    double futureScore = getOpportunityExpected(task.pickupCity, task.deliveryCity);

    return (long) Math.ceil((randomRatio - futureScore) * marginalCost);
  }
  private Gene mutateNode(NEATNodeGene mutatee) {
    double perturbRandVal = perturbRand.nextDouble();
    double mutateBias = perturbRand.nextDouble();
    NEATNodeGene mutated = mutatee;
    double newSF = mutatee.sigmoidFactor();
    double newBias = mutatee.bias();

    if (perturbRandVal < this.pPerturb) {
      newSF = mutatee.sigmoidFactor() + MathUtils.nextClampedDouble(-perturb, perturb);
      mutated =
          new NEATNodeGene(
              mutated.getInnovationNumber(),
              mutated.id(),
              newSF,
              mutated.getType(),
              mutated.bias());
    }

    if (mutateBias < this.pMutateBias) {
      newBias += MathUtils.nextClampedDouble(-biasPerturb, biasPerturb);
      mutated =
          new NEATNodeGene(
              mutated.getInnovationNumber(),
              mutated.id(),
              mutated.sigmoidFactor(),
              mutated.getType(),
              newBias);
    }

    return (mutated);
  }
  @Test
  public void testNoOpUpdater() {
    Random r = new Random(12345L);
    double lr = 0.5;

    NeuralNetConfiguration conf =
        new NeuralNetConfiguration.Builder()
            .learningRate(lr)
            .layer(
                new DenseLayer.Builder()
                    .nIn(nIn)
                    .nOut(nOut)
                    .updater(org.deeplearning4j.nn.conf.Updater.NONE)
                    .build())
            .build();

    int numParams = LayerFactories.getFactory(conf).initializer().numParams(conf, true);
    INDArray params = Nd4j.create(1, numParams);
    Layer layer = LayerFactories.getFactory(conf).create(conf, null, 0, params, true);
    Updater updater = UpdaterCreator.getUpdater(layer);

    for (int i = 0; i < weightGradient.length(); i++) weightGradient.putScalar(i, r.nextDouble());
    for (int i = 0; i < biasGradient.length(); i++) biasGradient.putScalar(i, r.nextDouble());

    gradient.gradientForVariable().put(DefaultParamInitializer.WEIGHT_KEY, weightGradient);
    gradient.gradientForVariable().put(DefaultParamInitializer.BIAS_KEY, biasGradient);

    updater.update(layer, gradient, -1, 1);

    INDArray weightGradActual = gradient.getGradientFor(DefaultParamInitializer.WEIGHT_KEY);
    INDArray biasGradActual = gradient.getGradientFor(DefaultParamInitializer.BIAS_KEY);

    assertEquals(weightGradient, weightGradActual);
    assertEquals(biasGradient, biasGradActual);
  }
Beispiel #5
0
  @Override
  public void evaluate(VectorizedRowBatch batch) {

    if (childExpressions != null) {
      this.evaluateChildren(batch);
    }

    DoubleColumnVector outputColVector = (DoubleColumnVector) batch.cols[outputCol];
    int[] sel = batch.selected;
    int n = batch.size;
    double[] outputVector = outputColVector.vector;
    outputColVector.noNulls = true;
    outputColVector.isRepeating = false;

    // return immediately if batch is empty
    if (n == 0) {
      return;
    }

    // For no-seed case, create new random number generator locally.
    if (random == null) {
      random = new Random();
    }

    if (batch.selectedInUse) {
      for (int j = 0; j != n; j++) {
        int i = sel[j];
        outputVector[i] = random.nextDouble();
      }
    } else {
      for (int i = 0; i != n; i++) {
        outputVector[i] = random.nextDouble();
      }
    }
  }
 @Override
 void onUpdate() {
   final Item ITEM =
       ent.getWorld()
           .dropItem(
               ((Sheep) ent).getEyeLocation(),
               ItemFactory.create(
                   Material.WOOL, (byte) r.nextInt(017), UUID.randomUUID().toString()));
   ITEM.setPickupDelay(30000);
   ITEM.setVelocity(
       new Vector(r.nextDouble() - 0.5, r.nextDouble() / 2.0 + 0.3, r.nextDouble() - 0.5)
           .multiply(0.4));
   items.add(ITEM);
   Bukkit.getScheduler()
       .runTaskLater(
           Core.getPlugin(),
           new Runnable() {
             @Override
             public void run() {
               ITEM.remove();
               items.remove(ITEM);
             }
           },
           5);
 }
        @Override
        /**
         * Updates the task
         */
        public void updateTask()
        {
            Random random = this.field_179473_a.getRNG();
            World world = this.field_179473_a.worldObj;
            int i = MathHelper.floor_double(this.field_179473_a.posX - 2.0D + random.nextDouble() * 4.0D);
            int j = MathHelper.floor_double(this.field_179473_a.posY + random.nextDouble() * 3.0D);
            int k = MathHelper.floor_double(this.field_179473_a.posZ - 2.0D + random.nextDouble() * 4.0D);
            BlockPos blockpos = new BlockPos(i, j, k);
            IBlockState iblockstate = world.getBlockState(blockpos);
            Block block = iblockstate.getBlock();

            if (EntityChaoticEnderman.carriableBlocks.contains(block))
            {
            	int blockMeta = ModBlocks.chaos_Block.getMetaFromState(iblockstate);
            	if (block != ModBlocks.chaos_Block || (blockMeta < 4)) {
            		this.field_179473_a.func_175490_a(iblockstate);
            		world.setBlockState(blockpos, Blocks.air.getDefaultState());
            	} else
            		this.field_179473_a.func_175490_a(ModBlocks.chaos_Block.getStateFromMeta((world.rand.nextFloat() >= 0.2F ?
            			13 : 14) + blockMeta < 2 ? 0 : 1));
            }
        }
 private SampleEntity createSampleEntity(String id) {
   Random prng = new Random();
   SampleEntity entity = new SampleEntity();
   entity.setId(id);
   entity.setBooleanPrimitive(prng.nextBoolean());
   entity.setBooleanObject(prng.nextBoolean());
   entity.setBytePrimitive((byte) prng.nextInt(Byte.MAX_VALUE));
   entity.setByteObject((byte) prng.nextInt(Byte.MAX_VALUE));
   entity.setShortPrimitive((short) prng.nextInt(Short.MAX_VALUE));
   entity.setShortObject((short) prng.nextInt(Short.MAX_VALUE));
   entity.setIntPrimitive(prng.nextInt());
   entity.setIntObject(prng.nextInt());
   entity.setLongPrimitive(prng.nextLong());
   entity.setLongObject(prng.nextLong());
   entity.setFloatPrimitive(prng.nextFloat());
   entity.setFloatObject(prng.nextFloat());
   entity.setDoublePrimitive(prng.nextDouble());
   entity.setDoubleObject(prng.nextDouble());
   entity.setString(RandomStringUtils.randomAlphanumeric(16));
   entity.setByteArray(RandomStringUtils.randomAlphanumeric(16).getBytes(Charsets.UTF_8));
   entity.setDate(new Date());
   entity.setUuid(TimeUUIDUtils.getUniqueTimeUUIDinMicros());
   Foo foo = new Foo(prng.nextInt(), RandomStringUtils.randomAlphanumeric(4));
   entity.setFoo(foo);
   BarBar barbar = new BarBar();
   barbar.i = prng.nextInt();
   barbar.s = RandomStringUtils.randomAlphanumeric(4);
   Bar bar = new Bar();
   bar.i = prng.nextInt();
   bar.s = RandomStringUtils.randomAlphanumeric(4);
   bar.barbar = barbar;
   entity.setBar(bar);
   return entity;
 }
Beispiel #9
0
  @Test
  public void testVec4dInterner() {
    Random rand = new Random();

    Vec4d[] vecs = new Vec4d[128];
    Vec4d[] interned = new Vec4d[128];
    for (int i = 0; i < 128; ++i) {
      vecs[i] =
          new Vec4d(rand.nextDouble(), rand.nextDouble(), rand.nextDouble(), rand.nextDouble());
    }

    Vec4dInterner interner = new Vec4dInterner();

    for (int i = 0; i < 128; ++i) {
      interned[i] = interner.intern(vecs[i]);
      assertTrue(interned[i].equals2(vecs[i]));
    }

    // check index
    for (int i = 0; i < 128; ++i) {
      int ind = interner.getIndexForValue(vecs[i]);
      assertTrue(i < 128);
      assertTrue(interner.getValueForIndex(ind).equals2(vecs[i]));
    }
  }
Beispiel #10
0
  private void setupCutoffTimers() {
    Logger cutoffLogger = sessionLogger();
    Random random = new Random();
    int cutoffIfSimultaneous = (int) (random.nextDouble() * (latestCutoff - earliestCutoff));
    if (simultaneousCutoff) {
      cutoffLogger.info("using a simultaneous cutoff of " + cutoffIfSimultaneous + " seconds.");
    }
    Iterator<String> nameIterator = playerNameIterator();
    while (nameIterator.hasNext()) {
      Judge judge = getJudgeOrNull(nameIterator.next());
      if (judge == null) {
        continue;
      }

      int cutoff;
      if (simultaneousCutoff) {
        cutoff = cutoffIfSimultaneous;
      } else {
        cutoff = earliestCutoff + (int) (random.nextDouble() * (latestCutoff - earliestCutoff));
        cutoffLogger.info(
            "using a cutoff for judge '" + judge.getName() + "' of " + cutoff + " seconds.");
        int roundDuration = timeLimit();
        if (cutoff > roundDuration + 10) {
          cutoff = roundDuration + 10;
          cutoffLogger.info(
              "reducing timeout to " + cutoff + " (10 seconds after round finishes).");
        }
      }
      TimerTask task = judge.getCutoffTimer();
      timer.schedule(task, 1000 * cutoff);
    }
  }
 // the general Levy distribution is rather computing demanding
 public static final double nextLevy() {
   double v = Math.PI * (rand.nextDouble() - 0.5);
   double k = LEVY_ALFA * v;
   double w = -Math.log(rand.nextDouble()) / Math.cos(v - k);
   double h = w * Math.cos(v);
   return LEVY_CONSTRICTION * Math.abs(w * Math.sin(k) * Math.exp(-Math.log(h) / LEVY_ALFA));
 }
  public static void main(String[] args) {
    System.out.println("Buffon Pi Estimation");
    System.out.println("Enter the number of tries: ");
    Scanner in = new Scanner(System.in);
    int tries = in.nextInt();

    Random generator = new Random(42);
    int hits = 0;

    for (int i = 0; i < tries; i++) {

      // generate a yLow, the lowest point, or the farthest point on
      // the needle from the line (a number between 0 and 2).
      double yLow = 2 * generator.nextDouble(); // low point of needle

      // generate a random angle a between 0 and 180 degrees.
      // angle between 0 and 180
      double angle = 180 * generator.nextDouble();
      angle = Math.toRadians(angle);

      // yHigh is yLow plus the sine of a.
      double yHigh = yLow + Math.sin(angle);

      // Calculate the number of hits.
      // if yHigh is above the line (the line is at a height of 2),
      // the needle is touching the line, and counts as a hit.
      if (yHigh >= 2) {
        hits++;
      }
    }
    double piEstimate = tries / (double) (hits);

    System.out.println();
    System.out.println(piEstimate);
  }
  @Before
  public void setUp() {
    // mock the split context since BoundingBox does not make much use of it
    ctx = mock(ISplitContext.class);

    // {{ generate 100K stars
    for (int i = 0; i < 100000; i++) {
      Location location =
          new Location(
              random.nextDouble() * 100,
              random.nextDouble() * 100,
              random.nextDouble() * 100,
              DistanceUnit.LIGHT_YEAR);
      IStellar star = new Star(StarClass.O, location, 1);
      stars100K.add(star);
    }
    // }}

    // {{ generate 250K stars
    for (int i = 0; i < 5000; i++) {
      Location location =
          new Location(
              random.nextDouble() * 100,
              random.nextDouble() * 100,
              random.nextDouble() * 100,
              DistanceUnit.LIGHT_YEAR);
      IStellar star = new Star(StarClass.O, location, 1);
      stars50K.add(star);
    }
    // }}

    box100K = BoundingBox.newInstance(stars100K);
    box50K = BoundingBox.newInstance(stars50K);
  }
  /**
   * ballThrown()
   *
   * <p>Called to simulate a ball thrown comming in contact with the pinsetter
   *
   * @pre none
   * @post pins may have been knocked down and the thrownumber has been incremented
   */
  public void ballThrown() { // simulated event of ball hits sensor
    int count = 0;
    foul = false;
    double skill = rnd.nextDouble();
    for (int i = 0; i <= 9; i++) {
      if (pins[i]) {
        double pinluck = rnd.nextDouble();
        if (pinluck <= .04) {
          foul = true;
        }
        if (((skill + pinluck) / 2.0 * 1.2) > .5) {
          pins[i] = false;
        }
        if (!pins[i]) { // this pin just knocked down
          count++;
        }
      }
    }

    try {
      Thread.sleep(500); // pinsetter is where delay will be in a real game
    } catch (Exception e) {
    }

    sendEvent(count);

    throwNumber++;
  }
Beispiel #15
0
  /**
   * 57% of time spent in LogConditionalObjectiveFunction.calculateCLBatch() 22% spent in
   * constructing datums (expensive)
   *
   * <p>Single threaded, 4100 ms Multi threaded, 600 ms
   *
   * <p>With same data, seed 42, 52 ms With reordered accesses for cacheing, 38 ms Down to 73% of
   * the time
   *
   * <p>with 8 cpus, a 6.8x speedup -- basically the same as with RVFDatum
   */
  public static void benchmarkLogisticRegression() {
    Dataset<String, String> data = new Dataset<>();
    for (int i = 0; i < 10000; i++) {
      Random r = new Random(42);
      Set<String> features = new HashSet<>();

      boolean cl = r.nextBoolean();

      for (int j = 0; j < 1000; j++) {
        if (cl && i % 2 == 0) {
          if (r.nextDouble() > 0.3) {
            features.add("f:" + j + ":true");
          } else {
            features.add("f:" + j + ":false");
          }
        } else {
          if (r.nextDouble() > 0.3) {
            features.add("f:" + j + ":false");
          } else {
            features.add("f:" + j + ":false");
          }
        }
      }

      data.add(new BasicDatum<String, String>(features, "target:" + cl));
    }

    LinearClassifierFactory<String, String> factory = new LinearClassifierFactory<>();

    long msStart = System.currentTimeMillis();
    factory.trainClassifier(data);
    long delay = System.currentTimeMillis() - msStart;
    System.out.println("Training took " + delay + " ms");
  }
Beispiel #16
0
  public OsuApiBeatmap getBeatmap(int beatmapid) {
    Random rand = new Random(beatmapid);
    OsuApiBeatmap beatmap = database.beatmaps.get(beatmapid);
    if (beatmap == null) {
      beatmap = new OsuApiBeatmap();
      beatmap.setBeatmapId(beatmapid);
      if (setIds.containsKey(beatmapid)) {
        beatmap.setSetId(setIds.get(beatmapid));
      }
      {
        // ARTIST
        String[] artists = {"Hatsune Miku", "IOSYS", "Nightcore", "DragonForce", "ClariS"};
        beatmap.setArtist(artists[beatmapid % artists.length]);
      }
      beatmap.setTitle("Beatmap " + beatmapid);
      {
        // VERSION AND DIFFICULTY
        String[] versions = {"Easy", "Normal", "Hard", "Hyper", "Insane", "Another", "Extra"};
        int diff = beatmapid % versions.length;
        beatmap.setVersion(versions[diff]);

        beatmap.setStarDifficulty(diff + rand.nextDouble());
        beatmap.setTotalLength((int) (30 + Math.pow(rand.nextDouble(), 3) * 600));
        beatmap.setApproachRate(5 + Math.min(4, diff) + (int) (rand.nextDouble() + .5));
        beatmap.setCircleSize(diff + 1);
        beatmap.setBpm(50 * Math.pow(2, diff * .4 + rand.nextDouble()));
      }
    }
    return beatmap;
  }
  public TableModel produce(final DataRow parameters, final DataFactoryContext dataFactoryContext)
      throws ReportDataFactoryException {
    final int limit = getTypedParameter("limit", Integer.class, 100);
    final long seed = getTypedParameter("seed", Long.class, System.currentTimeMillis());

    final TypedTableModel model = new TypedTableModel();
    model.addColumn("rowcount", Integer.class);
    model.addColumn("integer", Integer.class);
    model.addColumn("double", Double.class);
    model.addColumn("text", String.class);
    model.addColumn("text2", String.class);
    model.addColumn("date", Date.class);

    final Random random = new Random();
    random.setSeed(seed);

    final Calendar baseDate = new GregorianCalendar(2000, 1, 1);
    baseDate.setTimeZone(TimeZone.getTimeZone("UTC"));
    final long millis = baseDate.getTimeInMillis();
    for (int i = 0; i < limit; i++) {
      model.addRow(
          i,
          (int) (random.nextDouble() * Integer.MAX_VALUE) - (Integer.MAX_VALUE / 2),
          random.nextDouble() * Integer.MAX_VALUE,
          "Some Text with breaks " + i,
          "SomeTextWithoutBreaks" + i,
          new Date(millis + (long) (200 * random.nextDouble() * Integer.MAX_VALUE)));
    }

    return model;
  }
  @Test
  public void testSpeed() {
    long total = 0;
    UpperQuantile data = new UpperQuantile(5000);
    Random gen = RandomUtils.getRandom();
    for (int i = 0; i < 10000; i++) {
      data.add(gen.nextDouble());
    }
    data.clear();
    int n = 100000;
    for (int i = 0; i < n; i++) {
      double x = gen.nextDouble();
      long t0 = System.nanoTime();
      data.add(x);
      long t1 = System.nanoTime();
      total += t1 - t0;
    }
    // time per insert should be less than a micro-second.  Typically this actually comes out ~300
    // ns
    log.debug("t = {} us", total / 1e9 / n / 1e-6);
    Assert.assertTrue(total / 1e9 / n < 100e-6);

    total = 0;
    for (int i = 0; i < 10; i++) {
      double q = gen.nextDouble() * 0.01 + 0.99;
      long t0 = System.nanoTime();
      double r = data.quantile(q);
      long t1 = System.nanoTime();
      Assert.assertEquals(String.format("q=%.3f r=%.3f i=%d", q, r, i), q, r, 0.01);
      total += t1 - t0;
    }
    log.debug("t = {} us", total / 1e9 / 10 / 1e-6);
  }
  private void init() {
    this.birdsFlock = new Bird[this.numOfObjects];
    this.bestSolutions = new double[this.dimensions];
    this.bestFitness = Double.MAX_VALUE;
    Random rnd = new Random();

    for (int bird = 0; bird < this.numOfObjects; bird++) {
      double[] randomPositions = new double[this.dimensions];
      double[] randomVelocities = new double[this.dimensions];
      Arrays.fill(randomPositions, 0.0);
      Arrays.fill(randomVelocities, 0.0);

      for (int i = 0; i < this.dimensions; i++) {
        randomPositions[i] =
            (this.MAX_POSITION - this.MIN_POSITION) * rnd.nextDouble() + this.MIN_POSITION;
        randomVelocities[i] =
            (this.MAX_POSITION * 0.1 - this.MIN_POSITION * 0.1) * rnd.nextDouble()
                + this.MIN_POSITION;
      }

      double fitness = this.costFunction.apply(randomPositions);

      this.birdsFlock[bird] =
          new Bird(randomPositions, randomVelocities, randomPositions, fitness, fitness);

      if (this.birdsFlock[bird].currentFitness < this.bestFitness) {
        this.bestFitness = this.birdsFlock[bird].currentFitness;

        for (int i = 0; i < this.dimensions; i++) {
          this.bestSolutions[i] = this.birdsFlock[bird].position[i];
        }
      }
    }
  }
Beispiel #20
0
 /**
  * Creates random circles on a map. Currently the only map generation algorithm.
  *
  * @param f Used field
  * @param n Number of circles
  * @param maxr Maximal radius of circles
  */
 public static void randomCircles(Field f, int n, double maxr) {
   for (int i = 0; i < n; i++) {
     f.createCircle(
         new Vector2D(rand.nextDouble() * f.getTilesX(), rand.nextDouble() * f.getTilesY()),
         rand.nextDouble() * maxr);
   }
 }
  @Override
  public Iterator<IntermediateSampleData<T>> sampleInPartition(Iterator<T> input) {
    if (numSamples == 0) {
      return EMPTY_INTERMEDIATE_ITERABLE;
    }

    // This queue holds fixed number elements with the top K weight for current partition.
    PriorityQueue<IntermediateSampleData<T>> queue =
        new PriorityQueue<IntermediateSampleData<T>>(numSamples);
    int index = 0;
    IntermediateSampleData<T> smallest = null;
    while (input.hasNext()) {
      T element = input.next();
      if (index < numSamples) {
        // Fill the queue with first K elements from input.
        queue.add(new IntermediateSampleData<T>(random.nextDouble(), element));
        smallest = queue.peek();
      } else {
        double rand = random.nextDouble();
        // Remove the element with the smallest weight, and append current element into the queue.
        if (rand > smallest.getWeight()) {
          queue.remove();
          queue.add(new IntermediateSampleData<T>(rand, element));
          smallest = queue.peek();
        }
      }
      index++;
    }
    return queue.iterator();
  }
    public Point getRandomPoint(Collection<Point> keepDistance, float d) {
      Point res = null;
      Random rnd = new Random();

      boolean distance = false;
      while (!distance) {
        double r =
            Math.sqrt(rnd.nextDouble()); // sqrt damit groessere r etwas wahrscheinlicher werden
        double a = rnd.nextDouble() * 2 * Math.PI;
        double x = Math.cos(a) * w * 0.5 * r;
        double y = Math.sin(a) * h * 0.5 * r;
        x *= 0.8;
        y *= 0.8; // damit es auch echt drin ist
        res = new Point((int) x + p.x + w / 2, (int) y + p.y + h / 2);

        distance = true;
        for (Point p : keepDistance) {
          if (p.distance(res) < d) {
            distance = false;
            break;
          }
        }
      }

      return res;
    }
  @SideOnly(Side.CLIENT)
  public void render(double x, double y, double z, double gunRadius) {
    if (isMinigunActivated()
        && getMinigunSpeed() == MAX_GUN_SPEED
        && gunAimedAtTarget
        && attackTarget != null) {
      GL11.glPushMatrix();
      GL11.glScaled(1, 1, 1);
      GL11.glTranslated(-x, -y, -z);
      GL11.glDisable(GL11.GL_TEXTURE_2D);
      // GL11.glDisable(GL11.GL_LIGHTING);
      RenderUtils.glColorHex(0xFF000000 | getAmmoColor());
      for (int i = 0; i < 5; i++) {

        Vec3 vec =
            Vec3.createVectorHelper(
                    attackTarget.posX - x, attackTarget.posY - y, attackTarget.posZ - z)
                .normalize();
        minigunFire.startX = x + vec.xCoord * gunRadius;
        minigunFire.startY = y + vec.yCoord * gunRadius;
        minigunFire.startZ = z + vec.zCoord * gunRadius;
        minigunFire.endX = attackTarget.posX + rand.nextDouble() - 0.5;
        minigunFire.endY = attackTarget.posY + attackTarget.height / 2 + rand.nextDouble() - 0.5;
        minigunFire.endZ = attackTarget.posZ + rand.nextDouble() - 0.5;
        minigunFire.render();
      }
      GL11.glColor4d(1, 1, 1, 1);
      // GL11.glEnable(GL11.GL_LIGHTING);
      GL11.glEnable(GL11.GL_TEXTURE_2D);
      GL11.glPopMatrix();
    }
  }
Beispiel #24
0
  /// <summary>
  /// Similar in functionality to singleThrow(double[] probabilities). However the 'probabilities'
  // array is
  /// not normalised. Therefore if the total goes beyond 1 then we allow extra throws, thus if the
  // total is 10
  /// then we perform 10 throws.
  /// </summary>
  /// <param name="probabilities"></param>
  /// <returns></returns>
  public static int[] multipleThrows(double[] probabilities) {
    double pTotal = 0; // Total probability
    int numberOfThrows;

    // ----- Determine how many throws of the ball onto the wheel.
    for (int i = 0; i < probabilities.length; i++) pTotal += probabilities[i];

    // If total probabilty is > 1 then we take this as meaning more than one throw of the ball.
    double pTotalInteger = Math.floor(pTotal);
    double pTotalRemainder = pTotal - pTotalInteger;
    numberOfThrows = (int) pTotalInteger;

    if (random.nextDouble() <= pTotalRemainder) numberOfThrows++;

    // ----- Now throw the ball the determined number of times. For each throw store an integer
    // indicating the outcome.
    int[] outcomes = new int[numberOfThrows];

    for (int i = 0; i < numberOfThrows; i++) {
      double throwValue = random.nextDouble() * pTotal;
      double accumulator = 0;

      for (int j = 0; j < probabilities.length; j++) {
        accumulator += probabilities[j];

        if (throwValue <= accumulator) {
          outcomes[i] = j;
          break;
        }
      }
    }

    return outcomes;
  }
Beispiel #25
0
  public static void main(String[] args) {
    System.out.println("Buffon Pi Estimation");
    System.out.println("Enter the number of tries: ");
    Scanner in = new Scanner(System.in);
    int tries = in.nextInt();

    Random generator = new Random(42);

    // YOUR CODE HERE
    // Calculate the number of hits.
    // generate a yLow, the lowest point, or the farthest point on
    // the needle from the line (a number between 0 and 2).
    double hits = 0;
    for (int i = 0; i < tries; i++) {
      double yLow = generator.nextDouble() * 2;
      // generate a random angle a between 0 and 180 degrees.
      double angle = generator.nextDouble() * 180;
      // yHigh is yLow plus the sine of a.
      double angleInRadians = Math.toRadians(angle);
      double yHigh = yLow + Math.sin(angleInRadians);
      if (yHigh > 2) {
        hits++;
      }
    }
    // if yHigh is above the line (the line is at a height of 2),
    // the needle is touching the line, and counts as a hit.
    // Hint: Math.sin takes an angle in radians.

    double piEstimate = (double) (tries / hits);
    System.out.println("hits were: " + hits);
    System.out.println(piEstimate);
  }
  public void generateTakeoff() {
    Random rand = new Random(); // new random number

    if (rand.nextDouble()
        <= Glider.getProbability()) { // if number matches the Glider's probability
      Aircraft ac = new Glider(); // create new Glider object
      ac.setPrefix("tk_"); // debug info
      ac.setNumber(tcounter); // debug info
      to.addAircraft(ac); // add aircraft to the queue
      tcounter++;
    } else if (rand.nextDouble()
        <= (Glider.getProbability()
            + LightAircraft
                .getProbability())) { // if number matches the Light Aircraft's probability
      Aircraft ac = new LightAircraft(); // create new LightAircraft object
      ac.setPrefix("tk_"); // debug info
      ac.setNumber(tcounter); // debug info
      to.addAircraft(ac); // add aircraft to the queue
      tcounter++;
    } else if (rand.nextDouble()
        <= (Glider.getProbability()
            + LightAircraft.getProbability()
            + Commercial
                .getProbability())) { // if number matches the Commercial Aircraft's probability
      Aircraft ac = new Commercial(); // create new Commercial object
      ac.setPrefix("tk_"); // debug info
      ac.setNumber(tcounter); // debug info
      to.addAircraft(ac); // add aircraft to the queue
      tcounter++;
    }
  }
Beispiel #27
0
  private Gene mutateLink(NEATLinkGene mutatee) {
    double perturbRandVal = perturbRand.nextDouble();
    double disableRandVal = disableRand.nextDouble();
    double newWeight;
    NEATLinkGene mutated = mutatee;

    if (perturbRandVal < this.pPerturb) {
      if (this.pWeightReplaced > perturbRand.nextDouble()) {
        newWeight = MathUtils.nextPlusMinusOne();
      } else {
        newWeight = mutatee.getWeight() + MathUtils.nextClampedDouble(-perturb, perturb);
      }
      //			newWeight = mutatee.getWeight() + MathUtils.nextClampedDouble(-PERTURB, PERTURB);
      mutated =
          new NEATLinkGene(
              mutatee.getInnovationNumber(),
              mutatee.isEnabled(),
              mutatee.getFromId(),
              mutatee.getToId(),
              newWeight);
    }

    if (disableRandVal < this.pToggle) {
      if (this.featureSelection) {
        mutated.setEnabled(!mutated.isEnabled());
      }
    }

    return (mutated);
  }
Beispiel #28
0
  /**
   * 67% of time spent in LogConditionalObjectiveFunction.rvfcalculate() 29% of time spent in
   * dataset construction (11% in RVFDataset.addFeatures(), 7% rvf incrementCount(), 11% rest)
   *
   * <p>Single threaded, 4700 ms Multi threaded, 700 ms
   *
   * <p>With same data, seed 42, 245 ms With reordered accesses for cacheing, 195 ms Down to 80% of
   * the time, not huge but a win nonetheless
   *
   * <p>with 8 cpus, a 6.7x speedup -- almost, but not quite linear, pretty good
   */
  public static void benchmarkRVFLogisticRegression() {
    RVFDataset<String, String> data = new RVFDataset<>();
    for (int i = 0; i < 10000; i++) {
      Random r = new Random(42);
      Counter<String> features = new ClassicCounter<>();

      boolean cl = r.nextBoolean();

      for (int j = 0; j < 1000; j++) {
        double value;
        if (cl && i % 2 == 0) {
          value = (r.nextDouble() * 2.0) - 0.6;
        } else {
          value = (r.nextDouble() * 2.0) - 1.4;
        }
        features.incrementCount("f" + j, value);
      }

      data.add(new RVFDatum<>(features, "target:" + cl));
    }

    LinearClassifierFactory<String, String> factory = new LinearClassifierFactory<>();

    long msStart = System.currentTimeMillis();
    factory.trainClassifier(data);
    long delay = System.currentTimeMillis() - msStart;
    System.out.println("Training took " + delay + " ms");
  }
Beispiel #29
0
  public static Observation makeObservationFor(POMDPDomain d, GroundedAction a, POMDPState s) {
    ObjectInstance indexer = s.getObject(Names.OBJ_INDEXER);
    int index = indexer.getDiscValForAttribute(Names.ATTR_INDEX);

    if (index == iterations) {
      return d.getObservation(Names.OBS_COMPLETE);
    }

    ObjectInstance leftDoor = s.getObject(Names.OBJ_LEFT_DOOR);
    ObjectInstance rightDoor = s.getObject(Names.OBJ_RIGHT_DOOR);

    int leftDoorTiger = leftDoor.getDiscValForAttribute(Names.ATTR_TIGERNESS);
    java.util.Random random = new java.util.Random();

    if (a.action.getName().equals(Names.ACTION_LISTEN)) {

      Observation left =
          d.getObservation(Names.OBS_LEFT_DOOR + random.nextInt(observationsPerState));
      Observation right =
          d.getObservation(Names.OBS_RIGHT_DOOR + random.nextInt(observationsPerState));

      if (leftDoorTiger == 1) {
        return random.nextDouble() < 1 - noise ? left : right;
      } else {
        return random.nextDouble() < 1 - noise ? right : left;
      }
    } else {
      return d.getObservation(Names.OBS_NULL);
    }
  }
 public SomePrimitives() {
   Random random = new Random(1776L);
   d = random.nextDouble();
   i = random.nextInt(1000);
   b = random.nextBoolean();
   s = "" + random.nextDouble();
 }