将字符串(strtold)转换为long double并从long double中减去>小量

时间:2016-03-26 19:54:13

标签: c++

不确定是否有人遇到此问题并且可以帮助找到解决方案。

基本上我将字符串转换为浮点值,然后从浮点值中减去以查看差异是否在+/- epsilon

问题是我为了获得长双倍的不同结果而做错了什么?

看起来两个长双打之间的区别是产生一个精确值的值,但不确定为什么......

代码的输出(mac和linux 64位都给出了相同的结果)

float        : a=145.568 d=145.568 epsilon=1.19209e-07 fabsf(a - d)=0 equal? equal
double       : b=145.568 e=145.568 epsilon=2.22045e-16 fabs(b - e)=0 equal? equal
long double  : c=145.568 f=145.568 epsilon=1.0842e-19 fabsl(c - f)=5.41234e-15 equal? not equal

这是代码

#include <limits>
#include <cstddef>
#include <iostream>
#include <sstream>
#include <cmath>

template <typename T>
bool cmp_equal(const T& lhs,
               const T& rhs,
               const T& epsilon = std::numeric_limits<T>::epsilon()) {
    const T diff = (lhs - rhs);
    return ((diff >= -epsilon) && (diff <= epsilon));
}

int main()
{
    float a = 145.5678f;
    double b = 145.5678;
    long double c = 145.5678l;

    std::stringstream s("145.5678 \r\t\n");
    char* end;

    float d = std::strtof(s.str().c_str(), &end);
    double e = std::strtod(s.str().c_str(), &end);
    long double f = std::strtold(s.str().c_str(), &end);

    std::cout << "float        : " << "a=" << a << " d=" << d
              << " epsilon=" << std::numeric_limits<float>::epsilon()
              << " fabsf(a - d)=" << std::fabsf(a - d)
              << " equal? " << (cmp_equal(a, d)?"equal":"not equal")
              << std::endl;

    std::cout << "double       : " << "b=" << b << " e=" << e
              << " epsilon=" << std::numeric_limits<double>::epsilon()
              << " fabs(b - e)=" << std::fabs(b - e)
              << " equal? " << (cmp_equal(b, e)?"equal":"not equal")
              << std::endl;

    std::cout << "long double  : " << "c=" << c << " f=" << f
              << " epsilon=" << std::numeric_limits<long double>::epsilon()
              << " fabsl(c - f)=" << std::fabsl(c - f)
              << " equal? " << (cmp_equal(c, f)?"equal":"not equal")
              << std::endl;
}

1 个答案:

答案 0 :(得分:2)

正如您所提到的,看起来长双重差异等于 float 精度(但它是双精度)。

文字浮点(如文字整数)可以是followed by a suffix,因此转换使用特定类型。默认情况下,类型为double。

你应该得到所需的精度:

float a = 145.5678f;
double b = 145.5678;
long double c = 145.5678l;

&#39; f&#39; (或&#39; F&#39;)floats和&#39; l&#39; (或{&lt; L&#39;)long double