Java Code Examples for org.apache.commons.math3.util.Precision#round()

The following examples show how to use org.apache.commons.math3.util.Precision#round() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AnalyticsUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Rounds a value. If the given parameters has skip rounding, the value is
 * rounded to {@link AnalyticsUtils#DECIMALS_NO_ROUNDING}. decimals. If the
 * given number of decimals is specified, the value is rounded to the given
 * decimals. Otherwise, default rounding is used. If 0 decimals is explicitly
 * specified, this method returns a long value. Otherwise, a double value is
 * returned.
 *
 * @param params the query parameters.
 * @param decimals the number of decimals.
 * @param value the value.
 * @return a double.
 */
public static Number getRoundedValue( DataQueryParams params, Integer decimals, Double value )
{
    if ( value == null )
    {
        return value;
    }
    else if ( params.isSkipRounding() )
    {
        return Precision.round( value, DECIMALS_NO_ROUNDING );
    }
    else if ( decimals != null && decimals > 0 )
    {
        return Precision.round( value, decimals );
    }
    else if ( decimals != null && decimals == 0 )
    {
        return Math.round( value );
    }
    else
    {
        return MathUtils.getRounded( value );
    }
}
 
Example 2
Source File: DirectiveTransformer.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private static void validateMinMax(Model curState, double target) {
   double minSetPoint = Precision.round(getMinSp(curState), 2);
   double maxSetPoint = Precision.round(getMaxSp(curState), 2);
   double roundedTarget = Precision.round(target, 2);
   if(roundedTarget < minSetPoint || roundedTarget > maxSetPoint) {
      throw new AlexaException(AlexaErrors.temperatureValueOutOfRange(target, Precision.round(minSetPoint, 2), Precision.round(maxSetPoint, 2)));
   }
}
 
Example 3
Source File: Txfm.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T extends TemperatureConfirmationPayload> T thermostatResponse(MessageBody response, Supplier<T> factory) {
   Map<String, Object> payload = (Map<String, Object>) AlexaService.ExecuteResponse.getPayload(response);

   Boolean result = (Boolean) payload.get(ThermostatCapability.SetIdealTemperatureResponse.ATTR_RESULT);
   String mode = (String) payload.get(ThermostatCapability.SetIdealTemperatureResponse.ATTR_HVACMODE);
   if(Boolean.FALSE.equals(result)) {

      if(ThermostatCapability.HVACMODE_OFF.equals(mode)) {
         throw new ErrorPayloadException(new UnwillingToSetValueError("ThermostatIsOff", "The requested operation is unsafe because it requires changing the mode."));
      }

      throw new ErrorPayloadException(
         new ValueOutOfRangeError(
            Precision.round((Double) payload.get(ThermostatCapability.SetIdealTemperatureResponse.ATTR_MINSETPOINT), 2),
            Precision.round((Double) payload.get(ThermostatCapability.SetIdealTemperatureResponse.ATTR_MAXSETPOINT), 2)
         )
      );
   }

   Double prevIdeal = ((Number) payload.get(ThermostatCapability.SetIdealTemperatureResponse.ATTR_PREVIDEALTEMP)).doubleValue();
   Double idealTempSet = ((Number) payload.get(ThermostatCapability.SetIdealTemperatureResponse.ATTR_IDEALTEMPSET)).doubleValue();

   TemperatureConfirmationPayload.PreviousState prevState = new TemperatureConfirmationPayload.PreviousState();
   prevState.setMode(new StringValue(mode));
   prevState.setTargetTemperature(new DoubleValue(prevIdeal));
   T confirm = factory.get();
   confirm.setTargetTemperature(new DoubleValue(idealTempSet));
   confirm.setTemperatureMode(prevState.getMode());
   confirm.setPreviousState(prevState);
   return confirm;
}
 
Example 4
Source File: SakaiBLTIUtil.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public static String getRoundedGrade(Double theGrade, Double points) throws Exception {
	if (theGrade < 0.0 || theGrade > 1.0) {
		throw new Exception("Grade out of range");
	}
	theGrade = theGrade * points;
	theGrade = Precision.round(theGrade, 2);
	return String.valueOf(theGrade);
}
 
Example 5
Source File: QuestionScoresBean.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
  * get the max Point
  *
  * @return the max point
  */
 public String getMaxPoint()
   {  
  ResourceLoader rb=new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages");
try{
	if (this.getMaxScore() == 1.0)
		return Precision.round(this.getMaxScore(), 2)+ " " + rb.getString("point");
else
	return Precision.round(this.getMaxScore(), 2)+ " " + rb.getString("points");
}
catch(NumberFormatException e){
	return Precision.round(this.getMaxScore(), 2)+ " " + rb.getString("point");
}
   }
 
Example 6
Source File: CosineSimilarityEvaluator.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public static double cosineSimilarity(double[] vectorA, double[] vectorB) {
  double dotProduct = 0.0;
  double normA = 0.0;
  double normB = 0.0;
  for (int i = 0; i < vectorA.length; i++) {
    dotProduct += vectorA[i] * vectorB[i];
    normA += Math.pow(vectorA[i], 2);
    normB += Math.pow(vectorB[i], 2);
  }
  double d = dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
  return Precision.round(d, 8);
}
 
Example 7
Source File: QuestionScoresBean.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
  * get the max Point
  *
  * @return the max point
  */
 public String getMaxPoint()
   {  
  ResourceLoader rb=new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages");
try{
	if (this.getMaxScore() == 1.0)
		return Precision.round(this.getMaxScore(), 2)+ " " + rb.getString("point");
else
	return Precision.round(this.getMaxScore(), 2)+ " " + rb.getString("points");
}
catch(NumberFormatException e){
	return Precision.round(this.getMaxScore(), 2)+ " " + rb.getString("point");
}
   }
 
Example 8
Source File: ContentsDeliveryBean.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * If we display the current score, return it, otherwise an empty string.
 * Not currently used, provided if we need it later.
 * @return either, a) the current score, otherwise, b) "" (empty string)
 */
