|
| 1 | +// Copyright 2025 Matt Borland |
| 2 | +// Distributed under the Boost Software License, Version 1.0. |
| 3 | +// https://www.boost.org/LICENSE_1_0.txt |
| 4 | +// |
| 5 | +// This example shows the difference in the results of repeated addition |
| 6 | + |
| 7 | +#include <boost/decimal/decimal32_t.hpp> // For type decimal32_t and std::numeric_limits support |
| 8 | +#include <boost/decimal/iostream.hpp> // For decimal support to <iostream> |
| 9 | +#include <iostream> |
| 10 | +#include <limits> |
| 11 | + |
| 12 | +int main() |
| 13 | +{ |
| 14 | + using boost::decimal::decimal32_t; |
| 15 | + |
| 16 | + constexpr decimal32_t decimal_one_tenth {"0.1"}; // Construct constant 0.1 from string for lossless conversion |
| 17 | + constexpr float float_one_tenth {0.1f}; // Construct floating point constant from literal |
| 18 | + |
| 19 | + decimal32_t decimal_value {}; // Construct decimal 0 to start from |
| 20 | + float float_value {}; // Construct float 0 to start from |
| 21 | + |
| 22 | + // We now add 0.1 1000 times which should result exactly in 100 |
| 23 | + // What we actually find is that the decimal32_t value does result in exactly 100 |
| 24 | + // With type float the result is not 100 due to inexact representation |
| 25 | + for (int i {}; i < 1000; ++i) |
| 26 | + { |
| 27 | + decimal_value += decimal_one_tenth; // Decimal types support compound arithmetic as expected |
| 28 | + float_value += float_one_tenth; |
| 29 | + } |
| 30 | + |
| 31 | + // Each of the decimal types has complete support for std::numeric_limits, |
| 32 | + // which we leverage here with set precision to show any fractional part of the number (if applicable) |
| 33 | + std::cout << std::setprecision(std::numeric_limits<decimal32_t>::digits10) |
| 34 | + << "Decimal Result: " << decimal_value << "\n" |
| 35 | + << std::setprecision(std::numeric_limits<float>::digits10) |
| 36 | + << " Float Result: " << float_value << std::endl; |
| 37 | +} |
0 commit comments