Exemplo n.º 1
0
int main ()
{
    printf ("rounding using ");
    switch (fegetround())
    {
    case FE_DOWNWARD:
        printf ("downward");
        break;
    case FE_TONEAREST:
        printf ("to-nearest");
        break;
    case FE_TOWARDZERO:
        printf ("toward-zero");
        break;
    case FE_UPWARD:
        printf ("upward");
        break;
    default:
        printf ("unknown");
    }
    printf (" rounding:\n");

    printf ( "nearbyint (2.3) = %.1f\n", nearbyint(2.3) );
    printf ( "nearbyint (3.8) = %.1f\n", nearbyint(3.8) );
    printf ( "nearbyint (-2.3) = %.1f\n", nearbyint(-2.3) );
    printf ( "nearbyint (-3.8) = %.1f\n", nearbyint(-3.8) );
    return 0;
}
Exemplo n.º 2
0
TEST(math, nearbyint) {
  auto guard = make_scope_guard([]() {
    fesetenv(FE_DFL_ENV);
  });
  fesetround(FE_UPWARD); // nearbyint/nearbyintf/nearbyintl obey the rounding mode.
  feclearexcept(FE_ALL_EXCEPT); // nearbyint/nearbyintf/nearbyintl don't set the FE_INEXACT flag.
  ASSERT_EQ(1234.0, nearbyint(1234.0));
  ASSERT_TRUE((fetestexcept(FE_ALL_EXCEPT) & FE_INEXACT) == 0);
  ASSERT_EQ(1235.0, nearbyint(1234.01));
  ASSERT_TRUE((fetestexcept(FE_ALL_EXCEPT) & FE_INEXACT) == 0);

  feclearexcept(FE_ALL_EXCEPT);
  ASSERT_EQ(1234.0f, nearbyintf(1234.0f));
  ASSERT_TRUE((fetestexcept(FE_ALL_EXCEPT) & FE_INEXACT) == 0);
  ASSERT_EQ(1235.0f, nearbyintf(1234.01f));
  ASSERT_TRUE((fetestexcept(FE_ALL_EXCEPT) & FE_INEXACT) == 0);

  feclearexcept(FE_ALL_EXCEPT); // nearbyint/nearbyintf/nearbyintl don't set the FE_INEXACT flag.
  ASSERT_EQ(1234.0, nearbyintl(1234.0L));
  ASSERT_TRUE((fetestexcept(FE_ALL_EXCEPT) & FE_INEXACT) == 0);
  ASSERT_EQ(1235.0, nearbyintl(1234.01L));
  ASSERT_TRUE((fetestexcept(FE_ALL_EXCEPT) & FE_INEXACT) == 0);

  fesetround(FE_TOWARDZERO); // nearbyint/nearbyintf/nearbyintl obey the rounding mode.
  ASSERT_EQ(1234.0, nearbyint(1234.01));
  ASSERT_EQ(1234.0f, nearbyintf(1234.01f));
  ASSERT_EQ(1234.0, nearbyintl(1234.01L));
}
Exemplo n.º 3
0
void test_nearbyint()
{
    static_assert((std::is_same<decltype(nearbyint((double)0)), double>::value), "");
    static_assert((std::is_same<decltype(nearbyintf(0)), float>::value), "");
    static_assert((std::is_same<decltype(nearbyintl(0)), long double>::value), "");
    assert(nearbyint(1) == 1);
}
Exemplo n.º 4
0
bool Net::timop(tick_t base, tick_t timo) {
   // Even though uniform_int_distribution takes an int, it is unsigned
   tick_t rtimo = timo 
      + dssim->rand_int(0, (int)nearbyint(0.3*timo)) 
      - (int)nearbyint(0.15*timo);
   if(rtimo <= 1) rtimo = timo;
   return now() >= (base + rtimo);
}
Exemplo n.º 5
0
Arquivo: sir.c Projeto: kingaa/pomp
void _sir_init (double *x, const double *p, double t, 
		const int *stateindex, const int *parindex, const int *covindex,
		const double *covars) {
  double m;
  m = POPSIZE/(S0+I0+R0);
  SUSC = nearbyint(m*S0);
  INFD = nearbyint(m*I0);
  RCVD = nearbyint(m*R0);
  CASE = 0;
  W = 0;
}
Exemplo n.º 6
0
int CompareDoubles2 (double A, double B)
{
    if ((nearbyint(A*1000000.0)-nearbyint(B*1000000.0))>0.0) {
        return 1;
    }else if ((nearbyint(A*1000000.0)-nearbyint(B*1000000.0))==0.0){
        return 0;
    }else{
        return -1;
    }
    
}
Exemplo n.º 7
0
void GrowAxis::format_text( char *text, char *fmt, double value) 
{
  if ( strcmp( fmt, "%1t") == 0) {
    // Hours, minutes and seconds, value in seconds
    int val = (int) nearbyint(value);
    int hours = val / 3600;
    int minutes = (val - hours * 3600) / 60; 
    int seconds = (val - hours * 3600 - minutes * 60); 
    sprintf( text, "%d:%02d:%02d", hours, minutes, seconds);
  }
  else if ( strcmp( fmt, "%2t") == 0) {
    // Hours and minutes, value in seconds
    int val = (int) nearbyint(value);
    int hours = val / 3600;
    int minutes = (val - hours * 3600) / 60; 
    sprintf( text, "%d:%02d", hours, minutes);
  }
  else if ( strcmp( fmt, "%3t") == 0) {
    // Days, hours and minues, value in seconds
    int val = (int) nearbyint(value);
    int days = val / (24 * 3600);
    int hours = (val - days * 24 * 3600) / 3600; 
    int minutes = (val - days * 24 * 3600 - hours * 3600) / 60; 
    sprintf( text, "%d %02d:%02d", days, hours, minutes);
  }
  else if ( strcmp( fmt, "%10t") == 0) {
    // Date
    char timstr[40];
    pwr_tTime t;
    t.tv_sec = (int) nearbyint(value);
    t.tv_nsec = 0;
    
    time_AtoAscii( &t, time_eFormat_NumDateAndTime, timstr, sizeof(timstr));
    timstr[19] = 0;
    strcpy( text, timstr);
  }
  else if ( strcmp( fmt, "%11t") == 0) {
    // Date, no seconds
    char timstr[40];
    pwr_tTime t;
    t.tv_sec = (int) nearbyint(value);
    t.tv_nsec = 0;
    
    time_AtoAscii( &t, time_eFormat_NumDateAndTime, timstr, sizeof(timstr));
    timstr[16] = 0;
    strcpy( text, timstr);
  }
  else {
    if ( fabs(value) < FLT_EPSILON)
      value = 0;
    sprintf( text, fmt, value);
  }
}
  std::string DEGU_CORNER::getValue(SpMObject mobile, Datapool& datapool) {
      if(checked) {
         checked = true;
         valid = true;
         //First check zones
         std::vector< QSharedPointer<world::ZoneH> > &zones = datapool.sceneModel->ZonesH;
         if (zones.empty())
             valid = false;
         else {
            int num = 0;
            std::vector< QSharedPointer<world::ZoneH> >::iterator zone_it, zone_end = zones.end();
            for(zone_it = zones.begin(); zone_it != zone_end; zone_it++ ) {
                if(values.count((*zone_it)->name.toStdString()) == 1) {
                    num++;
                    DEGU_CORNER::zones[(*zone_it)->name.toStdString()] = (*zone_it);
                }
            }
            if(num != values.size() - 1)
                valid = false;
         }
      }

      SpReliabilitySingleModelInterface m = mobile->getSubModel("BaseModel");
      if(m.isNull())
          return "NONE";

      if(valid) {
          double dist, X, Y, min_dist = DBL_MAX;
          std::string nearest;
          if(datapool.sceneModel->hmatrix_filled) {
            datapool.sceneModel->imgToHomographyCoords(datapool.sceneModel->h_matrix,
                                                       nearbyint(m->dynamics.dynamics["X"].att.value),
                                                       nearbyint(m->dynamics.dynamics["Y"].att.value),
                                                       &X, &Y);
            QSharedPointer<world::ZoneH> z;
            std::map< std::string, QSharedPointer<world::ZoneH> >::iterator it, it_end = zones.end();
            for(it = zones.begin();it != it_end; it++) {
                z = (*it).second;
                if(z->pointInZone(X,Y)) {
                    dist = z->distanceToCenter(X,Y);
                    if(dist < min_dist) {
                        min_dist = dist;
                        nearest = (*it).first;
                    }
                }
            }
            if(min_dist < DBL_MAX)
                return nearest;
         }
      }
      return "NONE";
  }
