0

The following two pieces of code produce two different outputs.

//this one gives incorrect output
cpp_dec_float_50 x=log(2)
std::cout << std::setprecision(std::numeric_limits<cpp_dec_float_50>::digits)<< x << std::endl;

The output it gives is

0.69314718055994528622676398299518041312694549560547

which is only correct upto the 15th decimal place. Had x been double, even then we'd have got first 15 digits correct. It seems that the result is overflowing. I don't see though why it should. cpp_dec_float_50 is supposed to have 50 digits precision.

//this one gives correct output
cpp_dec_float_50 x=2
std::cout << std::setprecision(std::numeric_limits<cpp_dec_float_50>::digits)<< log(x) << std::endl;

The output it gives is

0.69314718055994530941723212145817656807550013436026

which is correct according to wolframaplha .

4

2 回答 2

5

When you do log(2), you're using the implementation of log in the standard library, which takes a double and returns a double, so the computation is carried out to double precision.

Only after that's computed (to, as you noted, a mere 15 digits of precision) is the result converted to your 50-digit extended precision number.

When you do:

cpp_dec_float_50 x=2;
/* ... */ log(x);

You're passing an extended precision number to start with, so (apparently) an extended precision overload of log is being selected, so it computes the result to the 50 digit precision you (apparently) want.

于 2013-04-13T05:55:20.837 回答
3

This is really just a complex version of:

float a = 1 / 2;

Here, 1 / 2 is integer division because the parameters are integers. It's only converted to a float to be stored in a after the result is computed.

C++ rules for how to compute a result do not depend on what you do with that result. So the actual calculation of log(2) is the same whether you store it in an int, a float, or a cpp_dec_float_50.

Your second bit of code is the equivalent of:

float b = 1;
float c = 2;
float a = b / c;

Now, you're calling / on a float, so you get floating point division. C++'s rules do take into account the types of arguments and paramaters. That's complex enough, and trying to also take into account what you do with the result would make C++'s already overly-complex rules incomprehensible to mere mortals.

于 2013-04-13T05:43:51.790 回答