example84_contexts.run-fail.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // (C) Copyright Raffi Enficiaud 2019.
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // (See accompanying file LICENSE_1_0.txt or copy at
  4. // http://www.boost.org/LICENSE_1_0.txt)
  5. // See http://www.boost.org/libs/test for the library home page.
  6. //[example_code
  7. #define BOOST_TEST_MODULE example84
  8. #include <boost/test/included/unit_test.hpp>
  9. #include <random>
  10. #include <cmath>
  11. // this function does not compute properly the polynomial root estimation
  12. // in the case of a double root.
  13. template <class random_generator_t>
  14. std::pair<double, double> estimate_polynomial_roots(
  15. random_generator_t& gen,
  16. std::function<double(double)> polynomial) {
  17. using namespace std;
  18. std::uniform_real_distribution<> dis(-10, 10);
  19. double x1 = dis(gen);
  20. double x2 = dis(gen);
  21. double fx1 = polynomial(x1);
  22. double fx2 = polynomial(x2);
  23. BOOST_TEST_INFO_SCOPE("sample1 = " << x1);
  24. BOOST_TEST_INFO_SCOPE("sample2 = " << x2);
  25. // from Vieta formula
  26. double minus_b = x2 + x1 - (fx2 - fx1) / (x2 - x1);
  27. double c = (x1 * fx2 - x2 * fx1 + x2 * x1 * x1 - x1 * x2 * x2) / (x1 - x2);
  28. BOOST_TEST(minus_b * minus_b >= 4*c);
  29. return std::make_pair(
  30. (minus_b - sqrt(minus_b * minus_b - 4 * c)) / 2,
  31. (minus_b + sqrt(minus_b * minus_b - 4 * c)) / 2);
  32. }
  33. BOOST_AUTO_TEST_CASE(quadratic_estimation)
  34. {
  35. std::random_device rd;
  36. unsigned int seed = rd();
  37. std::mt19937 gen(seed);
  38. std::uniform_int_distribution<> dis(-10, 10);
  39. BOOST_TEST_MESSAGE("Seed = " << seed);
  40. for(int i = 0; i < 50; i++) {
  41. BOOST_TEST_INFO_SCOPE("trial " << i+1);
  42. int root1 = dis(gen);
  43. int root2 = dis(gen);
  44. if(root1 > root2) {
  45. std::swap(root1, root2);
  46. }
  47. BOOST_TEST_INFO_SCOPE("root1 = " << root1);
  48. BOOST_TEST_INFO_SCOPE("root2 = " << root2);
  49. std::pair<double, double> estimated = estimate_polynomial_roots(
  50. gen,
  51. [root1, root2](double x) -> double { return (x - root1) * (x - root2); });
  52. BOOST_TEST(estimated.first == double(root1), 10. % boost::test_tools::tolerance());
  53. BOOST_TEST(estimated.second == double(root2), 10. % boost::test_tools::tolerance());
  54. }
  55. }
  56. //]
  57. BOOST_AUTO_TEST_CASE(making_it_fail)
  58. {
  59. // cheating a bit ... but shhhh, do not show in the docs ...
  60. BOOST_FAIL("Making it fail always on all platforms");
  61. }