-1

I am looking to speed up a function that maps one double number to another double number. However the function must remain the same. Same same input must produce exactly the same output as before. The reason for this is we don't want to introduce any differences into the system, even if this original function has questionable behavior.

Function is:

double g(double d)
{
        std::stringstream ss;
        ss.precision(10);
        ss<<std::fixed<<d;
        std::string asString;
        ss >> asString;
        return atof(asString.c_str());
}

Function looks pretty slow. Converting a double to another double by going through strings looks odd.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
steviekm3
  • 905
  • 1
  • 8
  • 19

1 Answers1

1

An easier way to get a double to a precision of 10 decimal digits is by adding a number that is pow(10, 10) times bigger to the value and then subtracting it again. Like so:

double n = pow(10, 10 + ((long) log(d) / log(10)));
double truncated = d + n;
return truncated - n;
randomusername
  • 7,927
  • 23
  • 50
  • Let me give that a try. Thanks. – steviekm3 Dec 04 '14 at 20:59
  • 1
    the problem is that this is the land of floating point. He asks for a version that produces the same output, its not clear that this will produce the exact same output. JUst as its not clear that the original function will round to 10 places – pm100 Dec 04 '14 at 21:01
  • 1
    That's true, although final answer will only be at most one decimal digit off (more like 2 bits but that's hard to gauge when dealing with base 10). – randomusername Dec 04 '14 at 21:04
  • I did try and exact same output not produced. It looks like I will have to dig around what std::fixed std::precison and atof actually do down to detailed level. – steviekm3 Dec 04 '14 at 21:05
  • @steviekm3 Comparing strings is certainly the worst approach you can coose regarding performance! – πάντα ῥεῖ Dec 04 '14 at 21:06