{"id":36964824,"url":"https://github.com/xirf/latex_math_evaluator","last_synced_at":"2026-01-13T19:46:21.801Z","repository":{"id":328142819,"uuid":"1110463886","full_name":"xirf/latex_math_evaluator","owner":"xirf","description":"A Flutter/Dart library for parsing and evaluating mathematical expressions written in LaTeX format.","archived":false,"fork":false,"pushed_at":"2025-12-31T08:16:04.000Z","size":1078,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-12-31T22:59:08.679Z","etag":null,"topics":["dart","expression-evaluator","expression-parser","latex","math"],"latest_commit_sha":null,"homepage":"https://pub.dev/packages/latex_math_evaluator","language":"Dart","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/xirf.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":"ROADMAP.md","authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-12-05T08:26:49.000Z","updated_at":"2025-12-30T10:44:49.000Z","dependencies_parsed_at":"2025-12-29T07:00:31.361Z","dependency_job_id":null,"html_url":"https://github.com/xirf/latex_math_evaluator","commit_stats":null,"previous_names":["xirf/latex_math_evaluator"],"tags_count":10,"template":false,"template_full_name":null,"purl":"pkg:github/xirf/latex_math_evaluator","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xirf%2Flatex_math_evaluator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xirf%2Flatex_math_evaluator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xirf%2Flatex_math_evaluator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xirf%2Flatex_math_evaluator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/xirf","download_url":"https://codeload.github.com/xirf/latex_math_evaluator/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xirf%2Flatex_math_evaluator/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28397826,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-13T14:36:09.778Z","status":"ssl_error","status_checked_at":"2026-01-13T14:35:19.697Z","response_time":56,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dart","expression-evaluator","expression-parser","latex","math"],"created_at":"2026-01-13T19:46:20.807Z","updated_at":"2026-01-13T19:46:21.785Z","avatar_url":"https://github.com/xirf.png","language":"Dart","funding_links":[],"categories":[],"sub_categories":[],"readme":"# LaTeX Math Evaluator 🧮\n\n[![Tests](https://img.shields.io/badge/tests-1197%20passed-brightgreen)](https://github.com/xirf/latex_math_evaluator)\n[![Dart](https://img.shields.io/badge/dart-%3E%3D3.0.0-blue)](https://github.com/xirf/latex_math_evaluator)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)\n[![Pub Version](https://img.shields.io/pub/v/latex_math_evaluator)](https://pub.dev/packages/latex_math_evaluator)\n\nA Flutter/Dart library designed for parsing and evaluating complex mathematical expressions in native LaTeX format. Built for researchers, engineers, and educators who need symbolic accuracy and broad notation support.\n\n\u003e [!WARNING] This package is now texpr.\n\u003e\n\u003e We have renamed the package to reflect its expanded capabilities. While latex_math_evaluator focused on calculating results, texpr (TeX Expressions) provides a broader engine for parsing, analyzing, and evaluating mathematical LaTeX.\n\u003e\n\u003e Version 0.2.0+ is strictly available on texpr [(pub.dev/texpr)](https://pub.dev/packages/texpr) and GitHub [(github.com/xirf/texpr)](https://github.com/xirf/texpr).\n\u003e\n\u003e This package will receive no further updates.\n\n## ✨ Key Capabilities\n\n- 🎯 **Native LaTeX Parsing** – Evaluate expressions directly from academic papers without manual translation.\n- 🧮 **Symbolic Calculus** – Compute exact derivatives and simplify expressions using algebraic rules. Uses pattern-based simplification (not a full CAS).\n- 🔢 **Advanced Mathematics** – Support for summations, products, limits, integrals, and special functions.\n- 🏗️ **Linear Algebra** – Full suite of matrix and vector operations, including determinants and powers.\n- 🛡️ **Type-Safe Results** – Robust handling of Real, Complex, Matrix, and Vector types via Dart 3 sealed classes.\n- 🚩 **Domain Awareness** – Uses an Assumptions System (e.g., $x \u003e 0$) to ensure mathematically sound transformations.\n- 🔧 **Extensible Architecture** – Easily add custom LaTeX commands and evaluation logic.\n- 🧩 **Implicit/Explicit Logic** – Natural parsing of $2\\pi r$ or $\\sin 2x$—no need to type every \\*. easy to switch between implicit and explicit logic.\n- 🎲 **Equation Solving** – Solve linear and quadratic equations symbolically.\n- 📊 **Piecewise Functions** – Evaluate and differentiate piecewise expressions with conditions.\n\n---\n\n## 🚀 Quick Start\n\nAdd the dependency to your `pubspec.yaml`:\n\n```yaml\ndependencies:\n  latex_math_evaluator: ^0.2.0\n```\n\nor run this command:\n\n```bash\nflutter pub add latex_math_evaluator\n# or\ndart pub add latex_math_evaluator\n```\n\n### Basic Evaluation\n\n```dart\nimport 'package:latex_math_evaluator/latex_math_evaluator.dart';\n\nfinal evaluator = LatexMathEvaluator();\n\n// 1. Simple numeric result\nfinal result = evaluator.evaluateNumeric(r'\\frac{\\sqrt{16}}{2} + \\sin{\\pi}');\nprint(result); // 2.0\n\n// 2. Evaluation with variables\nfinal vars = {'x': 3.0, 'y': 4.0};\nfinal hypotenuse = evaluator.evaluateNumeric(r'\\sqrt{x^2 + y^2}', vars);\nprint(hypotenuse); // 5.0\n```\n\n---\n\n## 🛠️ Core Features\n\n### 1. Symbolic Calculus \u0026 Differentiation 📐\n\nUnlike libraries that use numeric approximations, `latex_math_evaluator` can compute exact symbolic derivatives.\n\n```dart\n// Differentiate an expression\nfinal derivative = evaluator.differentiate(r'x^3 + \\sin{x}', 'x');\n\n// Evaluate at x = 0\nprint(evaluator.evaluateParsed(derivative, {'x': 0})); // 1.0 (cos(0))\n\n// Works with piecewise functions too!\nfinal piecewise = evaluator.differentiate(r'|\\sin{x}|, -3 \u003c x \u003c 3', 'x');\nprint(evaluator.evaluateParsed(piecewise, {'x': 1})); // cos(1)\n```\n\n### 2. Complex Numbers \u0026 Multi-Dimensional Math 🏗️\n\nHandle matrices, vectors, and complex numbers as first-class citizens.\n\n```dart\n// Euler's identity: e^(iπ) = -1\nfinal euler = evaluator.evaluate(r'e^{i*\\pi}');\nprint(euler.asComplex().real); // -1.0\n\n// Complex trigonometry: sin(1+2i)\nfinal sinComplex = evaluator.evaluate(r'\\sin(1 + 2*i)');\nprint(sinComplex.asComplex()); // Complex(3.1658, 1.9596)\n\n// Square root of negative numbers returns complex\nfinal sqrtNeg = evaluator.evaluate(r'\\sqrt{-4}');\nprint(sqrtNeg.asComplex()); // Complex(0, 2) = 2i\n\n// Matrix multiplication and power\nfinal matrixResult = evaluator.evaluate(r'''\n  \\begin{pmatrix} 0.8 \u0026 0.1 \\\\ 0.2 \u0026 0.7 \\end{pmatrix} ^ 2\n''');\n```\n\n### 3. High-Fidelity Diagnostics 🔍\n\nGet precise feedback when parsing fails, with did-you-mean suggestions and common mistake detection.\n\n```dart\nfinal validation = evaluator.validate(r'\\frac{1{2}');\nif (!validation.isValid) {\n  print('Error at ${validation.position}: ${validation.errorMessage}');\n  print('Suggestion: ${validation.suggestion}');\n\n  // New: Check for multiple errors\n  if (validation.subErrors.isNotEmpty) {\n    print('Additional errors: ${validation.subErrors.length}');\n  }\n}\n\n// Did-you-mean for unknown functions\ntry {\n  evaluator.evaluate(r'\\sinn{x}');\n} on EvaluatorException catch (e) {\n  print(e.suggestion); // \"Did you mean 'sin'?\"\n}\n```\n\n### 4. Performance \u0026 Caching ⚡\n\nFor applications requiring frequent evaluations (like graphing or simulations), use the built-in multi-layer LRU cache.\n\n```dart\n// Configure caching for high-frequency evaluation\nfinal fastEvaluator = LatexMathEvaluator(\n  cacheConfig: CacheConfig.highPerformance,\n);\n\n// Or parse once and reuse for hot loops (fastest method)\nfinal ast = fastEvaluator.parse(r'\\sin(x) + \\cos(x)');\nfor (var x = 0.0; x \u003c 100; x += 0.01) {\n  fastEvaluator.evaluateParsed(ast, {'x': x}); // ~0.19 µs/op\n}\n```\n\n#### Performance Modes\n\n| Mode                    |        Time | What it Measures                         |\n| :---------------------- | ----------: | :--------------------------------------- |\n| `evaluate()` (no cache) |       ~5 µs | Parse + evaluate every call              |\n| `evaluate()` (cached)   |     ~2.5 µs | L1 cache hit + evaluate                  |\n| **`evaluateParsed()`**  | **~0.2 µs** | Pure evaluation, no parse/cache overhead |\n\n\u003e [!TIP]\n\u003e For hot loops, use **`evaluateParsed()`** with a pre-parsed AST—it's 20x+ faster than `evaluate()`.\n\n**Cost-aware caching:** L2 evaluation cache is only consulted for computationally expensive operations (integrals, summations, products, limits, large matrices). For cheap expressions, the overhead of cache key creation would exceed evaluation time.\n\n#### Performance Context\n\n\u003e [!IMPORTANT]\n\u003e **Comparison Limitations:** This performance comparison compares different tools with different purposes:\n\u003e - **Dart**: Numeric evaluation of LaTeX syntax\n\u003e - **Python**: Symbolic computation with SymPy (capable of algebra, not just evaluation)\n\u003e - **JavaScript**: General-purpose math with mathjs (supports units, matrices, complex types)\n\u003e\n\u003e Direct speed comparisons should be interpreted with these architectural differences in mind.\n\nPerformance References run using language-native tools:\n- **Dart**: `benchmark_harness` (JIT)\n- **Dart WASM**: `dart compile wasm` (WasmGC, AOT)\n- **Python**: `pytest-benchmark`\n- **JavaScript**: `benchmark.js`\n\nResults from MacBook Air M1 8GB, macOS 15.7.2:\n\n| Expression Category             | Dart (µs) | Dart WASM (µs) | Python (SymPy)* (µs) | JS (mathjs) (µs) |\n| :------------------------------ | --------: | -------------: | -------------------: | ---------------: |\n| **Basic: Trigonometry**         |      1.10 |           3.38 |                34.23 |             5.28 |\n| **Basic: Power \u0026 Sqrt**         |      1.05 |           2.80 |                32.93 |             6.09 |\n| **Polynomial**                  |      1.19 |           3.10 |                 6.45 |             5.59 |\n| **Academic: Normal PDF**        |      4.76 |          10.77 |               211.05 |            19.46 |\n| **Calculus: Definite Integral** |  1,415.93 |            N/A |             1,811.45 |              N/A |\n\n\u003e [!NOTE]\n\u003e * **Input formats:** Dart parses LaTeX (`\\sin{x}`), Python uses SymPy syntax (`sin(x)`), JavaScript uses text syntax (`sin(x)`)\n\u003e * **Python (SymPy):** Performs symbolic computation, maintaining exact forms (e.g., $\\sqrt{2}$ vs 1.414...), which adds overhead\n\u003e * **WASM:** ~2-4x overhead vs native Dart is expected due to JIT vs AOT differences and browser sandbox.\n\u003e * **Scope:** Dart benchmarks include parsing LaTeX string + numeric evaluation.\n\u003e\n\n#### Dart Library Comparison\n\nComparing `latex_math_evaluator` (LaTeX syntax) vs `math_expressions` (text syntax):\n\n| Expression       | Parse+Eval LaTeX (µs) | Parse+Eval Text (µs) | Eval-Only LaTeX (µs) | Eval-Only Text (µs) |\n| :--------------- | --------------------: | -------------------: | -------------------: | ------------------: |\n| Arithmetic       |                  0.73 |                 0.95 |                 0.13 |                0.05 |\n| Trigonometry     |                  1.18 |                12.74 |                 0.21 |                0.07 |\n| Power \u0026 Sqrt     |                  1.09 |                10.20 |                 0.23 |                0.08 |\n| Polynomial       |                  1.19 |                 6.45 |                 0.33 |                0.12 |\n| Nested Functions |                  1.03 |                11.20 |                 0.15 |                0.06 |\n\n\u003e [!NOTE]\n\u003e **Observations:**\n\u003e - Parse+Eval (one-shot): `latex_math_evaluator` is faster due to optimized tokenizer/parser\n\u003e - Eval-Only (hot loop): `math_expressions` is faster due to simpler AST structure\n\u003e - For hot loops, use `evaluateParsed()` regardless of library choice\n\nSee `benchmark/comparison/README.md` for how to run these benchmarks yourself.\n\n### 5. Export \u0026 Interoperability\n\nExport parsed expressions to other formats for debugging, web display, or advanced analysis.\n\n```dart\nfinal expr = evaluator.parse(r'\\int x^2 dx');\n\n// 1. JSON (Stable) - For debugging and tooling\nprint(expr.toJson());\n\n// 2. SymPy (Experimental) - For Python interoperability\nprint(expr.toSymPy()); // integrate(x**2, x)\n\n// 3. MathML (Experimental) - For web display\nprint(expr.toMathML()); // \u003cmath\u003e\u003cmo\u003e∫\u003c/mo\u003e...\u003c/math\u003e\n```\n\n[**Learn more about text export**](doc/features/export.md)\n\n---\n\n## 📚 Real-World Examples\n\n| Domain          | LaTeX Expression                                                        | Capability                        |\n| :-------------- | :---------------------------------------------------------------------- | :-------------------------------- |\n| **Physics**     | `\\frac{1}{\\sqrt{1 - \\frac{v^2}{c^2}}}`                                  | Lorentz Factor (Variable Binding) |\n| **Engineering** | `\\frac{P L^3}{48 E I} ( 3 \\frac{x}{L} - 4 ( \\frac{x}{L} )^3 )`          | Beam Deflection (Algebraic)       |\n| **Quantum**     | `\\int_{0}^{L} \\psi^*(x) \\hat{H} \\psi(x) dx`                             | Expectation Values (Integration)  |\n| **Statistics**  | `\\frac{1}{\\sigma \\sqrt{2\\pi}} e^{-\\frac{1}{2}(\\frac{x-\\mu}{\\sigma})^2}` | Normal Distribution (Constants)   |\n\n---\n\n## 📖 Documentation \u0026 Resources\n\n- [**Getting Started**](doc/getting_started.md)\n- [**LaTeX Commands Reference**](doc/latex_commands.md) – Complete list of supported LaTeX notation.\n- [**Symbolic Algebra**](doc/symbolic_algebra.md) – Simplification and expansion rules.\n- [**Piecewise Functions**](doc/features/piecewise.md) – Conditional expressions and domain-restricted functions.\n- [**Function Reference**](doc/functions/README.md) – Mathematical functions and their behavior.\n- [**Extending the Library**](doc/extensions.md) – How to add custom functions.\n- [**Export Features**](doc/features/export.md) – Export to JSON, SymPy, and MathML.\n- [**Performance Guide**](doc/performance/caching.md) – Tuning the cache and memoization.\n\n## 🤝 Contributing\n\nWe welcome contributions of all kinds! Whether it's reporting a bug, improving documentation, or adding a new mathematical feature.\n\n1. Fork the repository.\n2. Create your feature branch.\n3. Commit your changes.\n4. Push to the branch and open a Pull Request.\n\n## 📄 License\n\nThis project is licensed under the **MIT License**. See the [LICENSE](LICENSE) file for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fxirf%2Flatex_math_evaluator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fxirf%2Flatex_math_evaluator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fxirf%2Flatex_math_evaluator/lists"}