开发者

How to do a correct size check?

Having four va开发者_运维百科rs:

short mantissa,  
exponent,  
base;  
long double factor;

How shall I check each of those three components to ensure that result will fit into factor? Or maybe leave it as a user responsibility to make sure that data provided make sense?


Since factor is a floating point value (long double), the result will almost always fit. It won't always be very precise when the number gets large, but it will never overflow unless the exponent is larger than can fit in a long double's mantissa (usually 11 bits, so usually 2^11).

If you want to do a crude check for precision, compute the answer and then check if it's within a reasonable range such as [10^20, 10^-20].


Basically you can't exactly do this because the format of how long double stores the data is unspecified by the standard. However you can approximate what you want by comparing with: numeric_limits<long double>::digits, numeric_limits<long double>::radix, numeric_limits<long double>::min_exponent and numeric_limits<long double>::max_exponent.


The float.h/cfloat header gives some maxima and minima, from which you could derive bit limits, but that seems a little awkward; what I would do personally is define the limits on mantissa, exponent, and base as constants, explicitly, for each platform you support, with a #pragma warning and comments to handle platforms you don't recognize.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