public String getPointsDisplayString()
{
 String pointsDisplayString = "";
 if (showStudentScore)
 {
  pointsDisplayString = "" + Precision.round(currentScore, 2);
 }
 return pointsDisplayString;
}
 
Example 9
Source File: SakaiBLTIUtil.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public static String getRoundedGrade(Double theGrade, Double points) throws Exception {
	if (theGrade < 0.0 || theGrade > 1.0) {
		throw new Exception("Grade out of range");
	}
	theGrade = theGrade * points;
	theGrade = Precision.round(theGrade, 2);
	return String.valueOf(theGrade);
}
 
Example 10
Source File: DoubleType.java    From json-data-generator with Apache License 2.0 5 votes vote down vote up
@Override
public Double getNextRandomValue() {
    double range = max - min;
    double scaled = rand.nextDouble() * range;
    double shifted = scaled + min;

    return Precision.round(shifted, decimalPlaces);

}
 
Example 11
Source File: MathUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Rounds a number, keeping at least 3 significant digits.
 * <p>
 * <ul>
 * <li>If value is >= 10 or <= -10 it will have 1 decimal.</li>
 * <li>If value is between -10 and 10 it will have three significant digits.</li>
 * </ul>
 *
 * @param value the value to round off.
 * @return a rounded off number.
 */
public static double roundSignificant( double value )
{
    if ( value >= 10.0 || value <= -10.0 )
    {
        return Precision.round( value, 1 );
    }
    else
    {
        return roundToSignificantDigits( value, 3 );
    }
}
 
Example 12
Source File: SectionContentsBean.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public double getRoundedMaxPoints()
{
  // only show 2 decimal places 
  
  return Precision.round(maxPoints, 2);
}
 
Example 13
Source File: ItemContentsBean.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public double getRoundedMaxPointsToDisplay() {
	return Precision.round(maxPoints, 2);		
}
 
Example 14
Source File: GradebookServiceHelperImpl.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
 * Update the grading of the assessment.
 * @param ag the assessment grading.
 * @param g  the Gradebook Service
 * @throws java.lang.Exception
 */
public void updateExternalAssessmentScore(AssessmentGradingData ag,
  GradebookExternalAssessmentService g) throws
  Exception
{
  boolean testErrorHandling=false;
  PublishedAssessmentService pubService = new PublishedAssessmentService();
  GradingService gradingService = new GradingService();

  //Following line seems just for the need of getting publishedAssessmentId
  //use ag.getPublishedAssessmentId() instead of pub.getPublishedAssessmentId() to
  //get publishedAssessmentId 
  //comment out following 3 lines since it returns null for not submitted students which we 
  //need not save to assessmentgrading table but will need to notify gradebook only  
  
 /* PublishedAssessmentIfc pub = (PublishedAssessmentIfc) gradingService.getPublishedAssessmentByAssessmentGradingId(ag.getAssessmentGradingId().toString());

  String gradebookUId = pubService.getPublishedAssessmentOwner(
         pub.getPublishedAssessmentId());*/
  String gradebookUId = pubService.getPublishedAssessmentOwner(
          ag.getPublishedAssessmentId());
  if (gradebookUId == null)
  {
    return;
  }
  
  //Will pass to null value when last submission is deleted
  String points = null;
  if(ag.getFinalScore() != null) {
      //SAM-1562 We need to round the double score and covert to a double -DH
      double fScore = Precision.round(ag.getFinalScore(), 2);
      Double score = Double.valueOf(fScore).doubleValue();
      points = score.toString();
      log.info("rounded:  " + ag.getFinalScore() + " to: " + score.toString() );
  }
  g.updateExternalAssessmentScore(gradebookUId,
    ag.getPublishedAssessmentId().toString(),
    ag.getAgentId(),  points);
  if (testErrorHandling){
    throw new Exception("Encountered an error in update ExternalAssessmentScore.");
  }
}
 
