libcruft-util/test/polynomial.cpp

60 lines
1.7 KiB
C++
Raw Normal View History

2015-01-21 23:40:45 +11:00
#include "polynomial.hpp"
#include "float.hpp"
#include "debug.hpp"
2015-01-29 15:45:30 +11:00
#include "tap.hpp"
#include "types.hpp"
2015-01-21 23:40:45 +11:00
#include <algorithm>
#include <cmath>
#include <limits>
int
main (int, char**)
{
auto nan = std::numeric_limits<float>::quiet_NaN ();
struct {
2015-01-29 15:45:30 +11:00
const char *name;
2015-01-21 23:40:45 +11:00
std::array<float,4> coeffs;
std::array<float,3> solutions;
} CUBICS [] = {
2015-01-29 15:45:30 +11:00
{ "linear", { 0, 0, -8, 7 }, { 7.f / 8, nan, nan } },
{ "quadratic", { 0, 4, -8, 2 }, { 0.2928932188134524f, 1.7071067811865475f, nan } },
{ "unit cubic", { 1, 0, 0, 0 }, { 0, nan, nan } },
{ "simple cubic", { 1, 0, 2, 0 }, { 0, nan, nan } },
{ "twos cubic", { -2, 2, -2, 2 }, { 1, nan, nan } },
{ "a & d cubic", { 1, 0, 0, 2 }, { -std::cbrt(2.f), nan, nan } },
{ "cubic 1 real 1", { 2, -3, 8, -2 }, { 0.2728376017309678f, nan, nan } },
{ "cubic 1 real 2", { 1, 4, -8, 7 }, { -5.638871145892407f, nan, nan } },
{ "cubic all real", { 1, 3, -6, -8 }, { -4, -1, 2, } },
{ "cubic 1 uniq", { 1, -3, 3, -1 }, { 1, nan, nan } },
2015-01-21 23:40:45 +11:00
};
2015-04-13 16:43:49 +10:00
util::TAP::logger test;
2015-01-29 15:45:30 +11:00
2015-01-21 23:40:45 +11:00
for (auto &i: CUBICS) {
std::array<float,3> s = util::polynomial::solve<3> (i.coeffs);
2015-01-21 23:40:45 +11:00
std::sort (s.begin (), s.end ());
2015-01-29 15:45:30 +11:00
bool ok = true;
2015-01-21 23:40:45 +11:00
for (size_t j = 0; j < 3; ++j) {
2015-01-29 15:45:30 +11:00
if (std::isnan (i.solutions[j])) {
if (!std::isnan (s[j]))
ok = false;
continue;
}
2015-01-21 23:40:45 +11:00
2015-01-29 15:45:30 +11:00
if (!almost_equal (i.solutions[j], s[j]))
ok = false;
2015-01-21 23:40:45 +11:00
}
2015-01-29 15:45:30 +11:00
2015-04-13 16:43:49 +10:00
test.expect (ok, i.name);
2015-01-21 23:40:45 +11:00
}
2015-01-29 15:45:30 +11:00
return 0;
2015-01-21 23:40:45 +11:00
}