Skip to content

Commit 097bf7e

Browse files
committed
Add simple addition comparison example
1 parent fefc51c commit 097bf7e

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

examples/addition.cpp

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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 {0}; 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+
}

test/Jamfile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,7 @@ run ../examples/numerical_parsing.cpp ;
212212
run ../examples/first_example.cpp ;
213213
run ../examples/basic_arithmetic.cpp ;
214214
run ../examples/to_from_file.cpp ;
215+
run ../examples/addition.cpp ;
215216

216217
# Test compilation of separate headers
217218
compile compile_tests/bid_conversion.cpp ;

0 commit comments

Comments
 (0)