Skip to content

Commit db52e4b

Browse files
authored
Merge pull request #92 from saxbophone/josh/90-from-float-leading-zero
Bugfix: leading zero error when creating Nat from float
2 parents 980542c + 292b2d1 commit db52e4b

File tree

4 files changed

+16
-3
lines changed

4 files changed

+16
-3
lines changed

CMakeLists.txt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# begin basic metadata
2-
# minimum CMake version required for C++20 support, among other things
3-
cmake_minimum_required(VERSION 3.15)
2+
# minimum CMake version required for C++20 support and precompiled headers
3+
cmake_minimum_required(VERSION 3.16)
44

55
# detect if Arby is being used as a sub-project of another CMake project
66
if(NOT DEFINED PROJECT_NAME)

arby/include/arby/Nat.hpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,7 @@ namespace com::saxbophone::arby {
198198
throw std::domain_error("Nat cannot be Infinite or NaN");
199199
}
200200
Nat output;
201-
while (value > 0) {
201+
while (value > 1) { // value < 1 is zero which we store implicitly as empty array
202202
StorageType digit = (StorageType)std::fmod(value, Nat::BASE);
203203
output._digits.push_front(digit);
204204
value /= Nat::BASE;

tests/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ target_link_libraries(
2626
arby
2727
Catch2::Catch2 # unit testing framework
2828
)
29+
target_precompile_headers(tests PRIVATE <arby/Nat.hpp>)
2930

3031
enable_testing()
3132

tests/casting.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,17 @@ TEST_CASE("arby::Nat::from_float() with non-finite value throws std::domain_erro
5656
}
5757
}
5858

59+
TEST_CASE("arby::Nat::from_float() with value between 0 and 1") {
60+
// NOTE: top range is the last float value > 1
61+
long double zero_ish = GENERATE(take(1000, random(0.0L, std::nextafter(1.0L, 0.0L))));
62+
CAPTURE(zero_ish);
63+
64+
arby::Nat object = arby::Nat::from_float(zero_ish);
65+
66+
// value should be correct
67+
CHECK((long double)object == Approx(std::trunc(zero_ish)));
68+
}
69+
5970
TEST_CASE("arby::Nat::from_float() with positive value") {
6071
auto power = GENERATE(0.125, 0.25, 0.5, 1, 2, 4, 8);
6172
auto value = GENERATE_COPY(
@@ -66,6 +77,7 @@ TEST_CASE("arby::Nat::from_float() with positive value") {
6677
)
6778
)
6879
);
80+
CAPTURE(power, value);
6981

7082
arby::Nat object = arby::Nat::from_float(value);
7183

0 commit comments

Comments
 (0)