Floating-point arithmetic and boost.multiprecision

In C ++, float 4 bytes, double 8 bytes, IEEE 754 floating-point standard are used; inside are based on the binary expression of real numbers, some real number can be precisely expressed, such as 0.2, but some can not , such as 0.3. On this point, we have recently published a special article describes this: floating-point operations are not allowed Why? Someone built a website for .30000000000000004

In order to be able to express more accurate floating-point number, you have to find a direction to the library. gmp, mpfr can express infinite precision, but only gcc compiler bar, boost at the start of version 1.56 provides support for boost.multiprecision more accurate numerical representation, license liberal than other libraries, but in the direction of computing efficiency inferior to gmp, mpfr.

Bbp accurate results such as the use of pi formula, as follows:

// Author: [email protected]

#include <iostream>
#include <iomanip>
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/cpp_bin_float.hpp>

// 通过 BBP 公式计算 PI
template <class Type>
Type calc_pi_bbp(int n)
{
    Type pi = 0;

    std::streamsize prevsize = std::cout.precision(50);
    for (int k = 0; k < n; ++k)
    {
        Type it = static_cast<Type>(1) / pow(16, k)
            * (static_cast<Type>(4) / (8 * k + 1) 
                - static_cast<Type>(2) / (8 * k + 4)
                - static_cast<Type>(1) / (8 * k + 5)
                - static_cast<Type>(1) / (8 * k + 6));
        pi += it;
        std::cout << std::left << std::setw(8) << k << pi << std::endl;
    }
    std::cout.precision(prevsize);
    return pi;
}

int main(int argc, char* argv[])
{
    std::cout << "Use double: " << std::endl;
    calc_pi_bbp<double>(20);
    std::cout << std::endl;

    std::cout << "Use boost multiprecision: " << std::endl;
    calc_pi_bbp<boost::multiprecision::cpp_bin_float_100>(30);
    return 0;
}

20 to double the value calculated as follows:
image

30 and then to calculate boost.multiprecision results are as follows:
image

When using double calculated apparent, will not, after every 10th some change (less than 2.2204460492503131e-016 (i.e. DBL_EPSILON) by adding the value of 1.0 is still 1.0), and has also been boost.multiprecision change, and the results may be Window operating system stored in the calculator pi value of the same (but more numbers after the decimal point, about the accuracy of these no compare).

Guess you like

Origin www.cnblogs.com/bitbybit3d/p/11995816.html