当前位置: 首页>>代码示例>>C++>>正文


C++ round函数代码示例

本文整理汇总了C++中round函数的典型用法代码示例。如果您正苦于以下问题:C++ round函数的具体用法?C++ round怎么用?C++ round使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了round函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: rp_set_params


//.........这里部分代码省略.........
        }

        /* If AUTO trigger mode, reset trigger delay */
        if(mode == 0) 
            t_delay = 0;

        if(dec_factor < 0) {
            fprintf(stderr, "Incorrect time range: %d\n", time_range);
            return -1;
        }

        /* Pick time unit and unit factor corresponding to current time range. */
        if((time_range == 0) || (time_range == 1)) {
            time_unit     = 0;
            t_unit_factor = 1e6;
        } else if((time_range == 2) || (time_range == 3)) {
            time_unit     = 1;
            t_unit_factor = 1e3;
        }

        rp_main_params[TIME_UNIT_PARAM].value = time_unit;
        TRACE("PC: time_(R,U) = (%d, %d)\n", time_range, time_unit);

        /* Check if trigger delay in correct range, otherwise correct it
         * Correct trigger delay is:
         *  t_delay >= -t_max
         *  t_delay <= OSC_FPGA_MAX_TRIG_DELAY
         */
        if(t_delay < -t_max) {
            t_delay = -t_max;
        } else if(t_delay > (OSC_FPGA_TRIG_DLY_MASK * smpl_period)) {
            t_delay = OSC_FPGA_TRIG_DLY_MASK * smpl_period;
        } else {
            t_delay = round(t_delay / smpl_period) * smpl_period;
        }
        t_min = t_min + t_delay;
        t_max = t_max + t_delay;
        rp_main_params[TRIG_DLY_PARAM].value = t_delay;

        /* Convert to seconds */
        t_start = t_start / t_unit_factor;
        t_stop  = t_stop  / t_unit_factor;
        TRACE("PC: t_stop = %.9f\n", t_stop);

        /* Select correct time window with this settings:
         * time window is defined from:
         *  ([ 0 - 16k ] * smpl_period) + trig_delay */
        /* round to correct/possible values - convert to nearest index
         * and back 
         */
        t_start_idx = round(t_start / smpl_period);
        t_stop_idx  = round(t_stop / smpl_period);

        t_start = (t_start_idx * smpl_period);
        t_stop  = (t_stop_idx * smpl_period);

        if(t_start < t_min) 
            t_start = t_min;
        if(t_stop > t_max)
            t_stop = t_max;
        if(t_stop <= t_start )
            t_stop = t_max;

        /* Correct the window according to possible decimations - always
         * provide at least the data demanded by the user (ceil() instead
         * of round())
开发者ID:1nfused,项目名称:RemoteAccess,代码行数:67,代码来源:main.c

示例2: search_similar

string search_similar (void * webserver_request)
{
  Webserver_Request * request = (Webserver_Request *) webserver_request;

 
  Database_Volatile database_volatile = Database_Volatile ();
  

  int myIdentifier = filter_string_user_identifier (request);
  
  
  string bible = request->database_config_user()->getBible ();
  if (request->query.count ("b")) {
    bible = request->query ["b"];
  }


  if (request->query.count ("load")) {
    int book = Ipc_Focus::getBook (request);
    int chapter = Ipc_Focus::getChapter (request);
    int verse = Ipc_Focus::getVerse (request);
    // Text of the focused verse in the active Bible.
    // Remove all punctuation from it.
    string versetext = search_logic_get_bible_verse_text (bible, book, chapter, verse);
    vector <string> punctuation = filter_string_explode (Database_Config_Bible::getSentenceStructureEndPunctuation (bible), ' ');
    for (auto & sign : punctuation) {
      versetext = filter_string_str_replace (sign, "", versetext);
    }
    punctuation = filter_string_explode (Database_Config_Bible::getSentenceStructureMiddlePunctuation (bible), ' ');
    for (auto & sign : punctuation) {
      versetext = filter_string_str_replace (sign, "", versetext);
    }
    versetext = filter_string_trim (versetext);
    database_volatile.setValue (myIdentifier, "searchsimilar", versetext);
    return versetext;
  }
  
  
  if (request->query.count ("words")) {
    
    string words = request->query ["words"];
    words = filter_string_trim (words);
    database_volatile.setValue (myIdentifier, "searchsimilar", words);
    vector <string> vwords = filter_string_explode (words, ' ');
    
    // Include items if there are no more search hits than 30% of the total number of verses in the Bible.
    size_t maxcount = round (0.3 * search_logic_get_verse_count (bible));
    
    // Store how often a verse occurs in an array.
    // The keys are the identifiers of the search results.
    // The values are how often the identifiers occur in the entire focused verse.
    map <int, int> identifiers;
    
    for (auto & word : vwords) {
      
      // Find out how often this word occurs in the Bible. Skip if too often.
      vector <Passage> passages = search_logic_search_bible_text (bible, word);
      if (passages.size () > maxcount) continue;
      
      // Store the identifiers and their count.
      for (auto & passage : passages) {
        int id = filter_passage_to_integer (passage);
        if (identifiers.count (id)) identifiers [id]++;
        else identifiers [id] = 1;
      }
      
    }
    
    // Sort on occurrence from high to low.
    // Skip identifiers that only occur once.
    vector <int> ids;
    vector <int> counts;
    for (auto & element : identifiers) {
      int id = element.first;
      int count = element.second;
      if (count <= 1) continue;
      ids.push_back (id);
      counts.push_back (count);
    }
    quick_sort (counts, ids, 0, counts.size());
    reverse (ids.begin(), ids.end());

    // Output the passage identifiers to the browser.
    string output;
    for (auto & id : ids) {
      if (!output.empty ()) output.append ("\n");
      output.append (convert_to_string (id));
    }
    return output;
  }
  
  
  if (request->query.count ("id")) {
    int id = convert_to_int (request->query ["id"]);
    
    // Get the Bible and passage for this identifier.
    Passage passage = filter_integer_to_passage (id);
    string bible = request->database_config_user()->getBible ();
    // string bible = passage.bible;
    int book = passage.book;
//.........这里部分代码省略.........
开发者ID:alerque,项目名称:bibledit,代码行数:101,代码来源:similar.cpp

示例3: PTR_CAST

ossimRefPtr<ossimImageData> ossimTileToIplFilter::getTile(const ossimIrect& tileRect,
        ossim_uint32 resLevel)
{


    cout << "Getting Tile !" << endl;

    // Check input data sources for valid and null tiles
    ossimImageSource *imageSource = PTR_CAST(ossimImageSource, getInput(0));
    ossimRefPtr<ossimImageData> imageSourceData;


    if (imageSource)
        imageSourceData = imageSource->getTile(tileRect, resLevel);

    if (!isSourceEnabled())
        return imageSourceData;


    if (!theTile.valid())
    {
        if(getInput(0))
        {
            theTile = ossimImageDataFactory::instance()->create(this, this);
            theTile->initialize();
        }
    }

    if (!imageSourceData.valid() || !theTile.valid())
        return ossimRefPtr<ossimImageData>();

    theTile->setOrigin(tileRect.ul());
    if (theTile->getImageRectangle() != tileRect)
    {
        theTile->setImageRectangle(tileRect);
        theTile->initialize();
    }


    IplImage *input = cvCreateImage(cvSize(tileRect.width(), tileRect.height()),IPL_DEPTH_8U,3);
    IplImage *output = cvCreateImage(cvSize(tileRect.width(),tileRect.height()),IPL_DEPTH_8U,3);

    cvZero(input);
    cvZero(output);

    // If 16 or 32 bits, downsample to 8 bits
    ossimScalarType inputType = imageSourceData->getScalarType();
    if(inputType == OSSIM_UINT16 || inputType == OSSIM_USHORT11)
        CopyTileToIplImage(static_cast<ossim_uint16>(0), imageSourceData, input, tileRect);
    else
        CopyTileToIplImage(static_cast<ossim_uint8>(0), imageSourceData, input, tileRect);


    cvCopy(input, output);



    int bins = 256;
    int hsize[] = {bins};

    float binVal;
    float sum=0;
    int firstIndexFlag = 1;

    /*// Create histogram of image
    CvHistogram *hist;
    hist = cvCreateHist(1, hsize, CV_HIST_ARRAY, 0, 1);
    cvCalcHist(&input, hist, 0, 0);
    cvNormalizeHist(hist, 100);

    binVal = cvQueryHistValue_1D(hist,1);
    */

    // Determine the actual height and width of each tile
    ossimIrect fullImageRect;
    fullImageRect = imageSource->getBoundingRect(0);

    ossim_int32 tileHeight, tileWidth, imageWidth, imageHeight;
    tileHeight = tileRect.height();
    tileWidth = tileRect.width();

    imageWidth = fullImageRect.width();
    imageHeight = fullImageRect.height();

    ossim_int32 totRows, totCols;
    totRows = (ossim_uint32)round(imageHeight / tileHeight);
    totCols = (ossim_uint32)round(imageWidth / tileWidth);

    ossimIpt upperLeftTile = tileRect.ul();

    if ((upperLeftTile.x + 1) > fullImageRect.ul().x + totCols * tileWidth)
        tileWidth = imageWidth - totCols * tileWidth;

    if ((upperLeftTile.y + 1) > fullImageRect.ul().y + totRows * tileHeight)
        tileHeight = imageHeight - totRows * tileHeight;

    //Begin Ship Detect Algorithim