Exemplo n.º 9
0
int main()
{
    if ( fesetround( FE_TOWARDZERO) == 0)
       printf("The current rounding mode is \"round toward 0.\"\n");
    else
       printf("The rounding mode is unchanged.\n");

    printf( "nearbyint(1.9) = %4.1f    nearbyint(-1.9) = %4.1f\n",
            nearbyint(1.9), nearbyint(-1.9) );

    printf( "round(1.9) = %4.1f        round(-1.9) = %4.1f\n",
            round(1.9), round(-1.9) );

    return 0;
}
Exemplo n.º 10
0
void create_spherical_texture(int size, GLuint& tex)
{
	struct elem {
		unsigned char l;
		unsigned char a;
	};

	elem* buffer = (elem *) malloc(size * size * sizeof(elem));
	float r = (float)size / 2.0;

	for(int i = 0; i < size; ++i)
	{
		for(int j = 0; j < size; ++j)
		{
			float d = hypotf(i - r, j - r);
			buffer[(i * size) + j].l = 255u;
			buffer[(i * size) + j].a = d > r ? 0u : (unsigned char)nearbyint(sqrtf(r*r - d*d) / r * 255.0);
		}
	}

	glGenTextures(1, &tex);
	glBindTexture(GL_TEXTURE_2D, tex);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, size, size, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, (GLvoid*)buffer);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glBindTexture(GL_TEXTURE_2D, 0);

	free(buffer);
}
Exemplo n.º 11
0
void
dockapp_draw_bar_calculate( float draw_size, int bar_draw_x, int bar_draw_y )
{
   float draw_percent_f;
   int draw_percent;

   draw_percent_f = ( GET_HRS_F( draw_size ) / DOCKAPP_BAR_WIDTH ) * 100.0f;
   draw_percent = ( int ) nearbyint( draw_percent_f );

  if ( DOCKAPP_BAR_WIDTH == draw_percent )
  {
     dockapp_draw_bar( draw_percent,
		       bar_draw_x,
		       bar_draw_y,
		       DOCKAPP_BAR_OFF_X,
		       DOCKAPP_BAR_OFF_Y );
  }
  else
  {
     dockapp_draw_bar( draw_percent,
		       bar_draw_x,
		       bar_draw_y,
		       DOCKAPP_BAR_ON_X,
		       DOCKAPP_BAR_ON_Y );
  }
}
void mtsIntuitiveResearchKitPSM::RunPositionCartesian(void)
{
    //! \todo: should prevent user to go to close to RCM!

    if (IsCartesianGoalSet == true) {
        vctDoubleVec jointSet(6, 0.0);
        jointSet.Assign(JointCurrent, 6);

        // compute desired slave position
        CartesianPositionFrm.From(CartesianGoalSet.Goal());
        CartesianPositionFrm = CartesianPositionFrm * Frame6to7Inverse;

        Manipulator.InverseKinematics(jointSet, CartesianPositionFrm);
        jointSet.resize(7);
        jointSet[6] = DesiredOpenAngle;
#if 1 // Anton
        const double difference = JointCurrent[3] - jointSet[3];
        const double differenceInTurns = nearbyint(difference / (2.0 * cmnPI));
        jointSet[3] = jointSet[3] + differenceInTurns * 2.0 * cmnPI;
        /*
        if (differenceInTurns != 0.0) {
            CMN_LOG_CLASS_RUN_DEBUG << GetName()
                                    << " diff = " << difference
                                    << " turns = " << difference / (2.0 * cmnPI)
                                    << " corr = " << differenceInTurns
                                    << " res = " << jointSet[3] << std::endl;
        }
        */
#endif // Anton
        SetPositionJointLocal(jointSet);

        // reset flag
        IsCartesianGoalSet = false;
    }
}
Exemplo n.º 13
0
/**
 * This is a microbenchmark to get cpu frequency the process is running on. The
 * returned value is used to convert TSC counter values to microseconds.
 *
 * @return int64.
 * @author cjiang
 */
