Skip to content

Commit

Permalink
Merge pull request #92 from saxbophone/josh/90-from-float-leading-zero
Browse files Browse the repository at this point in the history
Bugfix: leading zero error when creating Nat from float
  • Loading branch information
saxbophone authored May 25, 2022
2 parents 980542c + 292b2d1 commit db52e4b
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 3 deletions.
4 changes: 2 additions & 2 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# begin basic metadata
# minimum CMake version required for C++20 support, among other things
cmake_minimum_required(VERSION 3.15)
# minimum CMake version required for C++20 support and precompiled headers
cmake_minimum_required(VERSION 3.16)

# detect if Arby is being used as a sub-project of another CMake project
if(NOT DEFINED PROJECT_NAME)
Expand Down
2 changes: 1 addition & 1 deletion arby/include/arby/Nat.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ namespace com::saxbophone::arby {
throw std::domain_error("Nat cannot be Infinite or NaN");
}
Nat output;
while (value > 0) {
while (value > 1) { // value < 1 is zero which we store implicitly as empty array
StorageType digit = (StorageType)std::fmod(value, Nat::BASE);
output._digits.push_front(digit);
value /= Nat::BASE;
Expand Down
1 change: 1 addition & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ target_link_libraries(
arby
Catch2::Catch2 # unit testing framework
)
target_precompile_headers(tests PRIVATE <arby/Nat.hpp>)

enable_testing()

Expand Down
12 changes: 12 additions & 0 deletions tests/casting.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,17 @@ TEST_CASE("arby::Nat::from_float() with non-finite value throws std::domain_erro
}
}

TEST_CASE("arby::Nat::from_float() with value between 0 and 1") {
// NOTE: top range is the last float value > 1
long double zero_ish = GENERATE(take(1000, random(0.0L, std::nextafter(1.0L, 0.0L))));
CAPTURE(zero_ish);

arby::Nat object = arby::Nat::from_float(zero_ish);

// value should be correct
CHECK((long double)object == Approx(std::trunc(zero_ish)));
}

TEST_CASE("arby::Nat::from_float() with positive value") {
auto power = GENERATE(0.125, 0.25, 0.5, 1, 2, 4, 8);
auto value = GENERATE_COPY(
Expand All @@ -66,6 +77,7 @@ TEST_CASE("arby::Nat::from_float() with positive value") {
)
)
);
CAPTURE(power, value);

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

Expand Down

0 comments on commit db52e4b

Please sign in to comment.