//.........这里部分代码省略.........
开发者ID:sunleechina,项目名称:icode-mda,代码行数:101,代码来源:ossimTileToIplFilter_1.cpp

示例4: az_draw_particle


//.........这里部分代码省略.........
      }
    } break;
    case AZ_PAR_ICE_BOOM: {
      const double t0 = particle->age / particle->lifetime;
      const double t1 = 1.0 - t0;
      glBegin(GL_TRIANGLE_FAN); {
        with_color_alpha(particle->color, 0);
        glVertex2f(0, 0);
        with_color_alpha(particle->color, t1 * t1 * t1);
        for (int i = 0; i <= 360; i += 6) {
          glVertex2d(particle->param1 * cos(AZ_DEG2RAD(i)),
                     particle->param1 * sin(AZ_DEG2RAD(i)));
        }
      } glEnd();
      glPushMatrix(); {
        const double rx = 0.65 * particle->param1;
        const double ry = sqrt(3.0) * rx / 3.0;
        const double cx = fmin(1, 4 * t0) * rx;
        for (int i = 0; i < 6; ++i) {
          glBegin(GL_TRIANGLE_FAN); {
            with_color_alpha(particle->color, t1);
            glVertex2d(cx, 0);
            with_color_alpha(particle->color, t1 * t1);
            glVertex2d(cx + rx, 0); glVertex2d(cx,  ry);
            glVertex2d(cx - rx, 0); glVertex2d(cx, -ry);
            glVertex2d(cx + rx, 0);
          } glEnd();
          glRotatef(60, 0, 0, 1);
        }
      } glPopMatrix();
    } break;
    case AZ_PAR_LIGHTNING_BOLT:
      if (particle->age >= particle->param2) {
        const int num_steps = az_imax(2, round(particle->param1 / 10.0));
        const double step = particle->param1 / num_steps;
        az_random_seed_t seed = { clock / 5, 194821.0 * particle->angle };
        az_vector_t prev = {0, 0};
        for (int i = 1; i <= num_steps; ++i) {
          const az_vector_t next =
            (i == num_steps ? (az_vector_t){particle->param1, 0} :
             (az_vector_t){3.0 * az_rand_sdouble(&seed) + i * step,
                           10.0 * az_rand_sdouble(&seed)});
          const az_vector_t side =
            az_vwithlen(az_vrot90ccw(az_vsub(next, prev)), 4);
          glBegin(GL_TRIANGLE_STRIP); {
            with_color_alpha(particle->color, 0);
            az_gl_vertex(az_vadd(prev, side));
            az_gl_vertex(az_vadd(next, side));
            glColor4f(1, 1, 1, 0.5);
            az_gl_vertex(prev); az_gl_vertex(next);
            with_color_alpha(particle->color, 0);
            az_gl_vertex(az_vsub(prev, side));
            az_gl_vertex(az_vsub(next, side));
          } glEnd();
          prev = next;
        }
        draw_bolt_glowball(particle->color, particle->param1, clock);
      }
      draw_bolt_glowball(particle->color, 0, clock);
      break;
    case AZ_PAR_OTH_FRAGMENT:
      glRotated(particle->age * AZ_RAD2DEG(particle->param2), 0, 0, 1);
      glBegin(GL_TRIANGLES); {
        const double radius =
          (particle->param1 >= 0.0 ?
           particle->param1 * (1.0 - particle->age / particle->lifetime) :
开发者ID:andrewrk,项目名称:azimuth,代码行数:67,代码来源:particle.c

示例5: gravity_fft_grid2p

void gravity_fft_grid2p(struct particle* p){
	
	// I'm sorry to say I have to keep these traps. Something's wrong if these traps are called.
		
	int x = (int) floor((p->x / boxsize_x + 0.5) * root_nx);
	int y = (int) floor((p->y / boxsize_y + 0.5) * root_ny);
		
	// Formally, pos.x is in the interval [-size/2 , size/2 [. Therefore, x and y should be in [0 , grid_NJ-1]
		
	
	// xp1, xm1... might be out of bound. They are however the relevant coordinates for the interpolation.
	int xp1 = x + 1;
	int xm1 = x - 1;
	int ym1 = y - 1;
	int yp1 = y + 1;

		
	// Target according to boundary conditions.
	// Although xTarget and yTarget are not relevant here, they will be relevant with shear
	// We have to use all these fancy variables since y depends on x because of the shearing path
	// Any nicer solution is welcome
	
	int xTarget = x;
	int xp1Target = xp1;
	int xm1Target = xm1;
	
	int ym1_xm1Target = (ym1 + root_ny) % root_ny;
	int ym1_xTarget   = ym1_xm1Target;
	int ym1_xp1Target = ym1_xm1Target;
		
	int y_xm1Target = y % root_ny;
	int y_xTarget   = y_xm1Target;
	int y_xp1Target = y_xm1Target;
		
	int yp1_xm1Target = yp1 % root_ny;
	int yp1_xTarget   = yp1_xm1Target;
	int yp1_xp1Target = yp1_xm1Target;


	double tx, ty;
	
	// Shearing patch trick
	// This is only an **approximate** mapping
	// one should use an exact interpolation scheme here (Fourier like).
		
	if(xp1Target>=root_nx) {
		xp1Target -= root_nx;							// X periodicity
		y_xp1Target = y_xp1Target + round((shift_shear/boxsize_y) * root_ny);
		y_xp1Target = (y_xp1Target + root_ny) % root_ny;			// Y periodicity
		yp1_xp1Target = yp1_xp1Target + round((shift_shear/boxsize_y) * root_ny);
		yp1_xp1Target = (yp1_xp1Target + root_ny) % root_ny;
		ym1_xp1Target = ym1_xp1Target + round((shift_shear/boxsize_y) * root_ny);
		ym1_xp1Target = (ym1_xp1Target + root_ny) % root_ny;
	}
		
	if(xm1Target<0) {
		xm1Target += root_nx;
		y_xm1Target = y_xm1Target - round((shift_shear/boxsize_y) * root_ny);
		y_xm1Target = (y_xm1Target + root_ny) % root_ny;			// Y periodicity
		yp1_xm1Target = yp1_xm1Target - round((shift_shear/boxsize_y) * root_ny);
		yp1_xm1Target = (yp1_xm1Target + root_ny) % root_ny;
		ym1_xm1Target = ym1_xm1Target - round((shift_shear/boxsize_y) * root_ny);
		ym1_xm1Target = (ym1_xm1Target + root_ny) % root_ny;
	}


	tx = ((double)xm1 +0.5) * boxsize_x / root_nx -0.5*boxsize_x - p->x;
	ty = ((double)ym1 +0.5) * boxsize_y / root_ny -0.5*boxsize_y - p->y;

	p->ax += fx[(root_ny+2) * xm1Target + ym1_xm1Target] * W(-tx/dx)*W(-ty/dy);
	p->ay += fy[(root_ny+2) * xm1Target + ym1_xm1Target] * W(-tx/dx)*W(-ty/dy);

	tx = ((double)x   +0.5) * boxsize_x / root_nx -0.5*boxsize_x - p->x;
	ty = ((double)ym1 +0.5) * boxsize_y / root_ny -0.5*boxsize_y - p->y;
	
	p->ax += fx[(root_ny+2) * xTarget   + ym1_xTarget] * W(-tx/dx)*W(-ty/dy);
	p->ay += fy[(root_ny+2) * xTarget   + ym1_xTarget] * W(-tx/dx)*W(-ty/dy);
	
	tx = ((double)xp1 +0.5) * boxsize_x / root_nx -0.5*boxsize_x - p->x;
	ty = ((double)ym1 +0.5) * boxsize_y / root_ny -0.5*boxsize_y - p->y;
	
	p->ax += fx[(root_ny+2) * xp1Target + ym1_xp1Target] * W(-tx/dx)*W(-ty/dy);
	p->ay += fy[(root_ny+2) * xp1Target + ym1_xp1Target] * W(-tx/dx)*W(-ty/dy);

	tx = ((double)xm1 +0.5) * boxsize_x / root_nx -0.5*boxsize_x - p->x;
	ty = ((double)y   +0.5) * boxsize_y / root_ny -0.5*boxsize_y - p->y;
	
	p->ax += fx[(root_ny+2) * xm1Target + y_xm1Target  ] * W(-tx/dx)*W(-ty/dy);
	p->ay += fy[(root_ny+2) * xm1Target + y_xm1Target  ] * W(-tx/dx)*W(-ty/dy);

	tx = ((double)x   +0.5) * boxsize_x / root_nx -0.5*boxsize_x - p->x;
	ty = ((double)y   +0.5) * boxsize_y / root_ny -0.5*boxsize_y - p->y;

	p->ax += fx[(root_ny+2) * xTarget   + y_xTarget  ] * W(-tx/dx)*W(-ty/dy);
	p->ay += fy[(root_ny+2) * xTarget   + y_xTarget  ] * W(-tx/dx)*W(-ty/dy); 

	tx = ((double)xp1 +0.5) * boxsize_x / root_nx -0.5*boxsize_x - p->x;
	ty = ((double)y   +0.5) * boxsize_y / root_ny -0.5*boxsize_y - p->y;
	
	p->ax += fx[(root_ny+2) * xp1Target + y_xp1Target  ] * W(-tx/dx)*W(-ty/dy);
//.........这里部分代码省略.........
开发者ID:MobileLearningSMKNers,项目名称:rebound,代码行数:101,代码来源:gravity_fft.c

示例6: main


//.........这里部分代码省略.........
     /* write markers */
     write_markers(&dinfo,&cinfo);

   }

   jpeg_finish_compress(&cinfo);
   outsize=outbuffersize;

   if (target_size != 0 && !retry) {
     /* perform (binary) search to try to reach target file size... */

     long osize = outsize/1024;
     long isize = insize/1024;
     long tsize = target_size;

     if (tsize < 0) { 
       tsize=((-target_size)*insize/100)/1024; 
       if (tsize < 1) tsize=1;
     }

     if (osize == tsize || searchdone || searchcount >= 8 || tsize > isize) {
       if (searchdone < 42 && lastsize > 0) {
	 if (abs(osize-tsize) > abs(lastsize-tsize)) {
	   if (verbose_mode) fprintf(LOG_FH,"(revert to %d)",oldquality);
	   searchdone=42;
	   quality=oldquality;
	   goto binary_search_loop;
	 }
       }
       if (verbose_mode) fprintf(LOG_FH," ");
       
     } else {
       int newquality;
       int dif = round(abs(oldquality-quality)/2.0);
       if (osize > tsize) {
	 newquality=quality-dif;
	 if (dif < 1) { newquality--; searchdone=1; }
	 if (newquality < 0) { newquality=0; searchdone=2; }
       } else {
	 newquality=quality+dif;
	 if (dif < 1) { newquality++; searchdone=3; }
	 if (newquality > 100) { newquality=100; searchdone=4; }
       }
       oldquality=quality;
       quality=newquality;

       if (verbose_mode) fprintf(LOG_FH,"(try %d)",quality);

       lastsize=osize;
       searchcount++;
       goto binary_search_loop;
     }
   } 

   if (buf) FREE_LINE_BUF(buf,dinfo.output_height);
   jpeg_finish_decompress(&dinfo);


   if (quality>=0 && outsize>=insize && !retry && !stdin_mode) {
     if (verbose_mode) fprintf(LOG_FH,"(retry w/lossless) ");
     retry=1;
     goto retry_point; 
   }

   retry=0;
   ratio=(insize-outsize)*100.0/insize;
开发者ID:martinmoehler,项目名称:jpegoptim,代码行数:67,代码来源:jpegoptim.c

示例7: laserCallback

void laserCallback(const sensor_msgs::LaserScan& msg)
{
  double angle;
  unsigned int i;

  // Store robot position in map grid coordinates
  unsigned int robot_col = 0; // CHANGE ME
  unsigned int robot_row = 0; // CHANGE ME

  angle = msg.angle_min;
  i=0;
  // Go through all the LRF measurements
  while(angle <= msg.angle_max)
  {
    if( msg.ranges[i] > msg.range_min )
    {
      ///////////////////////////////////////////////////////////////////////
      // Update map with each sensor reading.
      //
      // Important variables (already defined and available):
      //  - (robot_pose.x, robot_pose.y, robot_pose.theta) ==> Robot pose in the
      // world frame;
      //  - msg.ranges[i] ==> LRF i reading (distance from the LRF to the beacon
      // detected by the beacon at the i-th angle);
      //
      ///////////////////////////////////////////////////////////////////////
      // INSERT YOUR CODE BELOW THIS POINT
      ///////////////////////////////////////////////////////////////////////

      // Create obstacle position in sensor coordinates from msg.ranges[i]


      // Transform obstacle position to robot coordinates using local2world


      // Get obtained value in world coordinates using again local2world


      // Get obtained value in the map grid (columm and row) - must be unsigned
      // int.


      // Update map using the line iterator for free space

      // Update map using the line iterator for occupied space, if applicable

      ///////////////////////////////////////////////////////////////////////
      // INSERT YOUR CODE ABOVE THIS POINT
      ///////////////////////////////////////////////////////////////////////
    }

    // Proceed to next laser measure
    angle += msg.angle_increment;
    i++;
  }

  // Show map
  cv::imshow("Mapa", map);

  // Save the map every DELTA_SAVE iterations
  iteration++;
  if( iteration == DELTA_SAVE )
  {
    cv::imwrite("mapa.png", map);
    iteration = 0;
  }

  /// Update distance to closest obstacles
  // Right obstacle
  angle = -1.571; // DEG2RAD(-90)
  i = round((angle - msg.angle_min)/msg.angle_increment);
  closest_right_obstacle = msg.range_max;
  while( angle < -1.309 ) // DEG2RAD(-90+15)
  {
    if( (msg.ranges[i] < msg.range_max) &&
        (msg.ranges[i] > msg.range_min) &&
        (msg.ranges[i] < closest_right_obstacle) )
      closest_right_obstacle = msg.ranges[i];
    i++;
    angle += msg.angle_increment;
  }

  // Front obstacle
  angle = -0.785; // DEG2RAD(-45)
  i = round((angle - msg.angle_min)/msg.angle_increment);
  closest_front_obstacle = msg.range_max;
  while( angle < 0.785 ) // DEG2RAD(45)
  {
    if( (msg.ranges[i] < msg.range_max) &&
        (msg.ranges[i] > msg.range_min) &&
        (msg.ranges[i] < closest_front_obstacle) )
      closest_front_obstacle = msg.ranges[i];
    i++;
    angle += msg.angle_increment;
  }

  // Left obstacle
  angle = 1.309; // DEG2RAD(90-15)
  i = round((angle - msg.angle_min)/msg.angle_increment);
  closest_left_obstacle = msg.range_max;
//.........这里部分代码省略.........
开发者ID:NunoMiguelSantos,项目名称:adv_robotics,代码行数:101,代码来源:tp04.cpp

示例8: simdetect


//.........这里部分代码省略.........
                       searches cumulative distribution of p  */
                    runif = Random();
                    k = 0;
                    while ((runif > cump[k]) && (k<nk)) k++;
                    value[*ss * (caught[i]-1) + s] = k;  /* trap = k+1 */
                }
            }
        }

        /* -------------------------------------------------------------------------------- */
        /* the 'proximity' group of detectors 1:2 - proximity, count */
        else if ((*detect >= 1) && (*detect <= 2)) {
            for (i=0; i<*N; i++) {
                for (k=0; k<nk; k++) {
		    Tski = Tsk[s * nk + k];
		    if (fabs(Tski) > 1e-10) {
                        getpar (i, s, k, x[i], *N, *ss, nk, *cc0, *cc1, *fn, 
			    bswitch (*btype, *N, i, k, caughtbefore), 
                            gsb0, gsb0val, gsb1, gsb1val, &g0, &sigma, &z);
			/* d2val = d2(i,k, animals, traps, *N, nk); */
			d2val = d2L(k, i, dist2, nk);
                        p = pfn(*fn, d2val, g0, sigma, z, miscparm, 1e20);

                        if (p < -0.1) { PutRNGstate(); return; }   /* error */

                        if (p>0) {
                            if (*detect == 1) {
				if (fabs(Tski-1) > 1e-10)
				    p = 1 - pow(1-p, Tski);
                                count = Random() < p;            /* binary proximity */
                            }
                            else if (*detect == 2) {             /* count proximity */
				if (*binomN == 1)
				    count = rcount(round(Tski), p, 1);
				else
				    count = rcount(*binomN, p, Tski);
                            }
                            if (count>0) {
                                if (caught[i]==0) {              /* first capture of this animal */
                                    nc++;
                                    caught[i] = nc;
                                    for (j=0; j<*ss; j++)
                                      for (l=0; l<nk; l++)
                                        value[*ss * ((nc-1) * nk + l) + j] = 0;
                                }
                                value[*ss * ((caught[i]-1) * nk + k) + s] = count;
                            }
                        }
                    }
                }
            }
        }

        /* -------------------------------------------------------------------------------- */
        /* exclusive polygon detectors  */
        else if (*detect == 3) {
            /* find maximum distance between animal and detector vertex */
            w = 0;
            J = cumk[nk];
            for (i = 0; i< *N; i++) {
                for (j = 0; j < J; j++) {
                    dx = animals[i] - traps[j];
                    dy = animals[*N + i] - traps[J + j];
        	    d = sqrt(dx*dx + dy*dy);
                    if (d > w) w = d;
                }
开发者ID:cran,项目名称:secr,代码行数:67,代码来源:simsecr.c

示例9: add_msg

void activity_handlers::butcher_finish( player_activity *act, player *p )
{
    // Corpses can disappear (rezzing!), so check for that
    auto items_here = g->m.i_at( p->pos() );
    if( static_cast<int>( items_here.size() ) <= act->index ||
        !( items_here[act->index].is_corpse() ) ) {
        add_msg(m_info, _("There's no corpse to butcher!"));
        return;
    }

    item &corpse_item = items_here[act->index];
    const mtype *corpse = corpse_item.get_mtype();
    std::vector<item> contents = corpse_item.contents;
    const int age = corpse_item.bday;
    g->m.i_rem( p->pos(), act->index );

    const int factor = p->butcher_factor();
    int pieces = 0;
    int skins = 0;
    int bones = 0;
    int fats = 0;
    int sinews = 0;
    int feathers = 0;
    int wool = 0;
    bool stomach = false;

    switch (corpse->size) {
    case MS_TINY:
        pieces = 1;
        skins = 1;
        bones = 1;
        fats = 1;
        sinews = 1;
        feathers = 2;
        wool = 1;
        break;
    case MS_SMALL:
        pieces = 2;
        skins = 2;
        bones = 4;
        fats = 2;
        sinews = 4;
        feathers = 6;
        wool = 2;
        break;
    case MS_MEDIUM:
        pieces = 4;
        skins = 4;
        bones = 9;
        fats = 4;
        sinews = 9;
        feathers = 11;
        wool = 4;
        break;
    case MS_LARGE:
        pieces = 8;
        skins = 8;
        bones = 14;
        fats = 8;
        sinews = 14;
        feathers = 17;
        wool = 8;
        break;
    case MS_HUGE:
        pieces = 16;
        skins = 16;
        bones = 21;
        fats = 16;
        sinews = 21;
        feathers = 24;
        wool = 16;
        break;
    }

    const int skill_level = p->skillLevel( skill_survival );

    auto roll_butchery = [&] () {
        double skill_shift = 0.0;
        ///\xrefitem Skill_Effects_Survival "" "" Survival above 3 randomly increases Butcher rolls, below 3 decreases
        skill_shift += rng_float( 0, skill_level - 3 );
        ///\xrefitem Stat_Effects_Dexterity "" "" Dexterity above 8 randomly increases Butcher rolls, slightly, below 8 decreases
        skill_shift += rng_float( 0, p->dex_cur - 8 ) / 4.0;
        ///\xrefitem Stat_Effects_Strength "" "" Strength below 4 randomly decreases Butcher rolls, slightly
        if( p->str_cur < 4 ) {
            skill_shift -= rng_float( 0, 5 * ( 4 - p->str_cur ) ) / 4.0;
        }

        if( factor < 0 ) {
            skill_shift -= rng_float( 0, -factor / 5.0 );
        }

        return static_cast<int>( round( skill_shift ) );
    };

    int practice = std::max( 0, 4 + pieces + roll_butchery());

    p->practice( skill_survival, practice );

    // Lose some meat, skins, etc if the rolls are low
    pieces +=   std::min( 0, roll_butchery() );
//.........这里部分代码省略.........
开发者ID:jvj24601,项目名称:Cataclysm-DDA,代码行数:101,代码来源:activity_handlers.cpp

示例10: dynamixel_set_joint_goal_default

// radians [-pi, pi]
// speedfrac [0,1]
// torquefrac [0,1]
void
dynamixel_set_joint_goal_default(dynamixel_device_t *device,
                                 int pmask,
                                 double radians,
                                 double speedfrac,
                                 double torquefrac)
{
    assert (!device->rotation_mode && (pmask == 0xfff || pmask == 0x3ff));

    // Ensure proper ranges
    radians = mod2pi(radians);
    speedfrac = dmax(0.0, dmin(1.0, dabs(speedfrac)));
    torquefrac = dmax(0.0, dmin(1.0, torquefrac));

    double min = device->get_min_position_radians(device);
    double max = device->get_max_position_radians(device);
    radians = dmax(min, dmin(max, radians));

    int stop = speedfrac < (1.0/0x3ff);

    int posv = ((int) round((radians - min) / (max - min) * pmask)) & pmask;
    // in joint-mode, speed == 0 --> maxspeed
    int speedv = stop ? 0x1 : (int)(speedfrac * 0x3ff);
    int torquev = (int)(torquefrac * 0x3ff);

    dynamixel_msg_t *msg = dynamixel_msg_create(7);
    msg->buf[0] = 0x1e;
    msg->buf[1] = posv & 0xff;
    msg->buf[2] = (posv >> 8) & 0xff;
    msg->buf[3] = speedv & 0xff;
    msg->buf[4] = (speedv >> 8) & 0xff;
    msg->buf[5] = torquev & 0xff;
    msg->buf[6] = (torquev >> 8) & 0xff;
    dynamixel_msg_t *resp = device->write_to_RAM(device, msg, 1);

    dynamixel_msg_destroy(msg);
    if (resp != NULL);
        dynamixel_msg_destroy(resp);

    // Handle speed == 0 case (after slowing down, above) by relaying current
    // position back to servo. Do not set torque == 0, b/c that is possibly not
    // desired...
    if (stop) {
        msg = dynamixel_msg_create(2);
        msg->buf[0] = 0x24;
        msg->buf[1] = 2;
        resp = device->bus->send_command(device->bus,
                                         device->id,
                                         INST_READ_DATA,
                                         msg,
                                         1);
        dynamixel_msg_destroy(msg);
        if (resp != NULL) {
            dynamixel_msg_destroy(resp);
            posv = (resp->buf[1] & 0xff) + ((resp->buf[2] & 0xff) << 8);
            msg = dynamixel_msg_create(3);
            msg->buf[0] = 0x1e;
            msg->buf[1] = posv & 0xff;
            msg->buf[2] = (posv > 8) & 0xff;
            resp = device->write_to_RAM(device, msg, 1);
        }

        if (resp != NULL)
            dynamixel_msg_destroy(resp);
    }
}
开发者ID:mittalrajat,项目名称:Robotics-Systems-Lab,代码行数:69,代码来源:dynamixel_device.c

示例11: stOn

QVector<EcgStDescriptor> EcgStAnalyzer::analyze(const EcgStData &data, double sampleFreq)
{
    QVector<EcgStDescriptor> result;

    int num = data.rData.size();
    int snum = data.ecgSamples.size();

    if (num < 2 || snum == 0)
        return result;

    int p = smoothSize;
    int w = detectionSize;
    double lamdba = morphologyCoeff;

    QVector<int> stOn(num);
    QVector<int> stEnd(num);

    int i;

    // detect STend points
    for (i = 0; i < num; i++)
    {
        double ka = data.jData[i];
        double kb = data.tEndData[i];

        QVector<double> aVal(kb - ka + 1);

        for (int k = ka; k <= kb; k++)
        {
            int ke = std::max(1, std::min(k + p, snum));
            int nsr = ke - k + p + 1;
            QVector<double> wnd = data.ecgSamples.mid(k - p - 1, nsr);
            double sk = EcgUtils::sum(wnd) / nsr;
            ke = std::max(1, std::min(k + w - 1, snum));

            QVector<double> sqr(ke - k);
            for (int j = 0; j < sqr.size(); j++) {
                double smp = data.ecgSamples[k + j - 1] - sk;

                if (algorithm == ST_QUADRATIC)
                    sqr[j] = smp * smp;
                else
                    sqr[j] = smp;
            }

            aVal[k - ka] = EcgUtils::sum(sqr);
        }

        int kp, kp1, kp2;
        double ap1 = EcgUtils::max(aVal, &kp1);
        double ap2 = EcgUtils::min(aVal, &kp2);

        double at = fabs(ap1) / fabs(ap2);
        if ((1.0 / lamdba < at) && (at < lamdba))
            kp = std::min(kp1, kp2);
        else
            kp = fabs(ap1) > fabs(ap2) ? kp1 : kp2;

        stEnd[i] = ka + kp;
    }

    // calculate heart rate
    QVector<int> rr = EcgUtils::diff(data.rData);
    QVector<double> hr(num);
    for (i = 0; i < num - 1; i++)
        hr[i] = 60.0 / ((double) rr[i] / sampleFreq);
    hr[num - 1] = hr[num - 2];

    for (i = 0; i < num; i++)
    {
        double rt = stEnd[i] - data.rData[i];

        double x;
        double hrc = hr[i];
        if (hrc < 100)
            x = 0.4;
        else if (hrc < 110)
            x = 0.45;
        else if (hrc < 120)
            x = 0.5;
        else
            x = 0.55;

        int test = (int) round((double) data.rData[i] + x * rt);
        stOn[i] = std::min(data.jData[i] + 1, test);
    }

    // create and classify interval descriptors
    for (i = 0; i < num; i++)
    {
        EcgStDescriptor desc;

        desc.STOn = stOn[i];
        desc.STEnd = stEnd[i];
        desc.STMid = desc.STOn + (int) round((desc.STEnd - desc.STOn) / 2.0);

        desc.offset = data.ecgSamples[desc.STMid];

        int x1 = desc.STOn;
        int x2 = desc.STMid;
//.........这里部分代码省略.........
开发者ID:qwerty90,项目名称:ProjektEKG,代码行数:101,代码来源:ecgstanalyzer.cpp

示例12: round

double SDFFsequenceElement::extract_real_t_end(){
  double ts=emanager->get_sample_timestep();
  return round((t_start+t_duration)/ts)*ts;//floor
};
开发者ID:jkriege2,项目名称:sdfflib,代码行数:4,代码来源:sdffsequenceelements.cpp

示例13: setup_domain

void setup_domain (struct geom *g) {
  /* - double pass setup; PORE regios determine global 
       inter-layer spacing dz 
  */
  
  int i;
  double l_pore=0;  /* total length of pore region, center-center */
  int    q_pore;   /* number of gaps between layers */
  int    q_check, nborders, lastborder;
  double dz, dA;
  double z1, z2;
  enum domaintypes lastdtype;
  struct domain *dom;

  dA = 0.0;                /* distance between two atoms ('bond length') */
  q_check = 0;             /* internal topology check */
  nborders = 0;            /* number of interfaces between different domains */
  lastdtype = g->domain[0]->type;

  /* first pass:
     total length of pore region and global dz
     also check correct topology: MOUTH -> PORE -> MOUTH
  */
  for (i = 0; i < g->ndomains; i++) {
    dom = g->domain[i];

    if (dom->type != lastdtype) {
      nborders++;           /* increase nborders for each change M<->P */
      lastborder = i - 1;   /* last PORE region before second MOUTH */
    };
    lastdtype   = dom->type;

    if ( dom->type == PORE) {
      l_pore += dom->l;
      dA      = max(dA, 2 * dom->species->radius);
      mesg (SUB2, "setup_domain(): l_pore = %6.3f  2*rA = %4.2f", l_pore, dA);
    };
  };

  /* if nborders != 2 => error!! */
  if ( nborders != 2 ) {
    fatal_error (2,
    "setup_domain (): Fatal error. Topology of model is incorrect. It should\n"
    "                 have been MOUTH->PORE->MOUTH with 2 borders, but there\n"
    "                 were %d borders in %d domains", nborders, g->ndomains);
  };

  q_pore = (int) l_pore/dA;  
  if ( q_pore < 1 ) {
    fatal_error (2,
		 "setup_domain (): Fatal error. Number of layers in the PORE is not positive\n"
		 "                 (q_pore = %d). (l_pore=%4.2f) < (2*rA=%4.2f)\n",
		 q_pore, l_pore, dA);
  };

  dz = l_pore/q_pore;
  /* second pass:
     number of layers q per domain and z coordinates of lower and upper layer
  */
  z2 = -dz;

  for (i = 0; i < g->ndomains; i++) {
    dom = g->domain[i];
    if ( dom->type == PORE) 
      {
	dom->q   = round (dom->l / dz);
	q_check += dom->q;
	dom->dz  = dz;           /* rather pointless to store dz separately 
				  but I still used the old strucs */
      } 
    else 
      {
	dom->q   = round (dom->l / dA);
	dom->dz  = dz;           /* pointless ... */
      };

    if (dom->q < 0) {
      fatal_error (2,
		   "setup_domain (): Fatal error. Number of layers in domain %d "
		   "is not positive\n"
		   "                 (q = %d). Probably (l=%4.2f) < (2*rA=%4.2f)\n",
		   i,dom->q, dom->l, dA);
    };

    z1 = z2 + dz;
    z2 = z1 + (dom->q - 1) * dz;

    dom->z1 = z1;
    dom->z2 = z2;

  };  

  assert (q_check == q_pore);
  return;
};
开发者ID:orbeckst,项目名称:pgeom,代码行数:95,代码来源:pgeom.c

示例14: main


//.........这里部分代码省略.........
        // generate symbol
        ofdmframegen_writesymbol(fg, X, buffer);
#if 0
        // preamble
        if      (i==0) ofdmframegen_write_S0a(fg, buffer); // S0 symbol (first)
        else if (i==1) ofdmframegen_write_S0b(fg, buffer); // S0 symbol (second)
        else if (i==2) ofdmframegen_write_S1( fg, buffer); // S1 symbol
#endif

        // compute PAPR
        PAPR[i] = ofdmframe_PAPR(buffer, frame_len);

        // compute bin index
        unsigned int index;
        float ihat = num_bins * (PAPR[i] - xmin) / (xmax - xmin);
        if (ihat < 0.0f) index = 0;
        else             index = (unsigned int)ihat;
        
        if (index >= num_bins)
            index = num_bins-1;

        hist[index]++;

        // save min/max PAPR values
        if (i==0 || PAPR[i] < PAPR_min) PAPR_min = PAPR[i];
        if (i==0 || PAPR[i] > PAPR_max) PAPR_max = PAPR[i];
        PAPR_mean += PAPR[i];
    }
    PAPR_mean /= (float)num_symbols;

    // destroy objects
    ofdmframegen_destroy(fg);
    modem_destroy(mod);

    // print results to screen
    // find max(hist)
    unsigned int hist_max = 0;
    for (i=0; i<num_bins; i++)
        hist_max = hist[i] > hist_max ? hist[i] : hist_max;

    printf("%8s : %6s [%6s]\n", "PAPR[dB]", "count", "prob.");
    for (i=0; i<num_bins; i++) {
        printf("%8.2f : %6u [%6.4f]", xmin + i*bin_width, hist[i], (float)hist[i] / (float)num_symbols);

        unsigned int k;
        unsigned int n = round(60 * (float)hist[i] / (float)hist_max);
        for (k=0; k<n; k++)
            printf("#");
        printf("\n");
    }
    printf("\n");
    printf("min  PAPR: %12.4f dB\n", PAPR_min);
    printf("max  PAPR: %12.4f dB\n", PAPR_max);
    printf("mean PAPR: %12.4f dB\n", PAPR_mean);

    // 
    // export output file
    //

    // count subcarrier types
    unsigned int M_data  = 0;
    unsigned int M_pilot = 0;
    unsigned int M_null  = 0;
    ofdmframe_validate_sctype(p, M, &M_null, &M_pilot, &M_data);

    FILE * fid = fopen(OUTPUT_FILENAME,"w");
    fprintf(fid,"%% %s: auto-generated file\n\n", OUTPUT_FILENAME);
    fprintf(fid,"clear all;\n");
    fprintf(fid,"close all;\n\n");
    fprintf(fid,"M           = %u;\n", M);
    fprintf(fid,"M_data      = %u;\n", M_data);
    fprintf(fid,"M_pilot     = %u;\n", M_pilot);
    fprintf(fid,"M_null      = %u;\n", M_null);
    fprintf(fid,"cp_len      = %u;\n", cp_len);
    fprintf(fid,"num_symbols = %u;\n", num_symbols);

    fprintf(fid,"PAPR = zeros(1,num_symbols);\n");
    for (i=0; i<num_symbols; i++)
        fprintf(fid,"  PAPR(%6u) = %12.4e;\n", i+1, PAPR[i]);

    fprintf(fid,"\n");
    fprintf(fid,"figure;\n");
    fprintf(fid,"hist(PAPR,25);\n");

    fprintf(fid,"\n");
    fprintf(fid,"figure;\n");
    fprintf(fid,"cdf = [(1:num_symbols)-0.5]/num_symbols;\n");
    fprintf(fid,"semilogy(sort(PAPR),1-cdf);\n");
    fprintf(fid,"xlabel('PAPR [dB]');\n");
    fprintf(fid,"ylabel('Complementary CDF');\n");

    fclose(fid);
    printf("results written to %s\n", OUTPUT_FILENAME);

    // free allocated array
    free(PAPR);

    printf("done.\n");
    return 0;
}
开发者ID:0xLeo,项目名称:liquid-dsp,代码行数:101,代码来源:ofdmframe_papr_test.c

示例15: trun

int trun(double num, int precision)
{
	return round(pow(10,precision)*num)/pow(10,precision);
}
开发者ID:8S,项目名称:oldvoidMain,代码行数:4,代码来源:commondefswalk.cpp


注:本文中的round函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。