static int64_t get_cpu_frequency() {
  struct timeval start;
  struct timeval end;

  if (gettimeofday(&start, 0)) {
    perror("gettimeofday");
    return 0.0;
  }
  uint64_t tsc_start = cpuCycles();
  uint64_t tsc_end;
  volatile int i;
  // Busy loop for 5 miliseconds. Don't use usleep() here since it causes the
  // CPU to halt which will generate meaningless results.
  do {
    for (i = 0; i < 1000000; i++);
    if (gettimeofday(&end, 0)) {
      perror("gettimeofday");
      return 0.0;
    }
    tsc_end = cpuCycles();
  } while (get_us_interval(&start, &end) < 5000);

  return nearbyint((tsc_end - tsc_start) * 1.0
                                   / (get_us_interval(&start, &end)));
}
Exemplo n.º 14
0
void on_colorselection_color_changed (GtkColorSelection *colorselection, gpointer user_data)
{
    char szhsv[64];
    gdouble r, g, b;
    gdouble h, s, v;
    gtk_color_selection_get_current_color (colorselection, &colorvalue);
    r = 1.0 * colorvalue.red / 65535;
    g = 1.0 * colorvalue.green / 65535;
    b = 1.0 * colorvalue.blue / 65535;
    gtk_rgb_to_hsv(r, g, b, &h, &s, &v);
    snprintf(szhsv, sizeof(szhsv), "OpenCV H: %hu S: %hu V: %hu",
             (uint16_t)nearbyint(h * 180.0),
             (uint16_t)nearbyint(s * 255.0),
             (uint16_t)nearbyint(v * 255.0));
    gtk_entry_set_text((GtkEntry *)mytext, szhsv);
}
Exemplo n.º 15
0
static int64_t* get_cpu_frequency_from_file(const char *file, int ncpus)
{
  std::ifstream cpuinfo(file);
  if (cpuinfo.fail()) {
    return nullptr;
  }
  char line[MAX_LINELENGTH];
  int64_t* freqs = new int64_t[ncpus];
  for (int i = 0; i < ncpus; ++i) {
    freqs[i] = 0;
  }
  int processor = -1;

  while (cpuinfo.getline(line, sizeof(line))) {
    if (sscanf(line, "processor : %d", &processor) == 1) {
      continue;
    }
    float freq;
    if (sscanf(line, "cpu MHz : %f", &freq) == 1) {
      if (processor != -1 && processor < ncpus) {
         freqs[processor] = nearbyint(freq);
         processor = -1;
      }
    }
  }
  for (int i = 0; i < ncpus; ++i) {
    if (freqs[i] == 0) {
      delete[] freqs;
      return nullptr;
    }
  }
  return freqs;
}
Exemplo n.º 16
0
void rndit(double *a, double *b, int n)
{
    int i ;

    for (i=0; i<n; ++i) {
        a[i] = nearbyint(b[i]) ;
    }
}
Exemplo n.º 17
0
static inline int_check_t is_unconvertible_double(const double x, const double tol) {
    if (!ISNAN(x)) {
        if (x <= INT_MIN || x > INT_MAX)
            return INT_RANGE;
        if (fabs(x - nearbyint(x)) >= tol)
            return INT_TOL;
    }
    return INT_OK;
}
// setters
void
OWLDatabase::update_node(id_t id, const tags_t &attrs, const tags_t &tags) {
  // simple implementation as a delete-add. this isn't efficient, but it might not need to be.
  const int lat = nearbyint(lexical_cast<double>(required_attribute(attrs, "lat")) * SCALE);
  const int lon = nearbyint(lexical_cast<double>(required_attribute(attrs, "lon")) * SCALE);
  delete_node(id);

  stringstream query;
  query << "insert into nodes (id, version, changeset, lat, lon, tile) values ("
        << id << ", "
        << required_attribute(attrs, "version") << ", "
        << required_attribute(attrs, "changeset") << ", "
        << lat << ", " << lon << ", "
        << util::xy2tile(util::lon2x(lon), util::lat2y(lat)) << ")";
  transaction.exec(query);

  add_tags(transaction, "node_tags", id, tags);
}
Exemplo n.º 19
0
double
PTnint(double arg1)
{
    /* round to "nearest integer",
     *   round half-integers to the nearest even integer
     *   rely on default rounding mode of IEEE 754 to do so
     */
    return nearbyint(arg1);
}
Exemplo n.º 20
0
static inline double qwtRoundValueF( double value )
{
#if 1
    // MS Windows and at least IRIX does not have C99's nearbyint() function
    return ( value >= 0.0 ) ? ::floor( value + 0.5 ) : ::ceil( value - 0.5 );
#else
    return nearbyint( value );
#endif
}
Exemplo n.º 21
0
static void testit(int testnum, float in, float out)
{

    feclearexcept(ALL_STD_EXCEPT);
    assert(fpequal(out, nearbyintf(in)));
    assert(fpequal(-out, nearbyintf(-in)));
    assert(fetestexcept(ALL_STD_EXCEPT) == 0);

    assert(fpequal(out, nearbyint(in)));
    assert(fpequal(-out, nearbyint(-in)));
    assert(fetestexcept(ALL_STD_EXCEPT) == 0);

    assert(fpequal(out, nearbyintl(in)));
    assert(fpequal(-out, nearbyintl(-in)));
    assert(fetestexcept(ALL_STD_EXCEPT) == 0);

    printf("ok %d\t\t# nearbyint(%g)\n", testnum, in);
}
Exemplo n.º 22
0
int calcProb(int skill, int d) {
    int maxProb = 100;

    int prob = nearbyint((10+90.0*skill)/(0.5*d*sqrt(d) - 0.5));
    if (prob > maxProb) {
        prob = maxProb;
    }
    return prob;
}
Exemplo n.º 23
0
static int colour8(double d)
{
  int i = nearbyint(255*d);

  i = MAX(i, 0);
  i = MIN(i, 255);

  return i;
}
Exemplo n.º 24
0
double qpois(double p, double lambda, int lower_tail, int log_p)
{
    double mu, sigma, gamma, z, y;
#ifdef IEEE_754
    if (ISNAN(p) || ISNAN(lambda))
	return p + lambda;
#endif
    if(!R_FINITE(lambda))
	ML_ERR_return_NAN;
    if(lambda < 0) ML_ERR_return_NAN;
    R_Q_P01_check(p);
    if(lambda == 0) return 0;
    if(p == R_DT_0) return 0;
    if(p == R_DT_1) return ML_POSINF;

    mu = lambda;
    sigma = sqrt(lambda);
    /* gamma = sigma; PR#8058 should be kurtosis which is mu^-0.5 */
    gamma = 1.0/sigma;

    /* Note : "same" code in qpois.c, qbinom.c, qnbinom.c --
     * FIXME: This is far from optimal [cancellation for p ~= 1, etc]: */
    if(!lower_tail || log_p) {
	p = R_DT_qIv(p); /* need check again (cancellation!): */
	if (p == 0.) return 0;
	if (p == 1.) return ML_POSINF;
    }
    /* temporary hack --- FIXME --- */
    if (p + 1.01*DBL_EPSILON >= 1.) return ML_POSINF;

    /* y := approx.value (Cornish-Fisher expansion) :  */
    z = qnorm(p, 0., 1., /*lower_tail*/TRUE, /*log_p*/FALSE);
#ifdef HAVE_NEARBYINT
    y = nearbyint(mu + sigma * (z + gamma * (z*z - 1) / 6));
#else
    y = round(mu + sigma * (z + gamma * (z*z - 1) / 6));
#endif

    z = ppois(y, lambda, /*lower_tail*/TRUE, /*log_p*/FALSE);

    /* fuzz to ensure left continuity; 1 - 1e-7 may lose too much : */
    p *= 1 - 64*DBL_EPSILON;

    /* If the mean is not too large a simple search is OK */
    if(lambda < 1e5) return do_search(y, &z, p, lambda, 1);
    /* Otherwise be a bit cleverer in the search */
    {
	double incr = floor(y * 0.001), oldincr;
	do {
	    oldincr = incr;
	    y = do_search(y, &z, p, lambda, incr);
	    incr = fmax2(1, floor(incr/100));
	} while(oldincr > 1 && incr > lambda*1e-15);
	return y;
    }
}
Exemplo n.º 25
0
//get the distance between two cities
int getDistance(struct structCity A, struct structCity B)
{
    //get distance between two cities
    int x=A.iX-B.iX;//subtract x coordinates
    int y=A.iY-B.iY;//subtract y coordinates
    double dist=pow(y,2)+pow(x,2);// raise both to the power of two and add
    double distance=sqrt(dist);//sqrt of the sum of x^2+y^2
    int myDistance=nearbyint(distance);//round to nearest int
    return myDistance;
}
Exemplo n.º 26
0
// return the objective value
CUDFcoefficient cplex_solver::objective_value() { 
	double objval;
	int  status = CPXgetobjval (env, lp, &objval);
	if (status) {
		fprintf (stderr,"No MIP objective value available.  Exiting...\n");
		exit(-1);
	}
	//  printf("Objective value = % 24.24e\n", objval);
	return (CUDFcoefficient)nearbyint(objval);
}
Exemplo n.º 27
0
Arquivo: sir.c Projeto: kingaa/pomp
void _sir_binom_rmeasure (double *y, double *x, double *p, 
			  int *obsindex, int *stateindex, int *parindex, int *covindex,
			  int ncovars, double *covars, double t) {
  double mean, sd;
  double rep;
  mean = CASE*RHO;
  sd = sqrt(CASE*RHO*(1-RHO));
  rep = nearbyint(rnorm(mean,sd));
  REPORTS = (rep > 0) ? rep : 0;
}
Exemplo n.º 28
0
/*
 * Compression: converts the arguments of floats and returns a scaled integer in
 * the range of plus or minus 15. 
 */
