void SolarPlacer::placeOneNode(MultilevelGraph &MLG) { NodeMerge * lastNM = MLG.getLastMerge(); double x = 0.0; double y = 0.0; int i = 0; node sun = MLG.getNode(lastNM->m_changedNodes.front()); std::vector< std::pair<int, double> > positions = lastNM->m_position; node merged = MLG.undoLastMerge(); if (positions.size() > 0) { for (const std::pair<int, double> &p : positions) { double factor = p.second; node other_sun = MLG.getNode(p.first); i++; x += MLG.x(sun) * factor + MLG.x(other_sun) * (1.0f-factor); y += MLG.y(sun) * factor + MLG.y(other_sun) * (1.0f-factor); } } else { i++; x += MLG.x(sun); y += MLG.y(sun); } OGDF_ASSERT(i > 0); if (positions.size() == 0 || m_randomOffset) { x += randomDouble(-1.0, 1.0); y += randomDouble(-1.0, 1.0); } MLG.x(merged, (x / static_cast<double>(i))); MLG.y(merged, (y / static_cast<double>(i))); }
std::vector<cmst::Point2D> cmst::TestcaseGenerator(int num_lower_bound/* = 100*/, int num_upper_bound/* = 500*/, double x_upper_bound/* = MAX_X*/, double y_upper_bound/* = MAX_Y*/) { // srand(time(NULL)); int numberPoints = randomInt(num_lower_bound, num_upper_bound); #ifdef DEBUG debugout << "Generating " << numberPoints << " random points" << std::endl; #endif // DEBUG std::vector<cmst::Point2D> points; for(int i = 0; i < numberPoints; i++) points.push_back(cmst::Point2D(randomDouble(0.0, x_upper_bound), randomDouble(0.0, y_upper_bound))); // delete the same points std::sort(points.begin(), points.end()); points.erase(std::unique(points.begin(), points.end()), points.end()); while (points.size() < numberPoints) { cmst::Point2D p( randomDouble(0.0, x_upper_bound), randomDouble(0.0, y_upper_bound) ); if (std::lower_bound(points.begin(), points.end(), p) == points.end()) { points.push_back(p); std::sort(points.begin(), points.end()); } } return points; }
void BarycenterPlacer::placeOneNode(MultilevelGraph &MLG) { node merged = MLG.undoLastMerge(); double x = 0.0; double y = 0.0; double i = 0.0; for(adjEntry adj : merged->adjEdges) { if(m_weightedPositions) { double weight = 1.0 / MLG.weight(adj->theEdge()); i = i + weight; x += MLG.x(adj->twinNode()) * weight; y += MLG.y(adj->twinNode()) * weight; } else { i = i + 1.f; x += MLG.x(adj->twinNode()); y += MLG.y(adj->twinNode()); } } OGDF_ASSERT(i > 0); x = x / i; y = y / i; MLG.x(merged, x + ((m_randomOffset)?(float)randomDouble(-1.0, 1.0):0.f)); MLG.y(merged, y + ((m_randomOffset)?(float)randomDouble(-1.0, 1.0):0.f)); }
CFlower::CFlower() { // initialise geometry parameters nSlices=16; nStacks=16; angleWithXAxis=(GLfloat) randomDouble(0,90); // in degree (!) stemRadius=0.02; stemHeight=(GLfloat) randomDouble(0.3,0.5); leafLength=stemHeight/2; leafAngle=(GLfloat) randomDouble(30,70); // in degree (!) leafHeight1=stemHeight/3.5; leafHeight2=stemHeight/2.5; blossomCentreRadius=stemHeight/10; petalLength=4*blossomCentreRadius; numPetals=37; // initialise material parameters no_shininess[0]=50; mat_specular[0]=0.3; mat_specular[1]=0.3; mat_specular[2]=0.3; mat_specular[3]=1; mat_stem[0]=0.2f; mat_stem[1]=0.5f; mat_stem[2]=0.1f; mat_stem[3]=1; mat_blossom_centre[0]=0.7f; mat_blossom_centre[1]=0.65f; mat_blossom_centre[2]=0.15f; mat_blossom_centre[3]=1; mat_petal[0]=0.65f; mat_petal[1]=0.25f; mat_petal[2]=0.15f; mat_petal[3]=1; }
void GeneticAlgorithm::resetParameters(int nPopulation, double scaleFactor, double crossingProbability){ _scaleFactor = scaleFactor; _crossingProbability = crossingProbability; _nPopulation = nPopulation; delete [] _populationParametersOld; delete [] _populationParametersNew; _populationParametersOld = (Parameters::fitParameters *) mkl_malloc(sizeof(Parameters::fitParameters)*nPopulation,16); _populationParametersNew = (Parameters::fitParameters *) mkl_malloc(sizeof(Parameters::fitParameters)*nPopulation,16); for(int i = 0; i < _nPopulation; i++){ _populationParametersOld[i].c11 = (randomDouble(0.0,1.0))*pow(10,9); _populationParametersOld[i].c22 = _populationParametersOld[i].c11; _populationParametersOld[i].c33 = _populationParametersOld[i].c11; _populationParametersOld[i].c44 = (randomDouble(0.0,1.0))*pow(10,9); _populationParametersOld[i].c55 = _populationParametersOld[i].c44; _populationParametersOld[i].c66 = _populationParametersOld[i].c44; _populationParametersOld[i].c12 = (randomDouble(0.0,1.0))*pow(10,9); _populationParametersOld[i].c13 = _populationParametersOld[i].c12; _populationParametersOld[i].c23 = _populationParametersOld[i].c12; _populationParametersOld[i].chiSq = 1; _populationParametersOld[i].chiSq = calculateResidual(&_populationParametersOld[i],0); } //delete _integerDistribution; delete [] ints1; delete [] ints2; delete [] ints3; ints1 = new int[_nPopulation]; ints2 = new int[_nPopulation]; ints3 = new int[_nPopulation]; }
void SolarPlacer::placeOneNode(MultilevelGraph &MLG) { NodeMerge * lastNM = MLG.getLastMerge(); float x = 0.0; float y = 0.0; int i = 0; node sun = MLG.getNode(lastNM->m_changedNodes.front()); std::vector< std::pair<int, float> > positions = lastNM->m_position; node merged = MLG.undoLastMerge(); if (positions.size() > 0) { for (std::vector< std::pair<int, float> >::iterator j = positions.begin(); j != positions.end(); j++) { float factor = (*j).second; node other_sun = MLG.getNode((*j).first); i++; x += MLG.x(sun) * factor + MLG.x(other_sun) * (1.0f-factor); y += MLG.y(sun) * factor + MLG.y(other_sun) * (1.0f-factor); } } else { i++; x += MLG.x(sun); y += MLG.y(sun); } OGDF_ASSERT(i > 0); if (positions.size() == 0 || m_randomOffset) { x += (float)randomDouble(-1.0, 1.0); y += (float)randomDouble(-1.0, 1.0); } MLG.x(merged, (x / static_cast<float>(i))); MLG.y(merged, (y / static_cast<float>(i))); }
/** * @brief AgentCluster::moveRandomly Moves the agent randomly across the search space, a distance * related to the Agent's foraging range. If the newly selected position has a lower hapiness * level than the original, the agent is moved back to the original spot. * @param agent Agent to move. */ void AgentCluster::moveRandomly(Agent *agent) { double initialX = agent->x; double initialY = agent->y; double initialHappiness = agent->happiness; double moveMagnitude = randomDouble(0.0, agent->foragingRange * RANDOM_MOVE_FACTOR + 1); double moveDirection = randomDouble(0, 360) * (PI / 180.0); double posX = initialX + (cos(moveDirection) * moveMagnitude); double posY = initialY + (sin(moveDirection) * moveMagnitude); Q_ASSERT_X(nanTest(posX), "Failed NaN", __FUNCTION__); Q_ASSERT_X(nanTest(posY), "Failed NaN", __FUNCTION__); if (posX > m_dataMaxX) posX = m_dataMaxX; else if (posX < m_dataMinX) posX = m_dataMinX; if (posY > m_dataMaxY) posY = m_dataMaxY; else if (posY < m_dataMinY) posY = m_dataMinY; agent->x = posX; agent->y = posY; double newHappiness = calculateHappiness(agent); if (newHappiness >= initialHappiness) { //did we find a better position? agent->happiness = newHappiness; return; } //otherwise, move back... agent->x = initialX; agent->y = initialY; }
void GeneticAlgorithm::cubicParameters(double * pOld, double * pNew, double * rand1, double * rand2, double * rand3){ double p = randomDouble(0,1); if(p > _crossingProbability){ pNew[0] = pOld[0]; } else{ pNew[0] = rand1[0] + _scaleFactor*(rand2[0] - rand3[0]); } p = randomDouble(0,1); if(p > _crossingProbability){ pNew[3] = pOld[3]; } else{ pNew[3] = rand1[3] + _scaleFactor*(rand2[3] - rand3[3]); } p = randomDouble(0,1); if(p > _crossingProbability){ pNew[6] = pOld[6]; } else{ pNew[6] = rand1[6] + _scaleFactor*(rand2[6] - rand3[6]); } pNew[1] = pNew[0]; pNew[2] = pNew[0]; pNew[4] = pNew[3]; pNew[5] = pNew[3]; pNew[7] = pNew[6]; pNew[8] = pNew[6]; return; }
void RandomPlacer::placeOneNode(MultilevelGraph &MLG, DPoint center, double radius) { node merged = MLG.undoLastMerge(); float angle = (float)randomDouble(0.0, 2 * Math::pi); float randRadius = float(sqrt(randomDouble(0.0, radius * radius))); MLG.x(merged, cos(angle) * randRadius + ((m_randomOffset)?(float)randomDouble(-1.0, 1.0):0.f)); MLG.y(merged, sin(angle) * randRadius + ((m_randomOffset)?(float)randomDouble(-1.0, 1.0):0.f)); }
void ZeroPlacer::placeOneNode(MultilevelGraph &MLG) { NodeMerge * NM = MLG.getLastMerge(); node parent = MLG.getNode(NM->m_changedNodes[0]); node merged = MLG.undoLastMerge(); MLG.x(merged, MLG.x(parent) + ((m_randomOffset)?(float)randomDouble(-m_randomRange, m_randomRange):0.f)); MLG.y(merged, MLG.y(parent) + ((m_randomOffset)?(float)randomDouble(-m_randomRange, m_randomRange):0.f)); }
void diamondSquareRecurse(double* map, int x, int y, int w, int h, double noiseScale) { if (w <= 2 || h <= 2) { return; } //do diamond square for this region int x2 = x + w-1; //rightmost cell int y2 = y + h-1; //bottom cell double topLeft = get(map, y, x); double topRght = get(map, y, x2); double botLeft = get(map, y2, x); double botRght = get(map, y2, x2); //diamond step double averageCorners = (topLeft + topRght + botLeft + botRght)/4.0; double newCenter = averageCorners - ((randomDouble() - 0.5) * noiseScale * 2); //getNoise(step); int centerX = x + w / 2; int centerY = y + h / 2; set(map, centerY, centerX, newCenter); //square step int midX = x + w/2; int midY = y + h/2; //top = avg(tl, tr) + noise double top = (topLeft + topRght)/2.0 + (randomDouble() - 0.5) * noiseScale; if (get(map, y, midX) == -1.0) set(map, y, midX, top); //bot = avg(bl, br) + noise double bot = (botLeft + botRght)/2.0 + (randomDouble() - 0.5) * noiseScale; if (get(map, y2, midX) == -1.0) set(map, y2, midX, bot); //lef = avg(tl, bl) + noise double lef = (topLeft + botLeft)/2.0 + (randomDouble() - 0.5) * noiseScale; if (get(map, midY, x) == -1.0) set(map, midY, x, lef); //rig = avg(tr, br) + noise double rig = (topRght + botRght)/2.0 + (randomDouble() - 0.5) * noiseScale; if (get(map, midY, x2) == -1.0) set(map, midY, x2, rig); //if can divide, do so for each quarter int newW = w/2+1; int newH = h/2+1; if (newW < 3 && newH < 3) { return; } newW = max(newW, 3); newH = max(newH, 3); double newNoiseScale = noiseScale * pow(2.0, -0.75); diamondSquareRecurse(map, x, y, newW, newH, newNoiseScale); diamondSquareRecurse(map, centerX, y, newW, newH, newNoiseScale); diamondSquareRecurse(map, x, centerY, newW, newH, newNoiseScale); diamondSquareRecurse(map, centerX, centerY, newW, newH, newNoiseScale); }
Monster::Monster(Point p) : pos(p) { double rd = randomDouble(); walkDirection = rd * DOUBLE_PI; viewDirection = walkDirection; rd = randomDouble(); range = minViewAngle + rd * (maxViewAngle - minViewAngle); speed = 0.8; hunt = false; visible = true; //range = PI / 20; }
void FunctionTree::generateGrow(Function *currentNode, int maxDepth){ if (maxDepth > 1) { currentNode->l = new Function; currentNode->l->p = currentNode; currentNode->l->rChild = false; if (randomDouble()>growTerminalRate) generateGrow(currentNode->l, maxDepth-1); if (currentNode->functionType < 5) { currentNode->r = new Function; currentNode->r->p = currentNode; currentNode->r->rChild = true; if (randomDouble()>growTerminalRate) generateGrow(currentNode->r, maxDepth-1); } } }
/** * @brief AgentCluster::start Runs the AgentCluster algorithm. * @details It initializes the agent population, and then simply calls the functions built for each * of the three main clustering phases. */ void AgentCluster::start() { //Init the population to random positions; m_dataMinX = m_data[0]->x; m_dataMinY = m_data[0]->y; m_dataMaxX = m_dataMinX; m_dataMaxY = m_dataMinY; for (unsigned int i = 1; i < m_data.size(); i++) { ClusterItem* item = m_data[i]; if (item->x > m_dataMaxX) m_dataMaxX = item->x; else if (item->x < m_dataMinX) m_dataMinX = item->x; if (item->y > m_dataMaxY) m_dataMaxY = item->y; else if (item->y < m_dataMinY) m_dataMinY = item->y; } if (m_swarmSize == -1) { m_swarmSize = (int)((double)m_data.size() * SWARM_SIZE_FACTOR); } for (int i = 0; i < m_swarmSize; i++) { Agent* agent = new Agent(); agent->x = randomDouble(m_dataMinX, m_dataMaxX); agent->y = randomDouble(m_dataMinY, m_dataMaxY); m_agents.push_back(agent); } printf("Created a swarm containing %i agents...\n", m_swarmSize); m_agentSensorRange = averageClusterDistance() * SENSOR_TO_AVG_DIST_RATIO; m_minRange = m_agentSensorRange * 0.2; m_agentStepSize = m_agentSensorRange * STEP_SIZE_TO_SENSOR_RATIO; m_dataConcentrationSlope = -(m_agentSensorRange - m_minRange); m_crowdingConcetrationSlope = (double)(-1) / m_agents.size(); for (unsigned int i = 0; i < m_agents.size(); i++) m_agents[i]->foragingRange = m_agentSensorRange / 2.0; //Start each of the three clustering phases, in order convergencePhase(); consolidationPhase(); assignmentPhase(); emit finished(); }
SampleTemplate SampleTemplateGenerator::generateTemplateFromPosition( const Vector2<double>& posSeen, const Vector2<double>& posReal, const Pose2D& postOdometry) const { SampleTemplate newTemplate; double r = posSeen.abs() + theFieldDimensions.goalPostRadius; double distUncertainty = sampleTriangularDistribution(standardDeviationGoalpostSampleBearingDistance); if(r+distUncertainty > standardDeviationGoalpostSampleBearingDistance) r += distUncertainty; Vector2<double> realPosition = posReal; double minY = std::max<double>(posReal.y - r, static_cast<double>(theFieldDimensions.yPosRightFieldBorder)); double maxY = std::min<double>(posReal.y + r, static_cast<double>(theFieldDimensions.yPosLeftFieldBorder)); Vector2<double> p; p.y = minY + randomDouble()*(maxY - minY); double xOffset(sqrt(sqr(r) - sqr(p.y - posReal.y))); p.x = posReal.x; p.x += (p.x > 0) ? -xOffset : xOffset; if(theFieldDimensions.isInsideCarpet(p) && checkTemplateClipping(p)) { double origAngle = (realPosition-p).angle(); double observedAngle = posSeen.angle(); Pose2D templatePose(origAngle-observedAngle, p); Pose2D odometryOffset = theOdometryData - postOdometry; templatePose += odometryOffset; newTemplate = templatePose; newTemplate.timestamp = theFrameInfo.time; } return newTemplate; }
/** * @brief AgentCluster::moveTowards Moves the first agent towards the second one. * @param agentOne The agent being moved. * @param agentTwo The agent who is being moved towards. */ void AgentCluster::moveTowards(Agent *agentOne, Agent *agentTwo) { double crowdingFactor = (agentOne->crowdingRange + agentTwo->crowdingRange) * 0.5; double agentDistance = pointDistance(agentOne->x, agentTwo->x, agentOne->y, agentTwo->y) - crowdingFactor; if (agentDistance == 0) return; double moveMagnitude = std::min(randomDouble(0, agentOne->foragingRange), agentDistance) * randomDouble(0, 0.9); double unitVectorX = (agentTwo->x - agentOne->x) / agentDistance; double unitVectorY = (agentTwo->y - agentOne->y) / agentDistance; double newX = agentOne->x + (moveMagnitude * unitVectorX); double newY = agentOne->y + (moveMagnitude * unitVectorY); Q_ASSERT_X(nanTest(newX), "Failed NaN", __FUNCTION__); Q_ASSERT_X(nanTest(newY), "Failed NaN", __FUNCTION__); if (newX > m_dataMaxX) newX = m_dataMaxX; else if (newX < m_dataMinX) newX = m_dataMinX; if (newY > m_dataMaxY) newY = m_dataMaxY; else if (newY < m_dataMinY) newY = m_dataMinY; agentOne->x = newX; agentOne->y = newY; agentOne->happiness = calculateHappiness(agentOne); }
Perlin::Perlin(int seed, int sx, int sy, double min, double max, int st, int oc, double pers) : sizeX(sx), sizeY(sy), step(st), octaves(oc), persistence(pers) { auto g = seed == 0 ? Generator() : Generator(seed); int maxWidth = (int) ceil(sizeX * pow(2, octaves - 1) / step); int maxHeight = (int) ceil(sizeY * pow(2, octaves - 1) / step); v = g.randomDouble(min, max, maxWidth * maxHeight); }
std::unique_ptr<Shape> ShapesWidget::createRandomShape() { double size = 6 + randomDouble() * 6; ShapeColor c = createRandomColor(); double x = size + randomDouble() * (width().value() - 2 * size); double y = size + randomDouble() * (height().value() - 2 * size); const unsigned amountOfShapes = 2; unsigned shapeId = randomInt(amountOfShapes); if (shapeId == 0) return cpp14::make_unique<Circle>(WPointF(x, y), c, size); else return cpp14::make_unique<Rectangle>(WPointF(x, y), c, size); }
/** * Fills the buffer with generated white noise samples. * * @param samplesCount how many samples to generate */ void WhiteNoiseGenerator::generate(std::size_t samplesCount) { m_buffer.resize(samplesCount); for (std::size_t i = 0; i < samplesCount; ++i) { m_buffer[i] = m_amplitude * (randomDouble() - 0.5); } }
// ##################################################################### double randomDoubleFromNormal(const double s) { double sum = 0; for(int i=0; i<12; i++){ sum += randomDouble()*2*s - s; } return sum/2; }
FunctionTree::FunctionTree(){ error = -1; rootNode = new Function; if ((randomDouble()) > 0.5) generateFull(rootNode, maxInitialTreeDepth); else generateGrow(rootNode, maxInitialTreeDepth); writeFunctionString(); rootNode->reduce(); calculateError(); }
void NPC::push() { moveTimer.stop(); // Stop the clock! // If we're just standing here... if (direction == -1) { // Move somewhere for a bit duration = randomDouble(0.5, 4.0); direction = randomInt(0, 3); } else { // If we're on the move... // Take a breather duration = randomDouble(2.0, 6.0); direction = -1; } moveDirection(); // Set the moving* bools moveTimer.start(int(duration * 1000.0)); // Start the clock! }
void UnitTest::preparePointData(vector<pair<double,double> > &pnts, const Envelope& bbox, const uint64_t size) { set<pair<double,double> > container; srand(time(NULL)); while(container.size() < size) container.insert(std::make_pair<double,double>(randomDouble(bbox.xmin, bbox.xmax) ,randomDouble(bbox.ymin, bbox.ymax))); for(auto itor = container.begin(); itor != container.end(); ++itor) pnts.push_back(std::move(*itor)); }
NPC::NPC(QString charsheet, QGraphicsItem *parent) : QObject(), Character(charsheet, parent) { direction = -1; // Not moving to start with duration = randomDouble(2.0, 6.0); // Stand here for a while // The moveTimer compels us moveTimer.connect(&moveTimer, SIGNAL(timeout()), this, SLOT(push())); moveTimer.setSingleShot(true); // We reset this with a new duration manually moveTimer.start(int(duration * 1000.0)); // Start the clock (note msec conversion) }
void initMap(double* map) { for (int y = 0; y < HEIGHT; y++) { for (int x = 0; x < WIDTH; x++) { double setTo = (fabs(y - HEIGHT/(float)2) / (HEIGHT/(float)2)) * (fabs(x - WIDTH/(float)2) / (WIDTH/(float)2)); setTo = -1.0; //fmin(fmax(setTo, 0), 1); //0.5; //randomDouble(); //((double)y/HEIGHT) * ((double)x/WIDTH)); set(map, y, x, setTo); } } set(map, 0, 0, randomDouble()); set(map, 0, WIDTH-1, randomDouble()); set(map, HEIGHT-1, 0, randomDouble()); set(map, HEIGHT-1, WIDTH-1, randomDouble()); }
int main( int argc, char** argv ) { // Seed the random number generator // with the time measured in seconds. // "time_t" is a just another name for // a long (64 bit) integer. time_t t = time(NULL) ; srand( t ) ; double radius = 0.1; Vector spheres[51]; printPOVPrefix(); int i; for( i = 0; i < 50; i++ ) { double x = randomDouble(); double y = randomDouble(); double z = randomDouble(); Vector center = makeVector( x, y, z ); spheres[i] = center; } // Create spheres located randomly at centers of components with values between 0 & 1 int j, k; for(j = 0; j < 50; j++){ for(k = 0; k< 50; k++) { if( magnitude ( diff(spheres[j],spheres[k])) > 0.2){ printSphere(spheres[j], radius, spheres[j] ); } } }// print non intersecting spheres with colors derived from their center values } // main( int, char** )
// ##################################################################### int randomUpToNotIncluding(const int n) { // NOTE: we don't do (RAND%n) because the low-order bits of the // random number may be less random than the high-order bits const int result = int(randomDouble() * n); // randomDouble() is supposed to be in [0.0, 1.0), but just in case // randomDouble()*n happens to equal n due to floating-point // weirdness, let's return n-1 to fulfill the "NotIncluding" part of // our contract: if (result == n) return n-1; return result; }
/** * Fills the buffer with generated pink noise samples. * * @param samplesCount how many samples to generate */ void PinkNoiseGenerator::generate(std::size_t samplesCount) { m_buffer.resize(samplesCount); // Voss algorithm initialization maxKey = 0xFFFF; key = 0; for (std::size_t i = 0; i < whiteSamplesNum; ++i) { whiteSamples[i] = randomDouble() - 0.5; } for (std::size_t i = 0; i < samplesCount; ++i) { m_buffer[i] = m_amplitude * pinkSample(); } }
Neuron::Neuron(size_t numInputs, bool hasBias) { this->netInput = 0; this->numInputs = numInputs; if (hasBias) { this->numInputs += 1; } double XMin = -1; double XMax = 1; for (size_t n = 0; n < this->numInputs; ++n) { double x = randomDouble(XMin, XMax); this->weights.push_back(x); this->deltaWeights.push_back(0); } }
/** * Generates a single pink noise sample using Voss algorithm. * * @return pink noise sample */ double PinkNoiseGenerator::pinkSample() { int lastKey = key; double sum = 0; key++; if (key > maxKey) key = 0; int diff = lastKey ^ key; for (std::size_t i = 0; i < whiteSamplesNum; ++i) { if (diff & (1 << i)) whiteSamples[i] = randomDouble() - 0.5; sum += whiteSamples[i]; } return sum / whiteSamplesNum; }