Example 15
Source File: ItemContentsBean.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public double getRoundedMaxPointsToDisplay() {
	return Precision.round(maxPoints, 2);		
}
 
Example 16
Source File: DefaultHistoryRetriever.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public DataElementHistory getHistory( DataElement dataElement, CategoryOptionCombo optionCombo,
		CategoryOptionCombo attributeOptionCombo, OrganisationUnit organisationUnit, Period lastPeriod, int historyLength )
{
    if ( !dataElement.getValueType().isNumeric() )
    {
        return null; // TODO
    }

    // ---------------------------------------------------------------------
    // Initialise history
    // ---------------------------------------------------------------------

    DataElementHistory history = new DataElementHistory();
    history.setDataElement( dataElement );
    history.setOptionCombo( optionCombo );
    history.setAttributeOptionComboOptionCombo( attributeOptionCombo );
    history.setOrganisationUnit( organisationUnit );
    history.setHistoryLength( historyLength );
    addMinMaxLimits( organisationUnit, dataElement, optionCombo, history );

    // ---------------------------------------------------------------------
    // Create history points
    // ---------------------------------------------------------------------

    List<Period> periods = periodService.getPeriods( lastPeriod, historyLength );

    double max = 1;
    double average = 0;
    double total = 0;
    int count = 0;

    if ( history.getMaxLimit() != null )
    {
        max = Math.max( max, history.getMaxLimit() );
    }

    for ( Period period : periods )
    {
        DataElementHistoryPoint historyPoint = new DataElementHistoryPoint();
        historyPoint.setPeriod( period );

        Double value = getValue( dataElement, optionCombo, attributeOptionCombo, organisationUnit, period );

        if ( value != null )
        {
            historyPoint.setValue( value );
        }

        if ( historyPoint.getValue() != null )
        {
            max = Math.max( max, historyPoint.getValue() );
            total += historyPoint.getValue();
            average = total / ++count;
            average = Precision.round( average, 1 );
        }

        historyPoint.setAverage( average );

        history.getHistoryPoints().add( historyPoint );
    }

    history.setMaxHistoryValue( max );

    double maxValue = getMaxValue( history );

    if ( !MathUtils.equals( maxValue, Double.NEGATIVE_INFINITY ) )
    {
        history.setMaxValue( maxValue );

        double minValue = getMinValue( history );
        history.setMinValue( minValue );
    }

    return history;
}
 
Example 17
Source File: SpermSeqMarkDuplicates.java    From Drop-seq with MIT License 4 votes vote down vote up
public void calculateStats() {
	this.PCT_DUPLICATES=(double) this.NUM_DUPLICATES / (double) this.NUM_MAPPED_READS * 100;
	this.PCT_DUPLICATES=Precision.round(this.PCT_DUPLICATES, 3);
	this.ESTIMATED_LIBRARY_SIZE = DuplicationMetrics.estimateLibrarySize(this.NUM_MAPPED_READS, this.NUM_MAPPED_READS - this.NUM_DUPLICATES);
}
 
Example 18
Source File: DirectiveTransformer.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
private static double fToC(double val) {
   return Precision.round((val-32.0) * (5.0/9.0), 2);
}
 
Example 19
Source File: MathUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
/**
 * Returns a rounded off number.
 * <p>
 * <ul>
 * <li>If value is exclusively between 1 and -1 it will have 2 decimals.</li>
 * <li>If value if greater or equal to 1 the value will have 1 decimal.</li>
 * </ul>
 *
 * @param value the value to round off.
 * @return a rounded off number.
 */
public static double getRounded( double value )
{
    int scale = ( value < 1d && value > -1d ) ? 2 : 1;
    
    return Precision.round( value, scale );
}
 
Example 20
Source File: ItemContentsBean.java    From sakai with Educational Community License v2.0 2 votes vote down vote up
/**
 * String representation of the rounded discount.
 *
 * @return String representation of the discount.
 */
public double getDiscount() {
	 return Precision.round(discount, 2);
}