static int convertToScaledInt(float num) {
    if(num > .3) num = .3;
    else if (num < -.3) num = -.3;
    int scaled = nearbyint(50.0*num);
    if (scaled > 15)
        scaled = 15;
    if (scaled < -15)
        scaled = -15;

  return scaled;
}
int ResetStateOnTriggerTestProbe::outputState(double timevalue) {
   getValues(timevalue); // calls calcValues
   if (parent->columnId()!=0) { return PV_SUCCESS; }
   if (probeStatus != 0) {
      int nBatch = getNumValues();
      if (nBatch==1) {
         int nnz = (int) nearbyint(getValuesBuffer()[0]);
         fprintf(outputstream->fp, "%s t=%f, %d neuron%s the wrong value.\n",
               getMessage(), timevalue, nnz, nnz==1 ? " has" : "s have");
      }
      else {
         for (int k=0; k<nBatch; k++) {
            int nnz = (int) nearbyint(getValuesBuffer()[k]);
            fprintf(outputstream->fp, "%s t=%f, batch element %d, %d neuron%s the wrong value.\n",
                  getMessage(), timevalue, k, nnz, nnz==1 ? " has" : "s have");
         }
      }
   }
   return PV_SUCCESS;
}
Exemplo n.º 30
0
void SunMoonStripWidget::display_moons(uint8 day, uint8 hour, uint8 minute)
{
    uint8 phase = 0;
    // trammel (starts 1 hour ahead of sun)
    phase = uint8(nearbyint((day-1)/TRAMMEL_PHASE)) % 8;
    Tile *tileA = tile_manager->get_tile((phase == 0) ? 584 : 584 + (8-phase)); // reverse order in tilelist
    uint8 posA = ((hour + 1) + 3*phase) % 24; // advance 3 positions each phase-change

    // felucca (starts 1 hour behind sun)
    // ...my FELUCCA_PHASE may be wrong but this method works with it...
    sint8 phaseb = (day-1) % uint8(nearbyint(FELUCCA_PHASE*8)) - 1;
    phase = (phaseb >= 0) ? phaseb : 0;
    Tile *tileB = tile_manager->get_tile((phase == 0) ? 584 : 584 + (8-phase)); // reverse order in tilelist
    uint8 posB = ((hour - 1) + 3*phase) % 24; // advance 3 positions per phase-change

    if(posA >= 5 && posA <= 19)
        display_sun_moon(tileA, posA - 5);
    if(posB >= 5 && posB <= 19)
        display_sun_moon(tileB, posB - 5);
}