|
| 1 | +/* |
| 2 | + Small math example, checking whether we properly integrate with c++ math |
| 3 | +
|
| 4 | + ref: |
| 5 | + - https://github.com/esp8266/Arduino/issues/5530 |
| 6 | + - https://github.com/espressif/arduino-esp32/pull/2738 |
| 7 | +
|
| 8 | + Released to public domain |
| 9 | +*/ |
| 10 | + |
| 11 | +#include <BSTest.h> |
| 12 | +#include <type_traits> |
| 13 | + |
| 14 | +BS_ENV_DECLARE(); |
| 15 | + |
| 16 | +void setup() |
| 17 | +{ |
| 18 | + Serial.begin(115200); |
| 19 | + BS_RUN(Serial); |
| 20 | +} |
| 21 | + |
| 22 | +bool pretest() |
| 23 | +{ |
| 24 | + return true; |
| 25 | +} |
| 26 | + |
| 27 | +#define TEST_MATH_IS_SAME(OP1, OP2) \ |
| 28 | + std::is_same<decltype(OP1), decltype(OP2)>::value |
| 29 | + |
| 30 | +TEST_CASE("std::abs and abs result is the same", "[arduino-math]") |
| 31 | +{ |
| 32 | + CHECK(TEST_MATH_IS_SAME(abs(-5), std::abs(-5))); |
| 33 | + CHECK(TEST_MATH_IS_SAME(abs(-25.0), std::abs(-25.0))); |
| 34 | + CHECK(TEST_MATH_IS_SAME(abs(10.0), std::abs(10.0))); |
| 35 | + CHECK(! TEST_MATH_IS_SAME(abs(10.0), std::abs(10))); |
| 36 | + CHECK(! TEST_MATH_IS_SAME(abs(-5), std::abs(10.0))); |
| 37 | +} |
| 38 | + |
| 39 | +TEST_CASE("abs works with ints", "[arduino-math]") |
| 40 | +{ |
| 41 | + int a = -3; |
| 42 | + int b = 3; |
| 43 | + CHECK(TEST_MATH_IS_SAME(abs(a), a)); |
| 44 | + CHECK(TEST_MATH_IS_SAME(abs(b), b)); |
| 45 | + CHECK(abs(a) == b); |
| 46 | + CHECK(abs(b) == b); |
| 47 | +} |
| 48 | + |
| 49 | +template <typename T> |
| 50 | +bool compare_floats(T a, T b) { |
| 51 | + static_assert(std::is_floating_point<T>::value, ""); |
| 52 | + return std::fabs(a - b) < std::numeric_limits<float>::epsilon(); |
| 53 | +} |
| 54 | + |
| 55 | +TEST_CASE("abs works with floats", "[arduino-math]") |
| 56 | +{ |
| 57 | + float a = -3.5; |
| 58 | + float b = 3.5; |
| 59 | + CHECK(TEST_MATH_IS_SAME(abs(a), a)); |
| 60 | + CHECK(TEST_MATH_IS_SAME(abs(b), b)); |
| 61 | + CHECK(compare_floats(abs(a), b)); |
| 62 | + CHECK(compare_floats(abs(b), b)); |
| 63 | +} |
| 64 | + |
| 65 | +TEST_CASE("round works with ints", "[arduino-math]") |
| 66 | +{ |
| 67 | + int a = 5; |
| 68 | + int b = 10; |
| 69 | + CHECK(TEST_MATH_IS_SAME(round(a), std::round(a))); |
| 70 | + CHECK(TEST_MATH_IS_SAME(round(b), std::round(b))); |
| 71 | + CHECK(compare_floats(round(a), std::round(a))); |
| 72 | + CHECK(compare_floats(round(b), std::round(b))); |
| 73 | +} |
| 74 | + |
| 75 | +TEST_CASE("round works with floats", "[arduino-math]") |
| 76 | +{ |
| 77 | + float a = 2.9; |
| 78 | + float b = 3.0; |
| 79 | + CHECK(TEST_MATH_IS_SAME(round(a), a)); |
| 80 | + CHECK(TEST_MATH_IS_SAME(round(b), b)); |
| 81 | + CHECK(compare_floats(round(a), b)); |
| 82 | + CHECK(compare_floats(round(b), b)); |
| 83 | +} |
| 84 | + |
| 85 | +void loop(){} |
| 86 | + |
0 commit comments