kit

kit
git clone https://git.ryansepassi.com/git/kit.git
Log | Files | Refs | README

use_tinyexpr.c (936B)


      1 /* use_tinyexpr.c — exercise tinyexpr expression compilation + variable binding.
      2  * Deterministic output (fixed expressions, %.6g formatting). */
      3 #include "tinyexpr.h"
      4 #include <stdio.h>
      5 
      6 int main(void) {
      7   /* Pure constant-folding interpretations. */
      8   const char *exprs[] = {
      9       "sqrt(3^2 + 4^2)",
     10       "2 * (3 + 4) - 5",
     11       "sin(0) + cos(0)",
     12       "max(2, min(9, 7))",
     13   };
     14   int err;
     15   for (int i = 0; i < 4; i++) {
     16     double r = te_interp(exprs[i], &err);
     17     printf("expr[%d]=%.6g err=%d\n", i, r, err);
     18   }
     19 
     20   /* Compile-once, evaluate-many with bound variables. */
     21   double x = 0, y = 0;
     22   te_variable vars[] = {{"x", &x, 0, 0}, {"y", &y, 0, 0}};
     23   te_expr *e = te_compile("x*x + y*y", vars, 2, &err);
     24   if (!e) {
     25     printf("compile-fail at %d\n", err);
     26     return 1;
     27   }
     28   for (int i = 1; i <= 3; i++) {
     29     x = i;
     30     y = i + 1;
     31     printf("f(%d,%d)=%.6g\n", i, i + 1, te_eval(e));
     32   }
     33   te_free(e);
     34   return 0;
     35 }