I am trying to optimize the following. Below is the code:
If a = 0.775 and I need an accuracy of 2 dp, then a => 0.78
In principle, if the last digit is 5, it rounds up to the next digit, otherwise it is not.
My problem was that 0.45 is not rounded to 0.5 with 1 decimal point, as the value is saved as 0.499999999343 .... and setprecision rounds it to 0.4.
This is why setprecision is forced to be higher setprecision(p+10), and then if it really ends at 5, add a small amount for proper rounding.
After execution, it compares a with string b and returns the result. The problem is that this function is called several billion times, which makes the craw program. Any best ideas on how to rewrite / optimize this and what features in the code are so heavy on the machine?
bool match(double a,string b,int p) {
double t[] = {0.2, 0.02, 0.002, 0.0002, 0.00002, 0.000002, 0.0000002, 0.00000002};
stringstream buff;
string temp;
buff << setprecision(p+10) << setiosflags(ios_base::fixed) << a;
buff >> temp;
if(temp[temp.size()-10] == '5') a += t[p];
ostringstream test;
test << setprecision(p) << setiosflags(ios_base::fixed) << a;
temp = test.str();
if(b.compare(temp) == 0) return true;
return false;
}
Milan source
share