Vector3 SamplerUtil::RandHemiSphereSample(const Vector3& n) { DOUBLE x, y, z; do { x = RandDouble() - .5; y = RandDouble() - .5; z = RandDouble() - .5; } while (x*x + y*y + z*z > 1.0 || n[0]*x + n[1]*y + n[2]*z < 0.0); return Vector3(x, y, z).GetDirection(); }
void SamplerUtil::MultiJitteredSamples(DOUBLE* samples, UINT32 x, UINT32 y) { DOUBLE subCellWidth = 1.0f / (y*x); for (UINT32 i = 0; i < y; ++i) { for (UINT32 j = 0; j < x; ++j) { *(samples++) = i*x*subCellWidth + j*subCellWidth + RandDouble()*subCellWidth; *(samples++) = j*y*subCellWidth + i*subCellWidth + RandDouble()*subCellWidth; } } }
void SamplerUtil::JitteredSamples(DOUBLE* samples, UINT32 x, UINT32 y) { DOUBLE dx = 1.0f / x; DOUBLE dy = 1.0f / y; for (UINT32 i = 0; i < x; ++i) { for (UINT32 j = 0; j < y; ++j) { *(samples++) = dx*i + dx*RandDouble(); *(samples++) = dy*j + dy*RandDouble(); } } }
//2006-10-05 - changed to support both SafetyPackets and regular Packets -MH void CarModel::CreateMessage(Packet * msg) { switch(msg->m_ePacketType) { default: case ptGeneric: { msg->m_ID.srcID.iSeqNumber = GetNextSequenceNumber(); msg->m_ID.srcID.ipCar = m_ipCar; msg->m_ID.iRXSeqNumber = (unsigned)-1; msg->m_ptTXPosition = m_ptPosition; msg->m_ipTX = m_ipCar; msg->m_ipRX = 0; msg->m_tTX = GetCurrentTime() + MakeTime(RandDouble(0., ToDouble(m_tDelay))); msg->m_tRX = msg->m_tTX; msg->m_iRSSI = PACKET_RSSI_UNAVAILABLE; msg->m_iSNR = PACKET_SNR_UNAVAILABLE; break; } case ptSafety: { ((SafetyPacket*)msg)->m_ID.srcID.iSeqNumber = GetNextSequenceNumber(); ((SafetyPacket*)msg)->m_ID.srcID.ipCar = m_ipCar; ((SafetyPacket*)msg)->m_ID.iRXSeqNumber = (unsigned)-1; // msg.m_eType = Message::MessageTypeNormal; ((SafetyPacket*)msg)->m_tTime = m_tTimestamp; ((SafetyPacket*)msg)->m_tLifetime = m_tDelay; ((SafetyPacket*)msg)->m_ptPosition = ((SafetyPacket*)msg)->m_ptTXPosition = m_ptPosition; ((SafetyPacket*)msg)->m_iSpeed = ((SafetyPacket*)msg)->m_iTXSpeed = m_iSpeed; ((SafetyPacket*)msg)->m_iHeading = ((SafetyPacket*)msg)->m_iTXHeading = m_iHeading; ((SafetyPacket*)msg)->m_iRecord = m_iCurrentRecord; g_pMapDB->GetRelativeRecord(((SafetyPacket*)msg)->m_iRecord, ((SafetyPacket*)msg)->m_iCountyCode); ((SafetyPacket*)msg)->m_iTXRecord = ((SafetyPacket*)msg)->m_iRecord; ((SafetyPacket*)msg)->m_iTXCountyCode = ((SafetyPacket*)msg)->m_iCountyCode; ((SafetyPacket*)msg)->m_cDirection = ((SafetyPacket*)msg)->m_cTXDirection = m_bForwards ? MESSAGE_DIRECTION_FORWARDS : MESSAGE_DIRECTION_BACKWARDS; ((SafetyPacket*)msg)->m_iShapePoint = ((SafetyPacket*)msg)->m_iTXShapePoint = m_iCRShapePoint; ((SafetyPacket*)msg)->m_fProgress = ((SafetyPacket*)msg)->m_fTXProgress = m_fCRProgress; ((SafetyPacket*)msg)->m_ipTX = m_ipCar; ((SafetyPacket*)msg)->m_ipRX = 0; ((SafetyPacket*)msg)->m_tTX = GetCurrentTime() + MakeTime(RandDouble(0., ToDouble(m_tDelay))); ((SafetyPacket*)msg)->m_tRX = ((SafetyPacket*)msg)->m_tTX; ((SafetyPacket*)msg)->m_iRSSI = PACKET_RSSI_UNAVAILABLE; ((SafetyPacket*)msg)->m_iSNR = PACKET_SNR_UNAVAILABLE; break; } } }
int SimpleCommModel::ProcessEvent(SimEvent & event) { if (CarCommModel::ProcessEvent(event)) return 1; switch (event.GetEventID()) { case EVENT_CARCOMMMODEL_REBROADCAST: { RebroadcastMessage * pRBXMsg = (RebroadcastMessage *)event.GetEventData(); if (pRBXMsg != NULL) { struct timeval tNext = pRBXMsg->tIntervalHigh + (m_bJitter ? MakeTime(RandDouble(0., ToDouble(m_tRebroadcastInterval))) : m_tRebroadcastInterval); pRBXMsg->msg.m_tTX = event.GetTimestamp(); TransmitMessage(&(pRBXMsg->msg)); // only rebroadcast if there's time left pRBXMsg->tIntervalLow = pRBXMsg->tIntervalHigh; pRBXMsg->tIntervalHigh = pRBXMsg->tIntervalHigh + m_tRebroadcastInterval; if (pRBXMsg->msg.m_tTime + pRBXMsg->msg.m_tLifetime <= tNext) delete pRBXMsg; else { event.SetTimestamp(tNext); g_pSimulator->m_EventQueue.AddEvent(event); } } break; } default: break; } return 0; }
void TrainBackground::Update(CGameEngine *game, Vector2D p) { if ((p.x) * scrollRate - (tracksPosX + tracks->w) > 100) tracksPosX += tracks->w; if ((p.x) * scrollRate - (stationPosX + station->w) > 100) stationPosX += RandDouble(2500, 5000); train.Update(game, p); }
// Function for setting highlighting color, making sure that there is enough contrast to a black background void CLapPainter::MakeColor(const CExtendedLap* pLap, float* pR, float* pG, float* pB) { srand((int)pLap); // <-- makes sure that we randomize the colours consistently, so that lap plots don't change colour from draw to draw... if (m_pLapSupplier->GetDisplayOptions().fColorScheme) // Background color is black, make sure there is enough contrast with the lines { do { *pR = RandDouble(); *pG = RandDouble(); *pB = RandDouble(); } while(*pR + *pG + *pB < 0.5); glColor3d( *pR, *pG, *pB ); // Final color to use. Tells opengl to draw the following in the colour we just made up } else { do { *pR = RandDouble(); *pG = RandDouble(); *pB = RandDouble(); } while(*pR + *pG + *pB > 2.5); glColor3d( *pR, *pG, *pB ); // Final color to use. Tells opengl to draw the following in the colour we just made up } }
void Cannon::Kill(int k) { hp -= k; for (unsigned int i = 0; i < 5; ++i) explosions.push_back(new Explosion(pos + Vector2D(RandDouble(20, (double)sprite->w+40), RandDouble(-10, (double)sprite->w)), 1.0)); if (hp <= 0) { state = SO_DEAD; soundFire.Stop(); soundRev.Stop(); } }
void Ball::Serve(void) { // If ball is moving, cannot serve if (m_dVelocity[0] != 0 && m_dVelocity[1] != 0) return; // Random angle in radians (between 0 and 60 degrees) double dAngle = RandDouble(0, M_PI / 3.0) * RandParity(); int iHeight = GetEngine()->GetScreenHeight(); // Move upwards towards bricks (-1) m_dVelocity[1] = -1 * iHeight / 48.0 * cos(dAngle); m_dVelocity[0] = iHeight / 48.0 * sin(dAngle); }
QString QAutoGenDialog::GetRandomParameter(const QString & strParam, const QString & strValue, const ModelParameter & param) { QString strRet; QStringList listRandom = QStringList::split(';', strValue); unsigned int iRandom = RandUInt(0, listRandom.size()); int iSep = strValue.find(':'); switch (param.eType & 0xF) { case ModelParameterTypeInt: if (iSep > -1) strRet = QString("%1").arg(RandInt((long)StringToNumber(strValue.left(iSep)), (long)StringToNumber(strValue.mid(iSep+1)))); else if (!listRandom.empty()) strRet = listRandom[iRandom]; break; case ModelParameterTypeFloat: if (iSep > -1) strRet = QString("%1").arg(RandDouble(StringToNumber(strValue.left(iSep)), StringToNumber(strValue.mid(iSep+1)))); else if (!listRandom.empty()) strRet = listRandom[iRandom]; break; case ModelParameterTypeAddress: strRet = GetRandomAddress(strParam); break; case ModelParameterTypeAddresses: // TODO: generate random address list if (!listRandom.empty()) strRet = listRandom[iRandom]; break; case ModelParameterTypeCoords: if (iSep > -1) { Coords ptMin, ptMax; ptMin.FromString(strValue.left(iSep)); ptMax.FromString(strValue.mid(iSep+1)); strRet = Coords(RandInt(ptMin.m_iLong, ptMax.m_iLong), RandInt(ptMin.m_iLat, ptMax.m_iLat)).ToString(); } else if (!listRandom.empty()) strRet = listRandom[iRandom]; else strRet = GetRandomPosition(strParam); break; default: if (!listRandom.empty()) strRet = listRandom[iRandom]; break; } return strRet; }
void SamplerUtil::LHCSamples(DOUBLE* samples, UINT32 n, UINT32 dim) { DOUBLE delta = 1.f / n; for (UINT32 i = 0; i < n; ++i) { for (UINT32 j = 0; j < dim; ++j) { samples[dim*i+j] = (i+RandDouble()) * delta; } } for (UINT32 i = 0; i < dim; ++i) { for (UINT32 j = 0; j < n; ++j) { UINT32 k = RandUint() % n; DOUBLE temp = samples[dim*j + i]; samples[dim*j + i] = samples[dim*k+i]; samples[dim*k+i] = temp; } } }
FieldTrial::FieldTrial(const std::string& name, const Probability total_probability, const std::string& default_group_name, const int year, const int month, const int day_of_month) : name_(name), divisor_(total_probability), default_group_name_(default_group_name), random_(static_cast<Probability>(divisor_*RandDouble())), accumulated_group_probability_(0), next_group_number_(kDefaultGroupNumber+1), group_(kNotFinalized), enable_field_trial_(true) { DCHECK_GT(total_probability, 0); DCHECK(!name_.empty()); DCHECK(!default_group_name_.empty()); FieldTrialList::Register(this); DCHECK_GT(year, 1970); DCHECK_GT(month, 0); DCHECK_LT(month, 13); DCHECK_GT(day_of_month, 0); DCHECK_LT(day_of_month, 32); Time::Exploded exploded; exploded.year = year; exploded.month = month; exploded.day_of_week = 0; // Should be unused. exploded.day_of_month = day_of_month; exploded.hour = 0; exploded.minute = 0; exploded.second = 0; exploded.millisecond = 0; Time expiration_time = Time::FromLocalExploded(exploded); if(GetBuildTime() > expiration_time) { Disable(); } }
int cMathUtil::SampleDiscreteProb(const Eigen::VectorXd& probs) { assert(std::abs(probs.sum() - 1) < 0.00001); double rand = RandDouble(); int rand_idx = gInvalidIdx; int num_probs = static_cast<int>(probs.size()); for (int i = 0; i < num_probs; ++i) { double curr_prob = probs[i]; rand -= curr_prob; if (rand <= 0) { rand_idx = i; break; } } return rand_idx; }
QString QAutoGenDialog::GetRandomAddress(const QString & strParam) { QString strAddress; Address sAddress; std::map<QString, std::vector<unsigned int> >::iterator iterRecords = m_mapRandomRecords.find(strParam); std::map<QString, Rect>::iterator iterMapSelection = m_mapMapSelections.find(strParam); unsigned int i, iMaxRetries = 3, iRecord, iShapePoint; float fProgress; MapRecord * pRecord; if (iterRecords == m_mapRandomRecords.end()) { iterRecords = m_mapRandomRecords.find(OTHERADDRESSES); iterMapSelection = m_mapMapSelections.find(OTHERADDRESSES); if (iterRecords == m_mapRandomRecords.end()) return strAddress; } // choose a random location in this region if (iterRecords->second.empty()) return strAddress; for (i = 0; i < iMaxRetries; i++) { iRecord = RandUInt(0, iterRecords->second.size()); pRecord = g_pMapDB->GetRecord(iterRecords->second[iRecord]); if (pRecord->nShapePoints > 1) { iShapePoint = RandUInt(0, pRecord->nShapePoints - 1); fProgress = (float)RandDouble(0., 1.); if (g_pMapDB->AddressFromRecord(&sAddress, iterRecords->second[iRecord], iShapePoint, fProgress)) { strAddress = AddressToString(&sAddress); if (StringToAddress(strAddress, &sAddress) && sAddress.iRecord != (unsigned)-1 && iterMapSelection->second.intersectRect(pRecord->rBounds)) break; } } } return strAddress; }
double cMathUtil::RandDouble() { return RandDouble(0, 1); }
void SamplerUtil::RandomSamples(DOUBLE* samples, UINT32 n) { for (UINT32 i = 0; i < n; ++i) { *(samples++) = RandDouble(); } }
void Cannon::Update(CGameEngine *game, Runner *player) { switch(state) { case SO_NEUTRAL: if (pos.x - player->GetPos().x < detectionRange) { if (!shot) { state = SO_ALERT; soundRev.Play(-1); } } break; case SO_ALERT: if (pos.x - player->GetPos().x < attackRange) { state = SO_SHOOT; shot = true; soundRev.Stop(); soundFire.Play(); } break; case SO_SHOOT: if (anim_beam.GetCurrentFrame() == shotOffset) //if the beam is out weapActive = true; if (weapActive && weapElapsed < weapDuration) { int ptop = player->GetPos().y; int pbot = ptop + player->GetBox().y; int wtop = pos.y + weapLevelMin; int wbot = pos.y + weapLevelMax; if (!(pbot < wtop || ptop > wbot)) //if the bullet is on same level as player player->Stumble(); ++weapElapsed; } else weapActive = false; break; case SO_DEAD: shooterAlpha -= 30; pos.x += 1; if (shooterAlpha < 0) { if (dieLoop <= 2) { shooterAlpha = 230; ++dieLoop; if (RandInt(0, 6) == 2) explosions.push_back(new Explosion(pos + Vector2D(RandDouble(20, (double)sprite->w+40), RandDouble(-10, sprite->w)), 1.0)); } else { shooterAlpha = 0; state = SO_DELETE; } } SDL_SetAlpha(sprite, SDL_SRCALPHA, shooterAlpha); return; } for (unsigned int i = 0; i < explosions.size(); ++i) { if (explosions[i]->Done) { explosions[i]->Cleanup(); delete explosions[i]; explosions.erase(explosions.begin() + i); break; } } }
void SimpleCommModel::AddMessageToRebroadcastQueue(const SafetyPacket & msg) { if (!m_bRebroadcast) return; // check to see if this a message that should be rebroadcast RebroadcastMessage * pRBXMsg = new RebroadcastMessage; pRBXMsg->msg = msg; pRBXMsg->tIntervalLow = msg.m_tRX; pRBXMsg->tIntervalHigh = pRBXMsg->tIntervalLow + m_tRebroadcastInterval; g_pSimulator->m_EventQueue.AddEvent(SimEvent(pRBXMsg->tIntervalLow + (m_bJitter ? MakeTime(RandDouble(0., ToDouble(m_tRebroadcastInterval))) : m_tRebroadcastInterval), EVENT_PRIORITY_LOWEST, m_strModelName, m_strModelName, EVENT_CARCOMMMODEL_REBROADCAST, pRBXMsg, DestroyRebroadcastMessage)); }
int main(int argc, char* argv[]) { double sum_delta = 0.0, sum_ref = 0.0, L1norm = 0.0; unsigned int seed = 123; int verbose = 0; if (argc > 2) { printf("usage: Black-Scholes <verbose> verbose = 1 for validtating result, the default is 0. \n"); exit(1); } if (argc == 1) verbose = 0; else if (argc == 2) verbose = atoi(argv[1]); kmp_set_defaults("KMP_AFFINITY=compact,granularity=fine"); #ifdef _OPENMP int ThreadNum = omp_get_max_threads(); omp_set_num_threads(ThreadNum); #else int ThreadNum = 1; #endif int OptPerThread = OPT_N / ThreadNum; int mem_size = sizeof(double) * OptPerThread; setlocale(LC_ALL,""); printf("Black-Scholes Formula Double Precision.\n"); printf("Compiler Version = %d\n", __INTEL_COMPILER/100); printf("Release Update = %d\n", __INTEL_COMPILER_UPDATE); printf("Build Time = %s %s\n", __DATE__, __TIME__); printf("Input Dataset = %d\n", OPT_N); printf("Repetitions = %d\n", NUM_ITERATIONS); printf("Chunk Size = %d\n", CHUNKSIZE); printf("Worker Threads = %d\n\n", ThreadNum); if (verbose) printf("Allocate and initialize memory on %d boundary,\n", SIMDALIGN); #pragma omp parallel reduction(+ : sum_delta) reduction(+ : sum_ref) { #ifdef _OPENMP int threadID = omp_get_thread_num(); #else int threadID = 0; #endif double *CallResult = (double *)_mm_malloc(mem_size, SIMDALIGN); double *PutResult = (double *)_mm_malloc(mem_size, SIMDALIGN); double *StockPrice = (double *)_mm_malloc(mem_size, SIMDALIGN); double *OptionStrike = (double *)_mm_malloc(mem_size, SIMDALIGN); double *OptionYears = (double *)_mm_malloc(mem_size, SIMDALIGN); seed += threadID; for(int i = OptPerThread-1; i > -1 ; i--) { CallResult[i] = 0.0; PutResult[i] = -1.0; StockPrice[i] = RandDouble(5.0, 30.0, &seed); OptionStrike[i] = RandDouble(1.0, 100.0, &seed); OptionYears[i] = RandDouble(0.25, 10.0, &seed); } #pragma omp barrier if (threadID == 0) { start_cyc = _rdtsc(); } for(int i = 0; i < NUM_ITERATIONS; i++) for (int chunkBase = 0; chunkBase < OptPerThread; chunkBase += CHUNKSIZE) { #pragma simd vectorlength(CHUNKSIZE) #pragma simd #pragma vector aligned for(int opt = chunkBase; opt < (chunkBase+CHUNKSIZE); opt++) { double CNDD1, CNDD2; double T = OptionYears[opt]; double X = OptionStrike[opt]; double XexpRT = X*exp2(RLOG2E * T); double S = StockPrice[opt]; double sqrtT = sqrt(T); double d1 = log2(S / X) / (VLOG2E * sqrtT) + RVV * sqrtT; CNDF_C (&CNDD1, &d1 ); double d2 = d1 - VOLATILITY * sqrtT; CNDF_C (&CNDD2, &d2 ); double CallVal = S * CNDD1 - XexpRT * CNDD2; double PutVal = CallVal + XexpRT - S; CallResult[opt] = CallVal ; PutResult[opt] = PutVal ; } } #pragma omp barrier if (threadID == 0) { end_cyc = _rdtsc(); } if (verbose) { double delta = 0.0, ref = 0.0, L1norm = 0.0; int max_index = 0; for(int i = 0; i < OptPerThread; i++) { double callReference, putReference; BlackScholesReference( callReference, putReference, StockPrice[i], //Stock price OptionStrike[i], //Option strike OptionYears[i], //Option years RISKFREE, //Riskless rate VOLATILITY //Volatility rate ); ref = callReference; delta = fabs(callReference - CallResult[i]); sum_delta += delta; sum_ref += fabs(ref); } } _mm_free(CallResult); _mm_free(PutResult); _mm_free(StockPrice); _mm_free(OptionStrike); _mm_free(OptionYears); } //parallel section const unsigned long long cyc = end_cyc - start_cyc; double sec = cyc/(FREQ*1e9); printf("=============================================\n"); printf("Total Cycles = %lld\n", cyc); printf("Cycles/OptionPair at thread 0 = %5.2f\n", cyc/(1.0f*NUM_ITERATIONS*OptPerThread)); printf("Time Elapsed = %5.2f\n", sec); printf("Options/sec = %5.2f\n", (2.0f*NUM_ITERATIONS*OPT_N)/(1e9*sec)); printf("=============================================\n"); if (verbose) { L1norm = sum_delta / sum_ref; printf("L1 norm: %E\n", L1norm); printf((L1norm < 9e-5) ? "TEST PASSED\n" : "TEST FAILED\n"); } }