int main(void) { double a1 = 0.0, b1 = 1.0; double a2 = 1.0, b2 = 3.0; double eps = 0.000001; double d1 = dichotomy(f1, eps, a1, b1); double i1 = iteration(f1_it, eps, a1, b1); double n1 = newton(f1, f1_pr, eps, a1, b1); double d2 = dichotomy(f2, eps, a2, b2); double i2 = iteration(f2_it, eps, a2, b2); double n2 = newton(f2, f2_pr, eps, a2, b2); printf("Точность: %.6f\n", eps); printf("+-----------+----------+---------------+-----------------------+-----------+----------+---------+\n"); printf("| Уравнение | Отрезок | Базовый метод | Прибл. значение корня | Дихотомии | Итераций | Ньютона |\n"); printf("+-----------+----------+---------------+-----------------------+-----------+----------+---------+\n"); printf("| 1 | [0, 1] | Ньютона | 0.8814 |%.9f|%.8f|%.7f|\n", d1, i1, n1); printf("+-----------+----------+---------------+-----------------------+-----------+----------+---------+\n"); printf("| 2 | [1, 3] | Дихотомии | 1.3749 |%.9f| - |%.7f|\n", d2, n2); printf("+-----------+----------+---------------+-----------------------+-----------+----------+---------+\n"); return 0; }
template <class F> void IterativeSolverBase<F>::profilingRun (std::ostream& out, std::ostream& log, Core::ProfilingDataPtr prof) { this->epsB = 1; this->prev_err = 1; this->count = 10; this->counter = 0; { Core::ProfileHandle _p1 (prof, "itsolv1"); iteration (count - 1, log, true, prof); } const int nr = 5; const int mid = nr / 2; boost::tuple<uint64_t, int> res[nr]; { Core::ProfileHandle _p1 (prof, "itsolv2"); Core::TimeSpan now = Core::getCurrentTime (); for (int i = 0; i < nr; i++) { iteration (count + i, log, true, prof); res[i] = boost::make_tuple ((Core::getCurrentTime () - now).getMicroseconds (), i); now = Core::getCurrentTime (); } } std::sort (res, res + nr); for (int i = 0; i < nr; i++) out << "[" << res[i].get<1> () << "]" << Core::TimeSpan (res[i].get<0> ()).toString () << " "; uint64_t diff = std::max (res[mid].get<0> () - res[0].get<0> (), res[nr - 1].get<0> () - res[mid].get<0> ()); out << std::endl; out << std::endl; out << Core::TimeSpan (res[mid].get<0> ()).toString () << " +- " << Core::TimeSpan (diff).toString () << std::endl; }
int main() { double /* **U, **Unew,err=0.0,*/ sta = 1.0/8.0, stb=1.0/128.0; int sa = 9, sb = 129, i/*,j*/; FILE *outs; init(&U,sa,sa); init(&Unew,sa,sa); init(&Ub,sb,sb); init_cond(&U, sa, sa, sta,sta); memcpy(&Unew,&U,sizeof(Unew)); for(i = 0; i<1000 /*&& (err>0.001 || err == 0.0)*/; i++) { //err = 0.0; iteration(&U,&Unew, sa,sa, sta,sta); memcpy(&U,&Unew,sizeof(Unew)); } outs = fopen("../output/out1.dat", "w"); output_line(U, sa,sa, sta,sta, outs); fclose(outs); //init_cond(&Ub, sb, sb, stb,stb); interpol(&Ub, sb, sb, stb, stb, &U, sa-1, sa-1, sta, sta); init_cond(&Ub, sb, sb, stb, stb); outs = fopen("../output/out2.dat", "w"); output_line(Ub, sb,sb, stb,stb, outs); fclose(outs); freeArr(&Unew, sa); //output_line(U, sa,sa, sta,sta); //output_line(Ub, sb,sb, stb,stb); //freeArr(&U, sa); init(&Unew,sb,sb); init_cond(&Unew, sb, sb, stb, stb); memcpy(&Unew,&Ub,sizeof(Ub)); //err = 0.0; for(i = 0; i<1000 /*&& (err>0.0005 || err == 0.0)*/ ; i++) { iteration(&Ub,&Unew, sb,sb, stb,stb); memcpy(&Ub,&Unew,sizeof(Unew)); } outs = fopen("../output/out3.dat", "w"); output_line(Ub, sb,sb, stb,stb, outs); fclose(outs); outs = fopen("../output/out3_mstk.dat", "w"); opt_mstk_line(Ub, sb,sb, stb,stb, outs); fclose(outs); //output_line(U, size,size, step,step); //printf("%f %f %f\n", step*5, step*5, err); return 0; }
void TMIP::process() { auto volumes = inport_.getData(); if (volumes->empty()) { return; } auto firstVol = volumes->at(0); if (inport_.isChanged()) { const DataFormatBase* format = firstVol->getDataFormat(); volume0_ = std::make_shared<Volume>(firstVol->getDimensions(), format); volume0_->setModelMatrix(firstVol->getModelMatrix()); volume0_->setWorldMatrix(firstVol->getWorldMatrix()); // pass on metadata volume0_->copyMetaDataFrom(*firstVol); volume0_->dataMap_ = firstVol->dataMap_; volume1_ = std::shared_ptr<Volume>(volume0_->clone()); } int iterations = static_cast<int>(std::ceil(volumes->size() / static_cast<float>(maxSamplers_))); LogInfo(iterations); std::shared_ptr<Volume> readVol = volume0_; std::shared_ptr<Volume> writeVol = volume1_; int offset = 0; for (int i = 0; i < iterations; i++) { bool firstIT = i == 0; bool lastIT = i != 0 && iterations; auto startVolIT = volumes->begin() + offset + 1; if (firstIT) { auto endVolIT = volumes->begin() + offset + maxSamplers_; iteration(shader_, volumes->at(0), writeVol, startVolIT, endVolIT); } else if (!lastIT) { auto endVolIT = volumes->begin() + offset + maxSamplers_; iteration(shader_, readVol, writeVol, startVolIT, endVolIT); } else { iteration(shaderLast_, readVol, writeVol, startVolIT, volumes->end()); } std::swap(readVol, writeVol); offset += maxSamplers_; } outport_.setData(readVol); }
int aff_n(int nb, int base) { int iter; int final; iter = iteration(nb); final = final_nb(nb);
int main(void) { int n, option, result; int *arr; printf("Enter the number n: "); scanf("%d", &n); arr = malloc(sizeof(int) * n); printf("Enter the option m (1: Iteration, 2: Recursion): "); scanf("%d", &option); if (option == 1) result = iteration(arr, n); if (option == 2) result = recursion(arr, n); printf("Result: %d\n", result); free(arr); return 0; }
int main(){ int i,newdata; if (Graphics) GUI(); init(); while (!done){ if (Graphics){ Events(newdata); GetGraphics(); DrawGraphs(); } else {done=1;Pause=0;} if (!Pause||sstep){ sstep=0; newdata=1; for (i=0;i<Repeat;i++){ iterations++; circleBC(); iteration(); iterationColloid(); TotMomentum(); analysis(iterations); } } else sleep(1); } return 0; }
inline virtual std::string run(const Dataset& train, const Dataset& test) { srand(time(NULL)); initialize_pop(train, test); std::pair<unsigned int, double> best_at_train; for (unsigned int i = 0; i < num_iter; ++i) { std::cout << "--- ITERATION " << i + 1 << " ---" << std::endl; iteration(train, test); best_at_train = cur_pop->best(train); std::vector<Statistics> fitness_train = cur_pop->evaluate(train); std::cout << "RMSE (train): " << fitness_train[best_at_train.first].rmse << std::endl; std::cout << "MSE (train): " << fitness_train[best_at_train.first].mse << std::endl; std::cout << "MAE (train): " << fitness_train[best_at_train.first].mae << std::endl; std::cout << "Total error (train): " << fitness_train[best_at_train.first].total_error << std::endl; std::vector<Statistics> fitness_test = cur_pop->evaluate(test, false); std::cout << "RMSE (test): " << fitness_test[best_at_train.first].rmse << std::endl; std::cout << "MSE (test): " << fitness_test[best_at_train.first].mse << std::endl; std::cout << "MAE (test): " << fitness_test[best_at_train.first].mae << std::endl; std::cout << "Total error (test): " << fitness_test[best_at_train.first].total_error << std::endl; std::cout << "Size: " << (*cur_pop)[best_at_train.first].size() << std::endl; } return graph->print_expression((*cur_pop)[best_at_train.first].get_index()); }
int main() { FILE* image = fopen("image.bmp", "ab+"); setup(image); int i,j,a; complex z; for( j = 0; j < SIZE*2; j++) { for( i = 0; i < SIZE*2; i++) { z.re = (double)(2*(i-SIZE)) / (double)(SIZE); z.im = (double)(2*(j-SIZE)) / (double)(SIZE); a = ITER - iteration(z); if ( i%PRINT == 0 && j%PRINT == 0) printf("%f\t%f\t%d\n",z.re,z.im,a); color(a,image); } } readbitmap(image, 200); fclose(image); return 0; }
ant_miner::ant_miner(int num, base_type base,struct method_coefs K ): layer_num(num),ph_min(K.ph_min),ph_max(K.ph_max),eva_coef(K.evap_c), alpha(K.alpha),beta(K.beta), ants_number(K.ants_number),covarage(K.covarage) { cout<<eva_coef<<endl; start = new simpleNode(new test_empty("start"),1,1); finish = new simpleNode (new test_empty("finish"),1,1); vector <list<simpleNode*> > nodes (layer_num); pre_node_type::iterator it; for (int i=0;i<layer_num;++i) { for (it = base[i].begin();it!=base[i].end();++it ) { cout<<(*it).first->toString()<<" "<<(*it).second.second<<" "<<(*it).second.first<<endl; nodes[i].push_back(new simpleNode((*it).first,(*it).second.second,(*it).second.first)); } } make_connections(nodes,finish); count_probability(); cout<<"done!!"<<endl; iteration(); }
void dsme_main_loop_run(void (*iteration)(void)) { if (state == NOT_STARTED) { if (!(the_loop = g_main_loop_new(0, FALSE)) || !set_up_signal_pipe()) { // TODO: crash and burn exit(EXIT_FAILURE); } GMainContext* ctx = g_main_loop_get_context(the_loop); state = RUNNING; while (state == RUNNING) { if (iteration) { iteration(); } if (state == RUNNING) { (void)g_main_context_iteration(ctx, TRUE); } } g_main_loop_unref(the_loop); the_loop = 0; } }
static double compute_time_ms(int num_iter) { assert(num_iter > 0); struct timeval start, end; memset(&start, 0, sizeof(struct timeval)); memset(&end, 0, sizeof(struct timeval)); /* record time */ if (gettimeofday(&start, NULL)) return _NAN; int i; for (i = 0; i < num_iter; i++) iteration(); /* record time */ if (gettimeofday(&end, NULL)) return _NAN; /* convert struct timeval into doubles */ double start_time = start.tv_sec * MS_PER_SEC + start.tv_usec * MS_PER_USEC; double end_time = end.tv_sec * MS_PER_SEC + end.tv_usec * MS_PER_USEC; return end_time - start_time; }
/** In order to do so, first a reasonable dt for stability is calculated and F,G,RHS are evaluated. Afterwards, the Poisson pressure equation is solved and the velocitys are updated. \param[in] printInfo boolean if additional informations on the fields and rediduum of p are printed \param[in] verbose boolean if debbuging information should be printed (standard: false) */ void Compute::TimeStep(bool printInfo, bool verbose=false) { // TODO: test // compute dt if (verbose) std::cout << "Computing the timestep width..." << std::flush; // only for debugging issues real_t dt = compute_dt(); if (verbose) std::cout << "Done.\n" << std::flush; // only for debugging issues // compute F, G MomentumEqu(dt); update_boundary_values(); //update boundary values // compute rhs RHS(dt); // solve Poisson equation real_t residual(_epslimit + 1.0); index_t iteration(0); //while (iteration <= _param->IterMax() && residual > _epslimit){ while (true){ // one solver cycle is done here residual = _solver->Cycle(_p, _rhs); iteration++; if (iteration > _param->IterMax()){ //if (printInfo) { std::cout << "Warning: Solver did not converge! Residual: " << residual << "\n"; //} break; } else if (residual < _epslimit){ //if (printInfo) { std::cout << "Solver converged after " << iteration << " timesteps. Residual: " << residual << "\n"; //} break; } } // compute new velocitys u, v NewVelocities(dt); update_boundary_values(); //update total time _t += dt; // print information if (printInfo){ std::cout << "============================================================\n"; // total simulated time std::cout << "Total simulated time: t = " << _t << "\n"; // timestep std::cout << "Last timestep: dt = " << dt << "\n"; // magnitudes of the fields std::cout << "max(F) = " << _F->AbsMax() << ", max(G) = " << _G->AbsMax() << ", max(rhs) = " << _rhs->AbsMax() << "\n"; std::cout << "max(u) = " << _u->AbsMax() << ", max(v) = " << _v->AbsMax() << ", max(p) = " << _p->AbsMax() << "\n"; //std::cout << "Average value of rhs: " << _rhs->average_value() << "\n"; std::cout << "============================================================\n"; } }
int EventLoop::run() { impl->quit = false; impl->exit_code = 0; while (! impl->quit) iteration(); return impl->exit_code; }
void idle(void) { fps.update(120.0); if (systemRunning) { iteration(); } glutPostRedisplay(); }
void loop() { if(done) emscripten_cancel_main_loop(); else iteration(); }
void *tester_thread(void *pthread) { int thread = (int)(long)pthread; int count = 0; while (1) { iteration(thread, &count); } return NULL; }
int seriesDiverges(int depth, ComplexNumber *z, ComplexNumber *c) { for (int i = 0; i < depth; i++) { iteration(z, c); if (pow((*z).r, 2) + pow((*z).i, 2) > 4) { return i; } } return depth; //Recurrence depth beyond scope. }
void StepperMotor::step(float angles) { float steps = abs(stepsPerRevolution * angles / 360.0); for (float i = 0; i < steps; i++) { iteration(angles >= 0.0); } for (int i = 0; i < 4; i++) { digitalWrite(coils[i], LOW); } }
/** * Obtiene el autovalor dominante en modulo de una matriz. * * @param A matriz para buscar autoespacios * @param x vector inicial del algoritmo * @param norm norma vectorial para actualizar los valores * @param condition condicion para verificar la convergencia del metodo */ EigenPair powerIteration(const Matrix &A, std::vector<double> eigenVector, const Norm &norm, unsigned int iterations) { if (A.columns() != A.rows()) { throw new std::invalid_argument("La matriz no es cuadrada en el método de la potencia"); } if (iterations <= 0) { throw new std::invalid_argument("La cantidad de iteraciones para el método de la potencia debe ser mayor a 0"); } Timer timer("Power Iteration Timer"); Counter iteration("Power Iteration Iteration Counter"); double length = norm(eigenVector); // Normalizamos el autovector for (int j = 0; j < A.rows(); ++j) { eigenVector[j] /= length; } // Verificamos convergencia while (iteration < iterations) { // Elevamos a potencia std::vector<double> temp(eigenVector); // realizamos la copia para luego calcular un delta. eigenVector = A * eigenVector; // Normalizamos el vector length = norm(eigenVector); for (int j = 0; j < A.rows(); ++j) { eigenVector[j] /= length; } // Actualizamos el contador ++iteration; // Verificamos si estamos convergiendo. for (int j=0; j < A.rows(); j++) temp[j] -= eigenVector[j]; if (norm(temp) < POWER_ITERATION_DELTA) break; } double eigenValue = 0.0; for (int i = 0; i < A.rows(); ++i) { for (int j = 0; j < A.rows(); ++j) { eigenValue += eigenVector[i] * eigenVector[j] * A(i, j); } } eigenValue /= norm(eigenVector); return std::pair<double, std::vector<double>>(eigenValue, eigenVector); }
void Lattice::equilibrate(const ZZ N) { const std::clock_t t0 = std::clock(); for (ZZ i = 0; i < N; i++) iteration(); const std::clock_t t1 = std::clock(); std::cout << "Equilibrate: " << 1000 * (t1 - t0) / CLOCKS_PER_SEC << "ms" << std::endl; }
void InfiniteThread::run(){ try { while(true){ InfiniteThread::InterruptException::InterruptionPoint(); iteration(); } } catch(InfiniteThread::InterruptException const & ){ exception(); } }
bool operator () (ScTemplateSearchResult & result) { result.clear(); result.mReplacements = mTemplate.mReplacements; mResultAddrs.resize(calculateOneResultSize()); mReplRefs.resize(mResultAddrs.size(), 0); iteration(0, result); return result.getSize() > 0; }
void slae::gaussSeidel( myVector & oX, int iMaxIter, int & oIterCount, double iEps ) { int k; double res = 1; for( k = 0; k < iMaxIter && res > iEps; ++k ) { iteration(); res = residual(); } oX = m_AprX; oIterCount = k; }
int iteration(long a, long b, int n) { if(a == 1) { flaga = 1; } if(b == 1) { flagb = 1; } if(a == 1 && b == 1) { flagab = 1; return 1; } if(n > 100) return 0; while(a % n != 0 && b % n != 0 && n <= 100) ++n; if(n > 100) return 0; if(a % n == 0) { if(iteration(a / n, b, n + 1)) return 1; } if(b % n == 0) { if(iteration(a, b / n, n + 1)) return 1; } if(iteration(a, b, n + 1)) return 1; return 0; }
/** * @brief Delay for the specified number of milliseconds. */ void busy_delay_ms(int ms) { /* error checking */ assert(NUM_ITERATIONS_PER_MS > 0); int m; for (m = 0; m < ms; m++) { int i; for (i = 0; i < NUM_ITERATIONS_PER_MS; i++) iteration(); } }
bool Triangle::intersects(const Ray& ray, float* distance /*= nullptr*/, Vec3* point /*= nullptr*/) { float a,b,c,d,e,f,g,h,i,j,k,l; Vec3 dir = ray.getDirection(); a = coords[0].x - coords[1].x; b = coords[0].y - coords[1].y; c = coords[0].z - coords[1].z; d = coords[0].x - coords[2].x; e = coords[0].y - coords[2].y; f = coords[0].z - coords[2].z; g = dir.x; h = dir.y; i = dir.z; j = coords[0].x - ray.getOrigin().x; k = coords[0].y - ray.getOrigin().y; l = coords[0].z - ray.getOrigin().z; float t, beta, gama, m; m = a*(e*i - h*f) + b*(g*f - d*i) + c*(d*h-e*g); beta = ( j*(e*i-h*f) + k*(g*f-d*i) + l*(d*h-e*g) ) / m; gama = ( i*(a*k-j*b) + h*(j*c-a*l) + g*(b*l-k*c) ) / m; t = 0- (f*(a*k-j*b) + e*(j*c-a*l) + d*(b*l-k*c)) / m; if (distance) { *distance = t; } Vec3 iteration(t*dir.x, t*dir.y, t*dir.z); if (point) { *point = Vec3(ray.getOrigin().x + iteration.x, ray.getOrigin().y + iteration.y, ray.getOrigin().z + iteration.z); } if (gama <= 0 || gama >= 1) { return false; } if (beta <= 0 || beta >= 1 - gama) { return false; } if (ray.getDirection().dot(normal) < 0) { return false; } return true; }
int main(int argc, const char* argv[]) { // parse command line arguments const util::Args::Table option_table[] = { { "m_size", "m_size", 'm', true, "Width of input matrix A", "elements" }, { "w_size", "w_size", 'w', true, "Height of input matrix A and width of input matrix B", "elements" }, { "n_size", "n_size", 'n', true, "Height of input matrix B", "elements" }, { "iterations", "iterations", 'i', true, "Number of iterations", "iterations" }, util::Args::Table::Terminator }; util::Args args(option_table); int lastarg = args.parse(argc, argv); if (lastarg < argc) { std::cerr << "cali-throughput-thread: unknown option: " << argv[lastarg] << '\n' << " Available options: "; args.print_available_options(std::cerr); return -1; } size_t m_size = std::stoul(args.get("m_size", "512")); size_t w_size = std::stoul(args.get("w_size", "512")); size_t n_size = std::stoul(args.get("n_size", "512")); size_t num_iterations = std::stoul(args.get("iterations", "4")); cali::Annotation phase_annotation("phase", CALI_ATTR_SCOPE_PROCESS); phase_annotation.begin("benchmark"); cali::Loop loop("loop"); for(size_t i=0; i<num_iterations; i++) { cali::Loop::Iteration iteration(loop.iteration((int)i)); do_work(m_size, w_size, n_size); } phase_annotation.end(); }
/** * @brief Delay for the specified number of microseconds. */ void busy_delay_us(int us) { /* error checking */ assert(NUM_ITERATIONS_PER_MS > 0); int num_iterations_per_us = NUM_ITERATIONS_PER_MS / 1000; int m; for (m = 0; m < us; m++) { int i; for (i = 0; i < num_iterations_per_us; i++) iteration(); } }
void iteration(size_t orderIndex, ScTemplateSearchResult & result) { size_t const constrIndex = mTemplate.mSearchCachedOrder[orderIndex]; check_expr(constrIndex < mTemplate.mConstructions.size()); size_t const finishIdx = mTemplate.mConstructions.size() - 1; size_t resultIdx = constrIndex * 3; /// TODO: prevent recursive search and make test for that case ScTemplateConstr3 const & constr = mTemplate.mConstructions[constrIndex]; ScTemplateItemValue const * values = constr.getValues(); ScIterator3Ptr const it3 = createIterator(constr); while (it3->next()) { /// check if search in structure if (mScStruct.isValid()) { if (!checkInStruct(it3->value(0)) || !checkInStruct(it3->value(1)) || !checkInStruct(it3->value(2))) { continue; } } // do not make cycle for optimization issues (remove comparsion expresion) mResultAddrs[resultIdx] = it3->value(0); mResultAddrs[resultIdx + 1] = it3->value(1); mResultAddrs[resultIdx + 2] = it3->value(2); refReplacement(values[0], it3->value(0)); refReplacement(values[1], it3->value(1)); refReplacement(values[2], it3->value(2)); if (orderIndex == finishIdx) { result.mResults.push_back(mResultAddrs); } else { iteration(orderIndex + 1, result); } unrefReplacement(values[0]); unrefReplacement(values[1]); unrefReplacement(values[2]); } }