void ctrl::attach_tow() { aircraft::info_ptr towair; visit_objects<aircraft::info_ptr>(collection_, [this, &towair](aircraft::info_ptr air)->bool { geo_point_3 tow_pos = geo_base_3(air->pos())(cg::rotation_3(cpr(air->orien().course, 0, 0)) * (point_3(0, 5., 0) + point_3(air->tow_point_transform().translation()))); if (cg::distance2d(tow_pos, this->pos()) < 25) { towair = air; return false; } return true; }); if (towair) send_cmd(msg::attach_tow_msg_t(object_info_ptr(towair)->object_id())); }
void Controller::handleEvent(Handle* handle) { switch (State) { case WRITE: { cout << "Enter CPR-number: "; string input; cin >> input; try { CprNumber cpr(input); handle->send("7;" + input); reactor->removeHandler(4); reactor->registerHandler(this, 3); State = RECIVE; } catch (exception e) { cout << e.what() << endl; } } break; case RECIVE: { PatientEventHandler handler; handler.handleEvent(handle); reactor->removeHandler(3); reactor->registerHandler(this, 4); State = WRITE; } default: break; } }
int cg(MAT &A,VEC b,VEC &x,int maxIter,double tol){ int n = A.dim(); int k = 0; VEC x_next(n); VEC r_next(n); VEC p_next(n); VEC r(n); VEC p(n); MAT L(n); VEC cpr(n); double alpha,beta; double err; double diff; r = b - A*x; //initial condition p = r; while(k<maxIter){ //conjugate gradient decent alpha = (r*r)/(p*(A*p)); x_next = x + alpha*p; r_next = r - alpha*(A*p); beta = (r_next*r_next)/(r*r); p_next = r_next + beta*p; k++; x = x_next; //assign to the x,r,p of the next iteration r = r_next; p = p_next; err = pow((r*r)/n,0.5); if(err<tol) //see if the error is smaller than the defined tolerance. if so, break out of the loop break; } diff = 0; //the answer from hw4 L = cholesky(A); //in-place Cholesky Decomposition cpr = choSolve(L,b); //solve the linear system by forward and backward substitution //use the same method to compute the error between hw4 and hw5, see if < 10^-7. if not, decrease the tol for(int i=0;i<n;i++){ diff = max(diff,fabs(x[i]-cpr[i])); //use infinity norm to compute the error } printf("error between hw4 and hw6(infinity-norm): %e\n",diff); return k; }
auto_ptr<oadrPayload> CreatePartyRegistration::generatePayload() { oadrCreatePartyRegistrationType cpr(requestID(), m_profileType, m_transportType, m_reportOnly, m_xmlSignature); cpr.schemaVersion("2.0b"); cpr.oadrHttpPullModel(m_httpPullModel); if (m_venName != "") cpr.oadrVenName(m_venName); oadrSignedObject oso; oso.oadrCreatePartyRegistration(cpr); auto_ptr<oadrPayload> payload(new oadrPayload(oso)); return payload; }
void ctrl::fire_fight() { aircraft::info_ptr burning_plane; bool reverse = false; visit_objects<aircraft::info_ptr>(collection_, [this, &burning_plane](aircraft::info_ptr air)->bool { geo_point_3 tow_pos = geo_base_3(air->pos())(cg::rotation_3(cpr(air->orien().course, 0, 0)) * (point_3(0, 5., 0) )); if (cg::distance2d(tow_pos, this->pos()) < 25) { burning_plane = air; return false; } return true; }); if (burning_plane) send_cmd(msg::fight_fire_msg_t(object_info_ptr(burning_plane)->object_id(), 1)); }
Patient PatientDatabase::getPatient(CprNumber cprNumber) { ifstream infile("patients.txt"); string line; while (getline(infile, line)) { string matchString = line.substr(0,11); if (strcmp(cprNumber.getCprNumber().c_str(), matchString.c_str())) continue; vector<string> raw; Tokenize(line, raw, ";"); CprNumber cpr(raw[0]); string name = raw[1]; string address = raw[2]; return Patient(cpr, name, address); } return Patient(CprNumber("000000-0000"), "Not Found", "Not in database"); }
int kadmin(int cmd, int fcn, void *mdep, cred_t *credp) { int error = 0; char *buf; size_t buflen = 0; boolean_t invoke_cb = B_FALSE; /* * We might be called directly by the kernel's fault-handling code, so * we can't assert that the caller is in the global zone. */ /* * Make sure that cmd is one of the valid <sys/uadmin.h> command codes * and that we have appropriate privileges for this action. */ switch (cmd) { case A_FTRACE: case A_SHUTDOWN: case A_REBOOT: case A_REMOUNT: case A_FREEZE: case A_DUMP: case A_SDTTEST: case A_CONFIG: if (secpolicy_sys_config(credp, B_FALSE) != 0) return (EPERM); break; default: return (EINVAL); } /* * Serialize these operations on ualock. If it is held, the * system should shutdown, reboot, or remount shortly, unless there is * an error. We need a cv rather than just a mutex because proper * functioning of A_REBOOT relies on being able to interrupt blocked * userland callers. * * We only clear ua_shutdown_thread after A_REMOUNT or A_CONFIG. * Other commands should never return. */ if (cmd == A_SHUTDOWN || cmd == A_REBOOT || cmd == A_REMOUNT || cmd == A_CONFIG) { mutex_enter(&ualock); while (ua_shutdown_thread != NULL) { if (cv_wait_sig(&uacond, &ualock) == 0) { /* * If we were interrupted, leave, and handle * the signal (or exit, depending on what * happened) */ mutex_exit(&ualock); return (EINTR); } } ua_shutdown_thread = curthread; mutex_exit(&ualock); } switch (cmd) { case A_SHUTDOWN: { proc_t *p = ttoproc(curthread); /* * Release (almost) all of our own resources if we are called * from a user context, however if we are calling kadmin() from * a kernel context then we do not release these resources. */ if (p != &p0) { proc_is_exiting(p); if ((error = exitlwps(0)) != 0) { /* * Another thread in this process also called * exitlwps(). */ mutex_enter(&ualock); ua_shutdown_thread = NULL; cv_signal(&uacond); mutex_exit(&ualock); return (error); } mutex_enter(&p->p_lock); p->p_flag |= SNOWAIT; sigfillset(&p->p_ignore); curthread->t_lwp->lwp_cursig = 0; curthread->t_lwp->lwp_extsig = 0; if (p->p_exec) { vnode_t *exec_vp = p->p_exec; p->p_exec = NULLVP; mutex_exit(&p->p_lock); VN_RELE(exec_vp); } else { mutex_exit(&p->p_lock); } pollcleanup(); closeall(P_FINFO(curproc)); relvm(); } else { /* * Reset t_cred if not set because much of the * filesystem code depends on CRED() being valid. */ if (curthread->t_cred == NULL) curthread->t_cred = kcred; } /* indicate shutdown in progress */ sys_shutdown = 1; /* * Communcate that init shouldn't be restarted. */ zone_shutdown_global(); killall(ALL_ZONES); /* * If we are calling kadmin() from a kernel context then we * do not release these resources. */ if (ttoproc(curthread) != &p0) { VN_RELE(PTOU(curproc)->u_cdir); if (PTOU(curproc)->u_rdir) VN_RELE(PTOU(curproc)->u_rdir); if (PTOU(curproc)->u_cwd) refstr_rele(PTOU(curproc)->u_cwd); PTOU(curproc)->u_cdir = rootdir; PTOU(curproc)->u_rdir = NULL; PTOU(curproc)->u_cwd = NULL; } /* * Allow the reboot/halt/poweroff code a chance to do * anything it needs to whilst we still have filesystems * mounted, like loading any modules necessary for later * performing the actual poweroff. */ if ((mdep != NULL) && (*(char *)mdep == '/')) { buf = i_convert_boot_device_name(mdep, NULL, &buflen); mdpreboot(cmd, fcn, buf); } else mdpreboot(cmd, fcn, mdep); /* * Allow fsflush to finish running and then prevent it * from ever running again so that vfs_unmountall() and * vfs_syncall() can acquire the vfs locks they need. */ sema_p(&fsflush_sema); (void) callb_execute_class(CB_CL_UADMIN_PRE_VFS, NULL); vfs_unmountall(); (void) VFS_MOUNTROOT(rootvfs, ROOT_UNMOUNT); vfs_syncall(); dump_ereports(); dump_messages(); invoke_cb = B_TRUE; /* FALLTHROUGH */ } case A_REBOOT: if ((mdep != NULL) && (*(char *)mdep == '/')) { buf = i_convert_boot_device_name(mdep, NULL, &buflen); mdboot(cmd, fcn, buf, invoke_cb); } else mdboot(cmd, fcn, mdep, invoke_cb); /* no return expected */ break; case A_CONFIG: switch (fcn) { case AD_UPDATE_BOOT_CONFIG: #ifndef __sparc { extern void fastboot_update_config(const char *); fastboot_update_config(mdep); } #endif break; } /* Let other threads enter the shutdown path now */ mutex_enter(&ualock); ua_shutdown_thread = NULL; cv_signal(&uacond); mutex_exit(&ualock); break; case A_REMOUNT: (void) VFS_MOUNTROOT(rootvfs, ROOT_REMOUNT); /* Let other threads enter the shutdown path now */ mutex_enter(&ualock); ua_shutdown_thread = NULL; cv_signal(&uacond); mutex_exit(&ualock); break; case A_FREEZE: { /* * This is the entrypoint for all suspend/resume actions. */ extern int cpr(int, void *); if (modload("misc", "cpr") == -1) return (ENOTSUP); /* Let the CPR module decide what to do with mdep */ error = cpr(fcn, mdep); break; } case A_FTRACE: { switch (fcn) { case AD_FTRACE_START: (void) FTRACE_START(); break; case AD_FTRACE_STOP: (void) FTRACE_STOP(); break; default: error = EINVAL; } break; } case A_DUMP: { if (fcn == AD_NOSYNC) { in_sync = 1; break; } panic_bootfcn = fcn; panic_forced = 1; if ((mdep != NULL) && (*(char *)mdep == '/')) { panic_bootstr = i_convert_boot_device_name(mdep, NULL, &buflen); } else panic_bootstr = mdep; #ifndef __sparc extern void fastboot_update_and_load(int, char *); fastboot_update_and_load(fcn, mdep); #endif panic("forced crash dump initiated at user request"); /*NOTREACHED*/ } case A_SDTTEST: { DTRACE_PROBE7(test, int, 1, int, 2, int, 3, int, 4, int, 5, int, 6, int, 7); break; } default: error = EINVAL; } return (error); }
//------------------------------------------------------------------------------------------------------ // Function: CPlayerReport::writeHTML // Purpose: writes the player's stats out as HTML // Input: html - the html file to which we're writing //------------------------------------------------------------------------------------------------------ void CPlayerReport::writeHTML(CHTMLFile& html) { //if we're writing the stats for a persistent player, just pass execution off to that function! if (reportingPersistedPlayer) { writePersistHTML(html); return; } pPlayer->totalTimeOn(); //this ensures that the logoff time is correct if (iWhichTeam==ALL_TEAMS) pPlayer->merge(); else if (!pPlayer->teams.contains(iWhichTeam)) { return; } int tid=iWhichTeam; if (tid==ALL_TEAMS) html.write("<font class=headline>%s</font><br>\n",pPlayer->name.c_str()); else html.write("<font class=player%s2>%s</font><hr align=left width=60%%>\n",Util::teamcolormap[tid],pPlayer->name.c_str()); if (pPlayer->aliases.size() > 1) { map<string,bool> namePrinted; namePrinted[pPlayer->name.c_str()]=true; html.write("<font class=whitetext>aliases:</font> <font class=awards2>"); CTimeIndexedList<string>::iterator nmiter=pPlayer->aliases.begin(); bool printed1=false; for (nmiter;nmiter!=pPlayer->aliases.end();++nmiter) { if (namePrinted[nmiter->data]!=true) { if (printed1) html.write(", "); html.write(nmiter->data.c_str()); namePrinted[nmiter->data]=true; printed1=true; } } html.write("</font><br>\n"); } html.write("<font class=whitetext>rank:</font> <font class=awards2> %.2lf </font><br>\n",pPlayer->perteam[tid].rank()); html.write("<font class=whitetext>kills/deaths:</font> <font class=awards2>%li/%li </font><br>\n",pPlayer->perteam[tid].kills,pPlayer->perteam[tid].deaths); html.write("<font class=whitetext>time:</font> <font class=awards2> %01li:%02li:%02li </font><br>\n",Util::time_t2hours(pPlayer->perteam[tid].timeOn()),Util::time_t2mins(pPlayer->perteam[tid].timeOn()),Util::time_t2secs(pPlayer->perteam[tid].timeOn())); int numClassesPlayed=pPlayer->perteam[tid].classesplayed.numDifferent(); player_class faveClass=pPlayer->perteam[tid].classesplayed.favourite(); if (numClassesPlayed == 1) { if (faveClass!=PC_UNDEFINED) html.write("<font class=whitetext>class:</font> <font class=awards2> %s </font><br>\n",plrClassNames[faveClass]); } else if (numClassesPlayed > 1) { if (faveClass!=PC_UNDEFINED) html.write("<font class=whitetext>favorite class:</font> <font class=awards2> %s </font><br>\n",plrClassNames[faveClass]); html.write("<font class=whitetext>classes played:</font> <font class=awards2> "); bool printedone=false; for(int pc=PC_SCOUT;pc!=PC_OBSERVER;++pc) { if (pPlayer->perteam[tid].classesplayed.contains((player_class)pc)) { if (printedone) html.write(", "); html.write(plrClassNames[pc]); printedone=true; } } html.write(" </font><br>\n"); } const string weap=pPlayer->perteam[tid].faveWeapon(); const string faveWeap=Util::getFriendlyWeaponName(weap); if (pPlayer->perteam[tid].kills!=0) { char lowerWeapName[50]; Util::str2lowercase(lowerWeapName,faveWeap.c_str()); html.write("<font class=whitetext>favorite weapon:</font> <font class=awards2> %s</font><br>\n",faveWeap.c_str()); html.write("<font class=whitetext>kills with %s:</font> <font class=awards2> %li</font><br>\n",lowerWeapName,pPlayer->perteam[tid].faveWeapKills()); } int numTeamsPlayed=pPlayer->teams.numDifferent(); if (numTeamsPlayed > 1) { if (iWhichTeam==ALL_TEAMS) html.write("<font class=whitetext>Played on</font> <font class=whitetext> "); else html.write("<font class=whitetext>Also played on</font> <font class=whitetext> "); map<int,bool> alreadyPrinted; CTimeIndexedList<int>::iterator tmiter=pPlayer->teams.begin(); bool printed1=false; for (tmiter;tmiter!=pPlayer->teams.end();++tmiter) { int team=tmiter->data; if (team != iWhichTeam && !alreadyPrinted[team]) { if (printed1) html.write(" and "); html.write("<font class=player%s>%s</font>",Util::teamcolormap[team],Util::teamcolormap[team]);// printed1=true; alreadyPrinted[team]=true; } } html.write("</font><br>\n"); } if (numTeamsPlayed > 1 && iWhichTeam != ALL_TEAMS) { html.write("<a class=whitetext href=\"%lu.html\"> <u> Combined stats for this match </u> </a> <br> \n",pPlayer->pid); if (!alreadyWroteCombStats[pPlayer->pid]) { CPlayerReport cpr(pPlayer,ALL_TEAMS); char numbuf[200]; char namebuf[200]; sprintf(numbuf,"%lu.html",pPlayer->pid); sprintf(namebuf,"Combined match statistics for %s",pPlayer->name.c_str()); cpr.makeHTMLPage(numbuf,namebuf); alreadyWroteCombStats[pPlayer->pid]=true; } } if (g_pApp->cmdLineSwitches["persistplayerstats"]=="yes" && !g_pMatchInfo->isLanGame()) html.write("<a class=whitetext href=\"%s/allplayers.html#%lu\"> <u> Combined stats on this server </u> </a> <br> \n",g_pApp->playerHTTPPath.c_str(),pPlayer->WONID,pPlayer->name.c_str()); if (g_pMatchInfo->isLanGame()) return; if (alreadyPersisted[pPlayer->WONID] || reportingPersistedPlayer) return; alreadyPersisted[pPlayer->WONID]=true; if (g_pApp->cmdLineSwitches["persistplayerstats"]=="yes") { CPlrPersist cpp; CPlrPersist onDisk; cpp.generate(*pPlayer); onDisk.read(pPlayer->WONID); cpp.merge(onDisk); cpp.write(); } }
void phys_state::sync_rotors(double dt) { self_.get_rotors()->visit_rotors([this, dt](rotors_group_t const& rg,size_t& id) { auto rnode = rg.node; geo_position rpos; const float ob_min = rg.ang_speed; nodes_management::node_position rotor_node_pos = rnode->position(); const float angular_speed = ob_min * 2 * cg::pif/60.0; // 2000 и 3000 об/мин (30-50 об/с) quaternion des_orien = rotor_node_pos.local().orien * quaternion(cpr(0,0,-cg::rad2grad() * angular_speed * dt)); // const cg::transform_4 rotor_node_trans = cg::transform_4(cg::as_translation(-rotor_node_pos.local().pos), /*rpos.orien*/des_orien.rotation()); point_3 omega_rel = cg::get_rotate_quaternion(rotor_node_pos.local().orien,des_orien).rot_axis().omega() / (dt); // rotor_node_pos.local().orien = /*rpos.orien*/rotor_node_trans.rotation().quaternion(); rotor_node_pos.local().omega = omega_rel; rnode->set_position(rotor_node_pos); const double abs_speed = abs(rg.ang_speed); if(abs_speed>150) { if(rg.dyn_rotor_node) { if(!rg.dyn_rotor_node->get_visibility() || rg.dyn_rotor_node->get_visibility() && !*(rg.dyn_rotor_node->get_visibility())) { rg.dyn_rotor_node->set_visibility(true); rg.dyn_rotor_node->set_position(rg.dyn_rotor_node->position()); } } if(rg.rotor_node) { if(!rg.rotor_node->get_visibility() || rg.rotor_node->get_visibility() && *(rg.rotor_node->get_visibility())) { rg.rotor_node->set_visibility(false); rg.rotor_node->set_position(rg.rotor_node->position()); } } } else { if(rg.dyn_rotor_node) { if(!rg.dyn_rotor_node->get_visibility() || rg.dyn_rotor_node->get_visibility() && *(rg.dyn_rotor_node->get_visibility())) { rg.dyn_rotor_node->set_visibility(false); rg.dyn_rotor_node->set_position(rg.dyn_rotor_node->position()); } } if(rg.rotor_node) { if(!rg.rotor_node->get_visibility() || rg.rotor_node->get_visibility() && !*(rg.rotor_node->get_visibility())) { rg.rotor_node->set_visibility(true); rg.rotor_node->set_position(rg.rotor_node->position()); } } } }); }
void phys_state::sync_wheels(double dt) { geo_position root_pos = self_.get_root_pos(); quaternion root_next_orien = quaternion(cg::rot_axis(root_pos.omega * dt)) * root_pos.orien; geo_base_3 root_next_pos = root_pos.pos(root_pos.dpos * dt); logger::need_to_log(true); geo_position body_pos = phys_aircraft_->get_position(); self_.get_shassis()->visit_chassis([this, &root_next_orien, &root_next_pos, &body_pos, dt](shassis_group_t const& gr, shassis_t & shassis) { auto wnode = shassis.wheel_node; auto chassis_node = shassis.node; if (shassis.phys_wheels.empty()) return; geo_position wpos = this->phys_aircraft_->get_wheel_position(shassis.phys_wheels[0]); quaternion wpos_rel_orien = (!body_pos.orien) * wpos.orien; point_3 wpos_rel_pos = (!body_pos.orien).rotate_vector(body_pos.pos(wpos.pos)); #ifdef OSG_NODE_IMPL nodes_management::node_info_ptr rel_node = wnode; #else nodes_management::node_info_ptr rel_node = wnode->rel_node(); #endif //geo_base_3 global_pos = wnode->get_global_pos(); //quaternion global_orien = wnode->get_global_orien(); transform_4 rel_node_root_tr = rel_node->get_root_transform(); point_3 desired_pos_in_rel = rel_node_root_tr.inverted() * wpos_rel_pos; quaternion desired_orien_in_rel = (!quaternion(rel_node_root_tr.rotation().cpr())) * wpos_rel_orien; desired_orien_in_rel = quaternion(cpr(0, 0, -root_next_orien.get_roll())) * desired_orien_in_rel; //LOG_ODS_MSG( " desired_orien_in_rel.get_course() = " << desired_orien_in_rel.get_course() << // " desired_orien_in_rel.get_pitch() = " << desired_orien_in_rel.get_pitch() << // " desired_orien_in_rel.get_roll() = " << desired_orien_in_rel.get_roll() << "\n" // ); nodes_management::node_position wheel_node_pos = wnode->position(); nodes_management::node_position chassis_node_pos = chassis_node->position(); chassis_node_pos.local().dpos.z = (desired_pos_in_rel.z - wheel_node_pos.local().pos.z) / dt; #if 0 const float angular_speed = 45 * 2 * cg::pif/60.0; desired_orien_in_rel = wheel_node_pos.local().orien * quaternion(cpr(0,-cg::rad2grad() * angular_speed * dt,0)); #endif //quaternion q = cg::get_rotate_quaternion(wheel_node_pos.local().orien, desired_orien_in_rel); point_3 omega_rel = cg::get_rotate_quaternion(wheel_node_pos.local().orien, desired_orien_in_rel).rot_axis().omega() / (dt); wheel_node_pos.local().omega = omega_rel ; wnode->set_position(wheel_node_pos); chassis_node->set_position(chassis_node_pos); }); logger::need_to_log(false); }
Chemistry::Chemistry() { // tracer::scope _("chymia ctor"); const simparam* p = &simparam::instance(); // tracer::instance().range("chem files"); namespace bf = boost::filesystem; enum {CHEM,THERM,TRAN,NFILE}; bf::path files[] = {p->chem, p->chem_therm, p->chem_tran}; for (int i=0; i!=3; ++i) { const bf::path& source = p->initial_path() / files[i]; const bf::path& target = files[i]; // source doesn't exists, just ignore (it could be nonfile input) if ( !bf::exists(source) ) continue; // remove target if already there if ( bf::exists(target) ) // do not remove if the target is the same file // happens when there are no process-rank enumerated dirs (as in ipfd) if( bf::equivalent( source, target ) ) continue; else bf::remove( target ); // now clean slate, copy the file bf::copy_file( source, target ); } mix_t mix( p->chem, p->chem_therm, p->chem_tran ); // tracer::instance().range("flamelet"); flamelet_t fmlet; /*HERE if ( std::ifstream("flamelet_table.in") ) fmlet.set(mix, "flamelet_table.in"); // TODO Check flamelet table species against mix species!" HERE*/ // tracer::instance().range("CP reactor"); reactor_t cpr(mix); cpr.solver(p->chem_solver); cpr.reltol(p->chem_reltol); cpr.abstol(p->chem_abstol); /*HERE if ( p->chem_isatetol > 0 ) cpr.isatetol(p->chem_isatetol); // set reference mixtures (required if ISAT is to be used as solver) // The one that specified in parameters and its equilibrium reactor_t::full_composition& compo = cpr.ref_comp(0); compo.T = p->ref_T; compo.p = p->ref_p; std::fill ( compo.X.begin(), compo.X.end(), real(0) ); BOOST_FOREACH( simparam::name_value_map::const_reference nv, p->ref_species ) compo.X[ mix.index(nv.first) ] = nv.second; mix.normalize(compo.X); reactor_t::full_composition& ceqpo = cpr.ref_comp(1); ceqpo = compo; mix.equil( ceqpo.X, ceqpo.p, ceqpo.T ); HERE */ // pimpl.reset(new impl(mix,fmlet,cpr)); }
void ctrl::set_initial_position( cg::geo_point_3 const &p, double c) { nodes_management::node_control_ptr root(/*get_nodes_manager()*/nodes_manager_->get_node(0)); root->set_position(geo_position(p, quaternion(cpr(c, 0, 0)))); FIXME(А у самолета тут гораздо больше кода) }
int sgs(MAT &A,VEC b,VEC &x,int maxIter,double tol) { int n = A.dim(); VEC S(n); VEC G(n); VEC tmp(n); MAT L(n); VEC cpr(n); //iterative int k=0; double err1; double err2; double errinf; double diff1,diff2,diffinf; while(k<maxIter){ for(int i=0;i<n;i++){ S[i] = 0; } //forward gauss-seidel //compute vector x from x[0] to x[n-1] for(int i=0;i<n;i++){ G[i] = A[i][i]; tmp[i] = x[i]; for(int j=0;j<n;j++){ if(j!=i){ S[i] = S[i] + A[i][j]*x[j]; } } x[i] = (1/G[i])*(b[i]-S[i]); } //backward gauss-seidel //use the reslults of forward gauss-seidel to compute vector x //direction : from x[n-1] to x[0] for(int i=0;i<n;i++){ S[i] = 0; //we also need to initialize the sum vector. } for(int i=n-1;i>=0;i--){ for(int j=n-1;j>=0;j--){ if(j!=i){ S[i] = S[i] + A[i][j]*x[j]; } } x[i] = (1/G[i])*(b[i]-S[i]); } k++; err1 = 0; err2 = 0; errinf = 0; for(int i=0;i<n;i++){ err1 += fabs(x[i] - tmp[i]); err2 += pow(x[i] - tmp[i], 2); errinf = max(errinf,fabs(x[i]-tmp[i])); } err2 = pow(err2,0.5); if(err1<tol){ break; } } diff1 = 0; diff2 = 0; diffinf = 0; //the answer from hw4 L = cholesky(A); //in-place Cholesky Decomposition cpr = choSolve(L,b); //solve the linear system by forward and backward substitution //use the same method to compute the error between hw4 and hw5, see if < 10^-7. if not, decrease the tol for(int i=0;i<n;i++){ diff1 += fabs(x[i] - cpr[i]); diff2 += pow(x[i] - cpr[i], 2); diffinf = max(diffinf,fabs(x[i]-cpr[i])); } diff2 = pow(diff2,0.5); printf("error between hw4 and hw5(1-norm 2-norm infinity-norm): %e %e %e\n",diff1,diff2,diffinf); return k; }
int gaussSeidel(MAT &A,VEC b,VEC &x,int maxIter,double tol) { int n = A.dim(); VEC S(n); VEC G(n); VEC tmp(n); MAT L(n); VEC cpr(n); //iterative int k=0; double err1; double err2; double errinf; double diff1,diff2,diffinf; while(k<maxIter){ for(int i=0;i<n;i++){ S[i] = 0; } for(int i=0;i<n;i++){ G[i] = A[i][i]; tmp[i] = x[i]; for(int j=0;j<n;j++){ if(j!=i){ S[i] = S[i] + A[i][j]*x[j]; } } x[i] = (1/G[i])*(b[i]-S[i]); //both x[i] and S[i] are computed in the same for loop, so some updated values are used in the current iteration } k++; err1 = 0; err2 = 0; errinf = 0; for(int i=0;i<n;i++){ err1 += fabs(x[i] - tmp[i]); err2 += pow(x[i] - tmp[i], 2); errinf = max(errinf,fabs(x[i]-tmp[i])); } err2 = pow(err2,0.5); if(err1<tol){ break; } } diff1 = 0; diff2 = 0; diffinf = 0; //the answer from hw4 L = cholesky(A); //in-place Cholesky Decomposition cpr = choSolve(L,b); //solve the linear system by forward and backward substitution //use the same method to compute the error between hw4 and hw5, see if < 10^-7. if not, decrease the tol for(int i=0;i<n;i++){ diff1 += fabs(x[i] - cpr[i]); diff2 += pow(x[i] - cpr[i], 2); diffinf = max(diffinf,fabs(x[i]-cpr[i])); } diff2 = pow(diff2,0.5); printf("error between hw4 and hw5(1-norm 2-norm infinity-norm): %e %e %e\n",diff1,diff2,diffinf); return k; }
int jacobi(MAT &A,VEC b,VEC &x, int maxIter, double tol){ int n = A.dim(); VEC S(n); //summation vector VEC G(n); //diagonal of A VEC tmp(n); //save the x before iterative method MAT L(n); VEC cpr(n); //the result of hw4 //iterative int k=0; double err1; double err2; double errinf; double diff1,diff2,diffinf; while(k<maxIter){ for(int i=0;i<n;i++){ S[i] = 0; //initialize the sum vector to 0 } for(int i=0;i<n;i++){ G[i] = A[i][i]; //save the previous vector x to tmp(for comparison between iteration k and k+1) tmp[i] = x[i]; for(int j=0;j<n;j++){ if(j!=i){ S[i] = S[i] + A[i][j]*x[j]; //sum the Aij*xj, where i is not equal to j } } } for(int i=0;i<n;i++){ x[i] = (1/G[i])*(b[i]-S[i]); //compute the new solution of x at iteration k } k++; //after each iteration, k=k+1 err1 = 0; //1-norm err2 = 0; //2-norm errinf = 0; //infinity-norm for(int i=0;i<n;i++){ err1 += fabs(x[i] - tmp[i]); //sum of absolute error err2 += pow(x[i] - tmp[i], 2); //sum of square error errinf = max(errinf,fabs(x[i]-tmp[i])); //take the maximum absolute difference as error } //max(a,b) defined on the top err2 = pow(err2,0.5); //find the square root of err2 and get the 2-norm //you can change err1 to err2 or errinf to get different number of iterations k based on which p-norm you preferred if(err1<tol){ break; } } diff1 = 0; diff2 = 0; diffinf = 0; //the answer from hw4 L = cholesky(A); //in-place Cholesky Decomposition cpr = choSolve(L,b); //solve the linear system by forward and backward substitution //use the same method to compute the error between hw4 and hw5, see if < 10^-7. if not, decrease the tol for(int i=0;i<n;i++){ diff1 += fabs(x[i] - cpr[i]); diff2 += pow(x[i] - cpr[i], 2); diffinf = max(diffinf,fabs(x[i]-cpr[i])); } diff2 = pow(diff2,0.5); printf("error between hw4 and hw5(1-norm 2-norm infinity-norm): %e %e %e\n",diff1,diff2,diffinf); return k; }
/* * Fill up the termcap tables. */ int filltables(void) { int i, tret; /* Retrieve the termcap entry. */ if ((tret = otgetent(bp, term_name)) != 1) { (void) fprintf(stderr, "%s: TERM=%s: tgetent failed with return code %d (%s).\n", progname, term_name, tret, (tret == 0) ? "non-existent or invalid entry" : (tret == -1) ? "cannot open $TERMCAP" : "unknown reason"); return (0); } if (verbose) { (void) fprintf(trace, "bp="); (void) cpr(trace, bp); (void) fprintf(trace, ".\n"); } if (uselevel == 0) checktermcap(); /* Retrieve the values that are in terminfo. */ /* booleans */ for (i = 0; boolcodes[i]; i++) { boolval[uselevel][i] = otgetflag(boolcodes[i]); if (verbose > 1) { (void) fprintf(trace, "boolcodes=%s, ", boolcodes[i]); (void) fprintf(trace, "boolnames=%s, ", boolnames[i]); (void) fprintf(trace, "flag=%d.\n", boolval[uselevel][i]); } } /* numbers */ for (i = 0; numcodes[i]; i++) { numval[uselevel][i] = otgetnum(numcodes[i]); if (verbose > 1) { (void) fprintf(trace, "numcodes=%s, ", numcodes[i]); (void) fprintf(trace, "numnames=%s, ", numnames[i]); (void) fprintf(trace, "num=%d.\n", numval[uselevel][i]); } } if (uselevel == 0) nextstring = capbuffer; /* strings */ for (i = 0; strcodes[i]; i++) { strval[uselevel][i] = otgetstr(strcodes[i], &nextstring); if (verbose > 1) { (void) fprintf(trace, "strcodes=%s, ", strcodes [i]); (void) fprintf(trace, "strnames=%s, ", strnames [i]); if (strval[uselevel][i]) { (void) fprintf(trace, "str="); tpr(trace, strval[uselevel][i]); (void) fprintf(trace, ".\n"); } else (void) fprintf(trace, "str=NULL.\n"); } /* remove zero length strings */ if (strval[uselevel][i] && (strval[uselevel][i][0] == '\0')) { (void) fprintf(stderr, "%s: TERM=%s: cap %s (info %s) is NULL: REMOVED\n", progname, term_name, strcodes[i], strnames[i]); strval[uselevel][i] = NULL; } } /* Retrieve the values not found in terminfo anymore. */ /* booleans */ for (i = 0; oboolcodes[i]; i++) { oboolval[uselevel][i] = otgetflag(oboolcodes[i]); if (verbose > 1) { (void) fprintf(trace, "oboolcodes=%s, ", oboolcodes[i]); (void) fprintf(trace, "flag=%d.\n", oboolval[uselevel][i]); } } /* numbers */ for (i = 0; onumcodes[i]; i++) { onumval[uselevel][i] = otgetnum(onumcodes[i]); if (verbose > 1) { (void) fprintf(trace, "onumcodes=%s, ", onumcodes[i]); (void) fprintf(trace, "num=%d.\n", onumval[uselevel][i]); } } /* strings */ for (i = 0; ostrcodes[i]; i++) { ostrval[uselevel][i] = otgetstr(ostrcodes[i], &nextstring); if (verbose > 1) { (void) fprintf(trace, "ostrcodes=%s, ", ostrcodes[i]); if (ostrval[uselevel][i]) { (void) fprintf(trace, "ostr="); tpr(trace, ostrval[uselevel][i]); (void) fprintf(trace, ".\n"); } else (void) fprintf(trace, "ostr=NULL.\n"); } /* remove zero length strings */ if (ostrval[uselevel][i] && (ostrval[uselevel][i][0] == '\0')) { (void) fprintf(stderr, "%s: TERM=%s: cap %s (no terminfo name) is NULL: " "REMOVED\n", progname, term_name, ostrcodes[i]); ostrval[uselevel][i] = NULL; } } return (1); }