Skip to main content

Utilities for MathJSON evaluation

Project description

MathJSON Solver

PyPI PyPI Downloads Python 3.7+

A reliable Python library for numerically evaluating mathematical expressions in MathJSON format. Perfect for applications that need to safely execute user-provided formulas, calculate dynamic equations, or process mathematical data.

What is MathJSON? MathJSON represents mathematical expressions as JSON arrays, like ["Add", 1, 2, 3] for 1+2+3. This format is safe, structured, and easy to generate programmatically.

Inspired by CortexJS Compute Engine though designed as an independent implementation focused on our specific use cases.

Table of Contents

Installation

pip install mathjson-solver

Requirements: Python 3.7+

Optional: numpy (only required for TrapezoidalIntegrate function)

Quick Start

from mathjson_solver import create_solver, MathJSONException

# Define variables and create solver
parameters = {"x": 2, "y": 3}
solver = create_solver(parameters)

# Evaluate expressions
basic_math = solver(["Add", "x", "y", 4])
print(basic_math)  # 9 (because 2+3+4=9)

# More complex expressions
result = solver(["Multiply", ["Add", "x", 1], ["Subtract", "y", 1]])
print(result)  # 6 (because (2+1) * (3-1) = 6)

# Handle errors gracefully
try:
    solver(["Divide", 1, 0])
except MathJSONException as e:
    print(f"Math error: {e}")
    # Math error: Problem in Divide. ['Divide', 1, 0]. division by zero

Supported Operations

The library supports a comprehensive set of mathematical operations:

  • Arithmetic: Add, Sum, Subtract, Multiply, Divide, Negate, Power, Square, Root, Sqrt, Abs, Round
  • Trigonometry: Sin, Cos, Tan, Arcsin, Arccos, Arctan
  • Logarithms: Log, Log2, Log10, Exp
  • Comparison: Equal, StrictEqual, NotEqual, Greater, GreaterEqual, Less, LessEqual
  • Logic & Sets: Any, All, Not, In, NotIn, ContainsAnyOf, ContainsAllOf, ContainsNoneOf
  • Statistics: Average, Max, Min, Median, Length
  • Arrays: Array creation and manipulation with Map function
  • Control Flow: If statements, Switch-Case, Constants definition
  • Type Conversion: Int, Float, Str, IsDefined
  • Date/Time: Strptime, Strftime, Today, Now, TimeDelta functions
  • Advanced: HasMatchingSublist, TrapezoidalIntegrate (requires numpy), Variable references
  • Constants: Pi

View complete documentation with examples →

Error Handling

MathJSON Solver raises MathJSONException for invalid expressions or mathematical errors:

from mathjson_solver import create_solver, MathJSONException

solver = create_solver({})

# Handle specific math errors
try:
    result = solver(["Sqrt", -1])  # Invalid: square root of negative
except MathJSONException as e:
    print(f"Cannot evaluate: {e}")

# Handle malformed expressions
try:
    result = solver(["UnknownFunction", 1, 2])
except MathJSONException as e:
    print(f"Unsupported operation: {e}")

Use Cases

  • Dynamic Formulas: Let users create custom calculations in web applications
  • Scientific Computing: Evaluate mathematical models with variable parameters
  • Business Logic: Process complex pricing rules or scoring algorithms
  • Data Processing: Apply mathematical transformations to datasets
  • Health Applications: Calculate medical scores, dosages, or risk assessments

Testing

Install development dependencies and run tests:

# Install pytest if not already installed
pip install pytest

# Run tests from project directory
pytest

# Run with coverage
pytest --cov=mathjson_solver

Community

Contributing

We welcome contributions! Please feel free to:

  • Report bugs or request features via GitHub Issues
  • Submit pull requests with improvements

License

View license information


Made with ❤️ by Longenesis

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mathjson_solver-1.15.0.tar.gz (16.1 kB view details)

Uploaded Source

Built Distribution

mathjson_solver-1.15.0-py3-none-any.whl (9.8 kB view details)

Uploaded Python 3

File details

Details for the file mathjson_solver-1.15.0.tar.gz.

File metadata

  • Download URL: mathjson_solver-1.15.0.tar.gz
  • Upload date:
  • Size: 16.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.3

File hashes

Hashes for mathjson_solver-1.15.0.tar.gz
Algorithm Hash digest
SHA256 88a0cf94d02a2b54850dd471aa9190cdff81ff3d39066a6903abeb17fcbfab7d
MD5 e86d7530ef84ce1122b08d8f9935f779
BLAKE2b-256 d3f1653524f5e832a22a02e677bf10f876c4bffe28a4d5fb50bc247d0807957a

See more details on using hashes here.

File details

Details for the file mathjson_solver-1.15.0-py3-none-any.whl.

File metadata

File hashes

Hashes for mathjson_solver-1.15.0-py3-none-any.whl
Algorithm Hash digest
SHA256 c27d52ce1b0631976ac3a7934379d0561ae3d13ba5a513ab3d7e32b1825e60e7
MD5 de7723c36e288eaf569438116361fd41
BLAKE2b-256 e943b7d1fb54913fcd889eb75cd30bdc82817c9d1dffe8af0758e71b40a0b9f6

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page