Skip to content

Instantly share code, notes, and snippets.

@petrstepanov
Created August 30, 2022 21:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petrstepanov/f75d556fd04fff4760dc9feddb645480 to your computer and use it in GitHub Desktop.
Save petrstepanov/f75d556fd04fff4760dc9feddb645480 to your computer and use it in GitHub Desktop.
C++ Round Vanue and Error to First Significant Number of the Error
//============================================================================
// Name : test.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <cmath>
#include <utility>
int getFirstDigit(double number){
// We obtain the first digit of the error (always positive)
// Like they teached in MEPhI
number = std::abs(number);
if (number == 1) return 1;
if (number > 1){
while(number >= 10){
number = number/10;
}
}
else if (number < 1){
while(number < 1){
number = number*10;
}
}
return (int)number;
}
std::pair<double, double> roundValueError(const double value, const double error){
// First we find the decimal point shift
int decimalPointShift = int(log10(error)); // This will give "-0.6" for 0.0234 error, "3" for
// For 0 < error < 1 we need to manually shift to the right
if (error < 1) decimalPointShift--;
// MEPhI - keep second digit if first is "1"
if (getFirstDigit(error) == 1) decimalPointShift--;
// Round error
double errorRounded = round(error*pow(10, -decimalPointShift));
double errorReverted = errorRounded*pow(10, decimalPointShift);
// Do the same operation with value
double valueRounded = int(value*pow(10, -decimalPointShift));
double valueReverted = valueRounded*pow(10, decimalPointShift);
return std::make_pair(valueReverted, errorReverted);
}
int main() {
double value = 1.432234;
double error = 0.002234;
std::pair<double,double> pair = roundValueError(value, error);
std::cout << "Original: " << value << " +- " << error << std::endl;
std::cout << "Rounded: " << pair.first << " +- " << pair.second << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment