int RandomColor::generate( ColorList colors, Luminosity luminosity ) { // Each color will have probability = color.hRange.size() / totalRangeSize, // so calculate totalRangeSize double totalRangeSize = 0; for (Color color : colors) { totalRangeSize += colorMap[color].hRange.size(); } // Generate a number within [0; 1) and select a color according with the // cumulative distribution function f(i) = f(i - 1) + colorProbability(i) std::uniform_real_distribution<double> probability(0, 1); double p = probability(randomEngine); double f = 0; for (Color color : colors) { const double colorProbability = colorMap[color].hRange.size() / totalRangeSize; f += colorProbability; if (f >= p) { return generate(color, luminosity); } } // This place can be reached due to rounding (if p ~ 1 and f < p even // for the last color). Then return the last color. Color lastColor = *(colors.end() - 1); return generate(lastColor, luminosity); }
void Ft_feature_model::update(const arma::colvec& x){ std::cout<< arma::norm(x,2) << std::endl; probability(air) = Decision_functions::bound_mv_gaussian_step_function(x,zero,0.5,3.0,1.0); probability(up) = Decision_functions::step_function(x(0),1.5); //Decision_functions::step_function(-x(2),1.5); probability(down) = Decision_functions::step_function(-x(0),1.5); probability(left) = Decision_functions::step_function(x(1),1.5); probability(right) = Decision_functions::step_function(-x(1),1.5); /* if( arma::norm(x - zero,2) < 3){ probability(0) = 1; }else{ probability(0) = 0; }*/ //for(std::size_t i = 1; i < gmms.size();i++){ // probability(i) = gmms[i].gmm.Probability(x); // probability(i) = likelihood(i);// Decision_functions::gaussian_step_function<float>(likelihood(i),desc_mu,desc_beta); // } }
/** * calculates the average number for the distribution; * note that this average is larger than the expectation value, * since curves are limited to the left by x-value 1 */ double GaussianDistribution::getAverage() { double sum1=0; double sum2=0; for (unsigned i=x_limit_left;i<=x_limit_right;i++) { sum1+=i*probability(i); sum2+=probability(i); } return sum1/sum2; }
DocClass classifyDocument(Document doc){ float p1 = getPdc(LESS_THAN_FIVE)*(1/3)/probability(doc); float p2 = getPdc(GREATHER_THAN_FIVE)*(1/3)/probability(doc); float p3 = getPdc(MIXED_VALUES)*(1/3)/probability(doc); DocClass result; if(p1 > std::max<float>(p2, p3)) result = LESS_THAN_FIVE; else if(p2 > std::max<float>(p1, p3)) result = GREATHER_THAN_FIVE; else result = MIXED_VALUES; return result; }
double probability(int color,int total,int remain){ if(remain>color || remain>total || remain<0) return 0.0; if((total+remain)%2==1) return 0.0; if(total==0 || total==1) return 1.0; if(answerMemory[total][remain]==UNDEF) answerMemory[total][remain]=probability(color,total-1,remain+1)*(remain+1.0)/color+ probability(color,total-1,remain-1)*(1.0-(remain-1.0)/color); #ifdef DEBUG printf("# probability(%d,%d,%d) = %f\n",color,total,remain,answerMemory[total][remain]); #endif return answerMemory[total][remain]; }
int main(){ float list[MAX_PROB]; memset(list, 0, sizeof(float) * MAX_PROB); FILE *fp = fopen("introduction_to_probability_input.txt", "r"); check(fp != NULL, "Problem opening input file"); int i = 0; while(!feof(fp)){ if(fscanf(fp, "%f", &list[i])) { i++; } } fclose(fp); int length = i; for (i = 0; i < length-1; i++) { printf("%0.6f ", probability(list[i])); } printf("\n"); return 0; error: return 1; }
void probability(int number, int* probabilities) { for (int i = 1; i <= g_maxValue; i++) { probability(number, number, i, probabilities); } }
void printProbability(int number) { if (number < 1) { return ; } int maxSum = number * g_maxValue; int* probabilities = new int[maxSum - number + 1]; for (int i = number; i <= maxSum; ++i) { probabilities[i - number] = 0; } probability(number, probabilities); int total = pow((double)g_maxValue, number); for (int i = number; i <= maxSum; ++i) { double ratio = (double)probabilities[i - number] / total; printf("%d: %e\n", i, ratio); } delete[] probabilities; }
Rate CreditDefaultSwap::impliedHazardRate( Real targetNPV, const Handle<YieldTermStructure>& discountCurve, const DayCounter& dayCounter, Real recoveryRate, Real accuracy) const { boost::shared_ptr<SimpleQuote> flatRate(new SimpleQuote(0.0)); Handle<DefaultProbabilityTermStructure> probability( boost::shared_ptr<DefaultProbabilityTermStructure>(new FlatHazardRate(0, WeekendsOnly(), Handle<Quote>(flatRate), dayCounter))); MidPointCdsEngine engine(probability, recoveryRate, discountCurve); setupArguments(engine.getArguments()); const CreditDefaultSwap::results* results = dynamic_cast<const CreditDefaultSwap::results*>( engine.getResults()); ObjectiveFunction f(targetNPV, *flatRate, engine, results); Rate guess = 0.001; Rate step = guess*0.1; return Brent().solve(f, accuracy, guess, step); }
int main() { int number; printf("input num of dices:"); scanf("%d",&number); probability(number); return 0; }
main(){ setlocale(LC_ALL, "Russian"); int n, m; float p=0.45, q=0.55; printf("Введите количество детей: n, m\n"); scanf("%d%d", &n, &m); probability(n, m, p, q); getch(); return 0; }
DataType BernoulliDistribution<DataType>::Sample() const { DataType sample = arma::randu<DataType> (probability.n_rows, probability.n_cols); for (size_t i = 0; i < sample.n_elem; i++) sample(i) = sample(i) < probability(i); return sample; }
GaussianDistribution::GaussianDistribution(unsigned _x_limit_left,double _mu, double _sigma) : mu(_mu), sigma(_sigma), x_limit_left(_x_limit_left), r(Randomnizer::getInstance()), RANGE(0) { if (mu<x_limit_left) { exit(4); // this is not allows for this curve type } double sum=0; unsigned num=x_limit_left; // sum<=0.5 makes sure that we do not break too early while (sum<=0.5 || probability(num)>OFFSET_VALUE) { sum+=probability(num++); bucket.push_back(Functions::doubleToUnsigned(sum*ACCURACY)); } sum+=probability(num); bucket.push_back(Functions::doubleToUnsigned(sum*ACCURACY)); RANGE=bucket[bucket.size()-1]; // this is the right bucket limit x_limit_right=num; }
void probability(int original, int current, int sum, int* probabilities) { if (current == 1) { probabilities[sum - original]++; } else { for (int i = 1; i <= g_maxValue; i++) { probability(original, current - 1, i + sum, probabilities); } } }
int main() { int m,n,t,p; cin>> m >> n >> t >> p; if( 0 < m && m <= 1000 && \ 0 < n && n <= m && \ 0 < t && t <= 100 && \ 0 < p && p <= m ) probability(m,n,t,p); return 0; }
int main(){ int color,total,remain; while(true){ scanf("%d",&color); if(color==0) return 0; scanf("%d%d",&total,&remain); if(total>1000) total=1000+total%2; for(int i=0;i<=total;i++) for(int j=0;j<=total;j++) answerMemory[i][j]=UNDEF; printf("%.3f\n",probability(color,total,remain)); } }
void crf::tagger::tag(sequence& seq) { auto trellis = scorer_.viterbi(seq); auto lbls = util::range(label_id{0}, label_id(static_cast<uint32_t>(num_labels_ - 1))); auto last_lbl = functional::argmax( lbls.begin(), lbls.end(), [&](label_id lbl) { return trellis.probability(seq.size() - 1, lbl); }); seq[seq.size() - 1].label(*last_lbl); for (uint64_t t = seq.size() - 1; t > 0; t--) seq[t - 1].label(trellis.previous_tag(t, seq[t].label())); }
//-------------------------------------------------------------------------- vector<Real> LossDist::probabilityOfNEvents(vector<Real>& p) { //-------------------------------------------------------------------------- Size n = p.size(); vector<Real> probability(n+1, 0.0); vector<Real> prev; probability[0] = 1.0; for (Size j = 0; j < n; j++) { prev = probability; probability[0] = prev[0] * (1.0 - p[j]); for (Size i = 1; i <= j; i++) probability[i] = prev[i-1] * p[j] + prev[i] * (1.0 - p[j]); probability[j+1] = prev[j] * p[j]; } return probability; }
/* * search for (approximation of) smallest value v such that probability(v,sigma,mu) >= t */ static double search(double const t, double const sigma, double const mu) { double low = mu - 10*sigma, high = mu + 10*sigma; while ( high - low > 1e-6 ) { double const mid = (high+low)/2.0; double const v = probability(mid,sigma,mu); if ( v < t ) low = mid; else high = mid; } return low; }
probability_t operator() (sigma_t sigma) { state_t state = m_state; probability_t probability(1); for(ObservationIteratorT it(m_observation_begin); it != m_observation_end; ++it) { edge_t /*backward_edge, edge = switch_setting(sigma, state),*/ observation = *it; //backward_edge = state.e == GRAPH_0 ? edge : GRAPH_0; probability *= observation == state.e ? (1 - p) : p / 2; state = m_graph.previous(state, sigma); } return probability; }
QVector<float> AntAlgorithm::calculateProbability(QList<int> path, int node) { QVector<float> probability(attractivenessM.count(), 0); float denominator = 0.; for (int j = 0; j < attractivenessM.count(); ++j) if ((weightM.at(node).at(j) != 0.) && (!path.contains(j))) denominator += pow(attractivenessM.at(node).at(j), alpha) + pow(1 / weightM.at(node).at(j), beta); for (int j = 0; j < attractivenessM.count(); ++j) if ((weightM.at(node).at(j) != 0) && (!path.contains(j)) && (denominator != 0)) probability[j] = (pow(attractivenessM.at(node).at(j), alpha) + pow(1 / weightM.at(node).at(j), beta)) / denominator; else probability[j] = 0.; emit strToLog(tr("Агент в узле %1").arg(node).append(tr(". Вероятности перехода:"))); QList< QVector<float> > list; list.append(probability); showM(list); return probability; }
Rate CreditDefaultSwap::conventionalSpread( Real conventionalRecovery, const Handle<YieldTermStructure>& discountCurve, const DayCounter& dayCounter) const { Rate flatHazardRate = impliedHazardRate(0.0, discountCurve, dayCounter, conventionalRecovery); Handle<DefaultProbabilityTermStructure> probability( boost::shared_ptr<DefaultProbabilityTermStructure>( new FlatHazardRate(0, WeekendsOnly(), flatHazardRate, dayCounter))); MidPointCdsEngine engine(probability, conventionalRecovery, discountCurve, true); setupArguments(engine.getArguments()); engine.calculate(); const CreditDefaultSwap::results* results = dynamic_cast<const CreditDefaultSwap::results*>( engine.getResults()); return results->fairSpread; }
void File::simulatedAnnealing(vector<Process> processes_list) { srand(time(NULL)); parallelTask(processes_list); if (time_is_over == true) { cout << "Time is over before first Parallel Task ordering\n"; cout << "No file saved\n"; return; } if (processes_list.size() <= 2) { return; } averageCalculating(processes_list); //this->saveToFile(alternative_solution, "PRL"); cout << "this->averageReadyTime = " << this->averageReadyTime << endl; cout << "this->averageProcsAmount = " << this->averageProcsAmount << endl; vector<Process> actual_solution = alternative_solution; lastTaskTime = alternative_last_task_time; vector<Process> old_good_solution = actual_solution; old_last_task_time = lastTaskTime; int temperature = TEMPERATURE; int min_temperature = MIN_TEMPERATURE; unsigned int counter_worse_solution = 0; unsigned int counter_better_solution = 0; unsigned int max_counter_better_solution = MAX_COUNTER_BETTER_SOLUTION; unsigned int max_counter_worse_solution = MAX_COUNTER_WORSE_SOLUTION; int minutes_amount = MINUTES_AMOUNT; int i = 0; while (temperature > min_temperature) { //cout << "temperature " << temperature << endl; if ((clock() - start2) / CLOCKS_PER_SEC > minutes_amount * 60) { cout << "Time is over\n"; actual_solution = old_good_solution; lastTaskTime = old_last_task_time; this->saveToFile(actual_solution,"SA"); return; } if (counter_worse_solution >= max_counter_worse_solution) { cout << "Counter_worse_solution is max\n"; counter_worse_solution = 0; actual_solution = old_good_solution; lastTaskTime = old_last_task_time; } // FIND ALTERNATIVE SOLUTION this->findAlternativeSolution(actual_solution); if (time_is_over) { cout << "Time is over\n"; actual_solution = old_good_solution; lastTaskTime = old_last_task_time; this->saveToFile(actual_solution,"SA"); return; } //this->saveToFile(alternative_solution, "ALTER"); if (alternative_last_task_time < lastTaskTime) { //cout << "Processing better scheduling\n"; actual_solution.clear(); if (old_last_task_time > alternative_last_task_time) { cout << "*********************Found new better scheduling************************** \n"; old_good_solution.clear(); old_good_solution = alternative_solution; old_last_task_time = alternative_last_task_time; } actual_solution = alternative_solution; lastTaskTime = alternative_last_task_time; counter_better_solution++; counter_worse_solution = 0; if (counter_better_solution == max_counter_better_solution) { temperature = (int)temperature_reducing(temperature); } } else if ((rand() % 100 + 0) < (probability(actual_solution.back().f_t, temperature))*100) { //cout << "get worse solution\n"; actual_solution.clear(); actual_solution = alternative_solution; lastTaskTime = alternative_last_task_time; counter_worse_solution++; counter_better_solution = 0; temperature = (int)temperature_reducing(temperature); } else { //cout <<"I've done nothing\n"; temperature = (int)temperature_reducing(temperature); } } cout << "Actual temperature is lower than boundary\n" << temperature << endl; actual_solution = old_good_solution; lastTaskTime = old_last_task_time; this->saveToFile(actual_solution,"SA"); }
void main() { int i,j,k; int X[16][4]= {{0,0,0,0},{0,0,0,1},{0,0,1,0},{0,0,1,1},{0,1,0,0},{0,1,0,1},{0,1,1,0},{0,1,1,1}, {1,0,0,0},{1,0,0,1},{1,0,1,0},{1,0,1,1},{1,1,0,0},{1,1,0,1},{1,1,1,0},{1,1,1,1}}; int temp[1][4],temp1[4]; // calculating X star for(i=0;i<16;i++) { for(j=0;j<4;j++) { array[a++]=delta_X[i][j]; } xor(array,X,i); a=0; } /*printf("\n\n\t\t----X star table-----\n");//printing X star table for(i=0;i<16;i++) { for(j=0;j<16;j++) { for(k=0;k<4;k++) { printf("%d ",X_star[i][j][k]); } printf("\n"); } printf("\n\n"); }*/ // Calculating Y table for(i=0;i<16;i++) { for(j=0;j<4;j++) { temp[0][j]=delta_X[i][j]; } sbox_f(temp,1); //function call to sbox } /*printf("\t\t----Y table---\n"); // printing Y table for(j=0;j<16;j++) { for(k=0;k<4;k++) { printf("%d ",Y[j][k]); } printf("\n"); }*/ //Calculating Y star table for(i=0;i<16;i++) { for(j=0;j<16;j++) { for(k=0;k<4;k++) { temp[0][k]=X_star[i][j][k]; } sbox_f(temp,0); //function call to sbox } col1++; row1=0; } /*printf("\n\n\t\t----Y star table-----\n");//printing Y star table for(i=0;i<16;i++) { for(j=0;j<16;j++) { for(k=0;k<4;k++) { printf("%d ",Y_star[i][j][k]); } printf("\n"); } printf("\n\n"); } */ //Calculating Y dash for(i=0;i<16;i++) { for(j=0;j<16;j++) { for(k=0;k<4;k++) { Y_dash[i][j][k]=Y[j][k]^Y_star[i][j][k]; } } } /*printf("\n\n\t\t----Y dash table-----\n"); //printing Y dash table for(i=0;i<16;i++) { for(j=0;j<16;j++) { for(k=0;k<4;k++) { printf("%d ",Y_dash[i][j][k]); } printf("\n"); } printf("\n\n"); }*/ ddt(); // function call ddt printf("\n\n\t\t------- DDT Table -------\n\n"); // printing DDT table for(i=0;i<16;i++) { for(j=0;j<16;j++) { printf("%d ",table[i][j]); } printf("\n\n"); } probability(); printf("\n\n\t\t------- Probability Table -------\n\n"); for(i=0;i<16;i++) { for(j=0;j<16;j++) { printf("%f ",probab[i][j]); } printf("\n\n"); } }
__host__ __device__ probability ProbabilisticVoxel::updateOccupancy(const probability occupancy) { m_occupancy = probability(MIN(MAX(int32_t(m_occupancy + occupancy), int32_t(MIN_PROBABILITY)), int32_t(MAX_PROBABILITY))); return m_occupancy; }
bool randomBool() { return probability(50) ? true : false; }
int randomSign() { return probability(50) ? -1 : 1; }
capd::interval formal::evaluate_pha(int min_depth, int max_depth) { CLOG_IF(global_config.verbose, INFO, "algorithm") << "Obtaining partition of domain of continuous random parameters"; // getting partition of domain of continuous random variables std::vector<box> init_rv_partition = measure::get_rv_partition(); // getting domain of continuous random variables box rv_domain = measure::bounds::get_rv_domain(); // here we start with entire domain instead of partition if (!global_config.partition_prob) { init_rv_partition.clear(); init_rv_partition.push_back(rv_domain); } // getting partition of domain of discrete random variables std::vector<box> dd_partition = measure::get_dd_partition(); if (dd_partition.empty()) { dd_partition.push_back(box()); } capd::interval probability(0, 1); // checking if there are any continuous random variables CLOG_IF(global_config.verbose, INFO, "algorithm") << "P = " << probability; // generating all paths of lengths [min_depth, max_depth] std::vector<std::vector<pdrh::mode *>> paths = pdrh::get_all_paths(min_depth, max_depth); //resulting probability capd::interval res_prob(0.0); // evaluating boxes //#pragma omp parallel for for (box dd : dd_partition) { if (pdrh::rv_map.size() > 0) probability = capd::interval(0, 2 - measure::p_measure(rv_domain, global_config.precision_prob).leftBound()); vector<box> rv_partition = init_rv_partition; std::vector<box> rv_stack; while (capd::intervals::width(probability) > global_config.precision_prob) { // sorting boxes by probability value if (global_config.sort_rv_flag) { CLOG_IF(global_config.verbose, INFO, "algorithm") << "Sorting the partition of domain of continuous random parameters"; sort(rv_partition.begin(), rv_partition.end(), measure::compare_boxes_by_p_measure); } //for(box rv : rv_partition) #pragma omp parallel for for (size_t i = 0; i < rv_partition.size(); i++) { box rv = rv_partition.at(i); // calculating probability measure of the box // initially p_box = [1.0, 1.0] CLOG_IF(global_config.verbose, INFO, "algorithm") << "===================="; capd::interval p_box(1); if (!dd.empty()) { p_box *= measure::p_dd_measure(dd); CLOG_IF(global_config.verbose, INFO, "algorithm") << "dd_box: " << dd; } if (!rv.empty()) { p_box *= measure::p_measure(rv, global_config.precision_prob); CLOG_IF(global_config.verbose, INFO, "algorithm") << "rv_box: " << rv; } CLOG_IF(global_config.verbose, INFO, "algorithm") << "p_box: " << p_box; // evaluating boxes std::vector<box> boxes{dd, rv}; // undetermined answers counter int undet_counter = 0; // unsat counter int unsat_counter = 0; // sat flag bool sat_flag = false; // evaluating all paths for all dd and rv //cout << "Before evaluate loop " << omp_get_thread_num() << endl; for (std::vector<pdrh::mode *> path : paths) { std::string solver_opt; std::stringstream p_stream; for (pdrh::mode *m : path) { p_stream << m->id << " "; } // removing trailing whitespace CLOG_IF(global_config.verbose, INFO, "algorithm") << "Path: " << p_stream.str().substr(0, p_stream.str().find_last_of( " ")); std::stringstream s; // changing solver precision #pragma omp critical { solver_opt = global_config.solver_opt; s << solver_opt << " --precision " << measure::volume(rv).leftBound() * global_config.solver_precision_ratio; global_config.solver_opt = s.str(); } int res = decision_procedure::evaluate(path, boxes, global_config.solver_bin, s.str()); // setting old precision #pragma omp critical { global_config.solver_opt = solver_opt; switch (res) { case decision_procedure::SAT: if (p_box.leftBound() > 0) { probability = capd::interval(probability.leftBound() + p_box.leftBound(), probability.rightBound()); } CLOG_IF(global_config.verbose, INFO, "algorithm") << "SAT"; CLOG_IF(global_config.verbose, INFO, "algorithm") << "P = " << probability; /* if(capd::intervals::width(probability) <= global_config.precision_prob) { return probability; } */ sat_flag = true; break; case decision_procedure::UNSAT: CLOG_IF(global_config.verbose, INFO, "algorithm") << "UNSAT"; unsat_counter++; break; case decision_procedure::UNDET: CLOG_IF(global_config.verbose, INFO, "algorithm") << "UNDET"; undet_counter++; break; case decision_procedure::ERROR: CLOG(ERROR, "algorithm") << "Error occurred while calling the solver"; exit(EXIT_FAILURE); default: break; } } // breaking out of the loop if a sat path was found if (sat_flag) break; } #pragma omp critical { // checking if there are no sat answers if (!sat_flag) { // if the box is undetermined on either path if (undet_counter > 0) { CLOG_IF(global_config.verbose, INFO, "algorithm") << "Bisect " << rv; std::vector<box> rv_bisect = box_factory::bisect(rv); rv_stack.insert(rv_stack.end(), rv_bisect.begin(), rv_bisect.end()); } // if the box is unsat for all paths else if (unsat_counter == paths.size()) { if (p_box.rightBound() > 0) { probability = capd::interval(probability.leftBound(), probability.rightBound() - p_box.leftBound()); } CLOG_IF(global_config.verbose, INFO, "algorithm") << "P = " << probability; } } }; } // copying the bisected boxes from the stack to partition rv_partition = rv_stack; rv_stack.clear(); // breaking out of the loop if there are no continuous random variables if (pdrh::rv_map.size() == 0) { rv_partition.push_back(box()); break; } } if (!dd.empty()) { capd::interval dd_measure = measure::p_dd_measure(dd); res_prob += probability * dd_measure; CLOG_IF(global_config.verbose, INFO, "algorithm") << "P(" << dd << ") = " << probability * dd_measure; } else { res_prob = probability; } } return res_prob; }
virtual double QoS(int Q) { return QoS_from_prob(probability(Q)); };
double random_prob() { return probability(engine); };