exprtk_simple_example_10.cpp 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. **************************************************************
  3. * C++ Mathematical Expression Toolkit Library *
  4. * *
  5. * Simple Example 10 *
  6. * Author: Arash Partow (1999-2020) *
  7. * URL: http://www.partow.net/programming/exprtk/index.html *
  8. * *
  9. * Copyright notice: *
  10. * Free use of the Mathematical Expression Toolkit Library is *
  11. * permitted under the guidelines and in accordance with the *
  12. * most current version of the MIT License. *
  13. * http://www.opensource.org/licenses/MIT *
  14. * *
  15. **************************************************************
  16. */
  17. #include <cmath>
  18. #include <cstdio>
  19. #include <string>
  20. #include "exprtk.hpp"
  21. template <typename T>
  22. void newton_sqrt()
  23. {
  24. typedef exprtk::symbol_table<T> symbol_table_t;
  25. typedef exprtk::expression<T> expression_t;
  26. typedef exprtk::parser<T> parser_t;
  27. typedef exprtk::function_compositor<T> compositor_t;
  28. typedef typename compositor_t::function function_t;
  29. T x = T(0);
  30. symbol_table_t symbol_table;
  31. symbol_table.add_constants();
  32. symbol_table.add_variable("x",x);
  33. compositor_t compositor(symbol_table);
  34. compositor
  35. .add(
  36. function_t( // define function: newton_sqrt(x)
  37. "newton_sqrt",
  38. " switch "
  39. " { "
  40. " case x < 0 : null; "
  41. " case x == 0 : 0; "
  42. " case x == 1 : 1; "
  43. " default: "
  44. " ~{ "
  45. " var z := 100; "
  46. " var sqrt_x := x / 2; "
  47. " repeat "
  48. " if (equal(sqrt_x^2, x)) "
  49. " break[sqrt_x]; "
  50. " else "
  51. " sqrt_x := (1 / 2) * (sqrt_x + (x / sqrt_x)); "
  52. " until ((z -= 1) <= 0); "
  53. " }; "
  54. " } ",
  55. "x"));
  56. const std::string expression_str = "newton_sqrt(x)";
  57. expression_t expression;
  58. expression.register_symbol_table(symbol_table);
  59. parser_t parser;
  60. parser.compile(expression_str,expression);
  61. for (std::size_t i = 0; i < 100; ++i)
  62. {
  63. x = static_cast<T>(i);
  64. const T result = expression.value();
  65. printf("sqrt(%03d) - Result: %15.13f\tReal: %15.13f\n",
  66. static_cast<unsigned int>(i),
  67. result,
  68. std::sqrt(x));
  69. }
  70. }
  71. int main()
  72. {
  73. newton_sqrt<double>();
  74. return 0;
  75. }