☑ Table of Contents
☑ Introduction
The ULTRAMEGA Expression Parser is a powerful, comprehensive mathematical expression evaluation library that supports over 440 functions, constants, and units. It's designed for scientific computing, engineering calculations, and complex mathematical operations.
Key Features
- 310+ Mathematical Functions: From basic arithmetic to advanced special functions
- 50+ Physics Functions: Classical mechanics, quantum mechanics, electromagnetics
- 35+ Electronics Functions: Circuit analysis, signal processing, power calculations
- 45+ Logic & Boolean Functions: Digital logic, fuzzy logic, set operations
- 47 Physical Constants: Universal constants, atomic properties, mathematical constants
- 80+ Unit System: Comprehensive unit conversion and dimensional analysis
- Advanced Syntax: Support for complex expressions with proper operator precedence
Who Should Use This Manual?
- Software developers integrating mathematical computations
- Engineers performing complex calculations
- Scientists analyzing data and modeling phenomena
- Educators creating mathematical tools and simulations
- Students learning scientific computing
💡 Quick Start Tip
If you're new to the parser, start with the "Getting Started" section and work through the basic examples before diving into advanced features.
☑ Getting Started
Let's start with simple expressions to understand the basic concepts:
Basic Arithmetic:
2 + 3 * 4
Result: 14
Using Functions:
sin(pi/4)
Result: 0.7071067811865476
Using Constants:
e^2
Result: 7.38905609893065
Integration in C#
using ULTRAMEGA.ExpressionParser;
// Create an evaluator instance
var evaluator = new ExpressionEvaluator();
// Simple evaluation
double result = evaluator.Evaluate("2 + 3 * 4");
Console.WriteLine($"Result: {result}"); // Output: 14
// Using variables
evaluator.SetVariable("x", 5);
evaluator.SetVariable("y", 3);
double result2 = evaluator.Evaluate("x^2 + y^2");
Console.WriteLine($"Result: {result2}"); // Output: 34
Key Concepts
- Expressions: Mathematical formulas written as text strings
- Functions: Pre-built operations like sin(), sqrt(), log()
- Constants: Pre-defined values like pi, e, c
- Variables: User-defined values that can be referenced in expressions
- Operators: Mathematical symbols like +, -, *, /, ^
📚 Learning Path
Follow this progression: Basic arithmetic → Functions → Variables → Complex expressions → Domain-specific functions (physics, electronics, etc.)
☑ Comprehensive Syntax Guide
Understanding operator precedence is crucial for writing correct expressions:
Precedence |
Operator |
Description |
Associativity |
Example |
1 (Highest) | ( ) | Parentheses | N/A | (2 + 3) * 4 = 20 |
2 | ^, ** | Exponentiation | Right | 2^3^2 = 2^(3^2) = 512 |
3 | +x, -x, ! | Unary operators | Right | -5^2 = -(5^2) = -25 |
4 | *, /, % | Multiplication, Division, Modulo | Left | 6 * 4 / 2 = 12 |
5 | +, - | Addition, Subtraction | Left | 5 + 3 - 2 = 6 |
6 | <, >, <=, >= | Comparison | Left | 5 > 3 = 1 (true) |
7 | ==, !=, <> | Equality | Left | x == 5 |
8 | &&, and | Logical AND | Left | a && b |
9 (Lowest) | ||, or | Logical OR | Left | a || b |
Number Formats
The parser supports multiple number formats for flexibility:
Integer Numbers:
42, -17, 0, 1000000
Decimal Numbers:
3.14159, -2.5, 0.001, .5 (= 0.5)
Scientific Notation:
1.23e-4 (= 0.000123)
6.022E23 (= 6.022 × 10²³)
-9.81e0 (= -9.81)
Alternative Operators
The parser provides multiple ways to write the same operation:
Operation |
Primary |
Alternative |
Example |
Exponentiation | ^ | ** | 2^3 = 2**3 = 8 |
Not equal | != | <> | a != b = a <> b |
Logical AND | && | and | a && b = a and b |
Logical OR | || | or | a || b = a or b |
Logical NOT | ! | not | !a = not a |
⚠️ Important Syntax Rules
- Case Sensitivity: Function names and variables are case-sensitive
- Whitespace: Spaces are ignored in expressions
- Decimal Point: Always use period (.) for decimal point, never comma
- Function Arguments: Separate with commas, not semicolons
- Parentheses Matching: Every opening parenthesis must have a matching closing one
☑ Using Functions
Functions are the core building blocks of complex expressions. Here's how to use them:
Basic Function Calls
Single Argument Functions:
sin(pi/4) → sine of π/4 radians
sqrt(25) → square root of 25
abs(-5.7) → absolute value of -5.7
Multiple Argument Functions:
pow(2, 8) → 2 raised to the 8th power
log(2, 1024) → logarithm base 2 of 1024
atan2(1, 1) → two-argument arctangent
Variable Argument Functions:
max(3, 1, 4, 2, 7) → maximum of all arguments
mean(10, 20, 30, 40, 50) → arithmetic mean
sum(1, 2, 3, 4, 5) → sum of all arguments
Function Categories
Mathematical Functions
- Basic: abs(), sqrt(), pow(), sign()
- Trigonometric: sin(), cos(), tan(), asin(), acos(), atan()
- Logarithmic: ln(), log(), log2(), log10()
- Statistical: mean(), median(), stdev(), variance()
Physics Functions
- Mechanics: kinetic_energy(), momentum(), force()
- Thermodynamics: ideal_gas_pressure(), carnot_efficiency()
- Electromagnetics: coulomb_force(), magnetic_force()
Electronics Functions
- Basic Laws: ohms_law_voltage(), power_electrical()
- Components: resistors_series(), capacitors_parallel()
- AC Analysis: impedance_magnitude(), power_factor()
💡 Function Discovery
Use the reference tabs above to explore all available functions. Functions are organized by domain, making it easy to find what you need for your specific application.
☑ Working with Variables
Variables allow you to store values and reuse them in expressions, making your calculations more flexible and maintainable.
Setting Variables in C#
// Create evaluator
var evaluator = new ExpressionEvaluator();
// Set individual variables
evaluator.SetVariable("mass", 1500.0); // kg
evaluator.SetVariable("velocity", 25.0); // m/s
evaluator.SetVariable("gravity", 9.81); // m/s²
evaluator.SetVariable("pi_over_4", Math.PI / 4);
// Set multiple variables
var variables = new Dictionary<string, double>
{
["radius"] = 5.0,
["height"] = 10.0,
["density"] = 1200.0
};
evaluator.SetVariables(variables);
Variable Naming Rules
- Case Sensitive: Mass and mass are different variables
- Start with letter: Variables must begin with a letter (a-z, A-Z)
- Can contain: Letters, numbers, and underscores
- Cannot contain: Spaces, special characters, or operators
- Cannot be: Reserved words like function names or constants
💡 Performance Tip
Setting variables once and reusing them in multiple expressions is more efficient than embedding constants directly in expression strings.
☑ Practical Examples
Learn through practical examples that demonstrate the parser's capabilities in various domains.
Engineering Calculations
Structural Engineering - Beam Deflection
// Calculate maximum deflection of a simply supported beam
var evaluator = new ExpressionEvaluator();
// Set variables (SI units)
evaluator.SetVariable("F", 10000); // Applied force (N)
evaluator.SetVariable("L", 6); // Beam length (m)
evaluator.SetVariable("E", 200e9); // Young's modulus (Pa)
evaluator.SetVariable("I", 8.33e-6); // Second moment of area (m⁴)
// Calculate maximum deflection: δ = FL³/(48EI)
string expression = "F * L^3 / (48 * E * I)";
double deflection = evaluator.Evaluate(expression);
Console.WriteLine($"Maximum deflection: {deflection:F6} m");
Electrical Engineering - RLC Circuit Analysis
// RLC series circuit calculations
evaluator.SetVariable("R", 100); // Resistance (Ω)
evaluator.SetVariable("L", 0.1); // Inductance (H)
evaluator.SetVariable("C", 10e-6); // Capacitance (F)
evaluator.SetVariable("f", 60); // Frequency (Hz)
// Calculate impedances
double XL = evaluator.Evaluate("2 * pi * f * L"); // Inductive reactance
double XC = evaluator.Evaluate("1 / (2 * pi * f * C)"); // Capacitive reactance
evaluator.SetVariable("XL", XL);
evaluator.SetVariable("XC", XC);
// Total impedance magnitude
double Z = evaluator.Evaluate("sqrt(R^2 + (XL - XC)^2)");
Console.WriteLine($"Circuit impedance: {Z:F2} Ω");
Scientific Calculations
Physics - Orbital Mechanics
// Calculate orbital period of a satellite
evaluator.SetVariable("G", 6.67430e-11); // Gravitational constant
evaluator.SetVariable("M", 5.972e24); // Earth mass (kg)
evaluator.SetVariable("r", 7000e3); // Orbital radius (m)
// Orbital period: T = 2π√(r³/GM)
string periodExpression = "2 * pi * sqrt(r^3 / (G * M))";
double period = evaluator.Evaluate(periodExpression);
Console.WriteLine($"Orbital period: {period/3600:F2} hours");
// Orbital velocity: v = √(GM/r)
double velocity = evaluator.Evaluate("sqrt(G * M / r)");
Console.WriteLine($"Orbital velocity: {velocity:F0} m/s");
☑ Common Patterns and Techniques
Master these common patterns to write more effective and maintainable expressions.
Conditional Logic Patterns
Using the if() Function
Basic Conditional:
if(temperature > 100, "Steam", "Water")
→ Returns "Steam" if temp > 100°C, otherwise "Water"
Mathematical Conditionals:
if(x >= 0, sqrt(x), 0)
→ Safe square root that returns 0 for negative inputs
Mathematical Transformation Patterns
Normalization and Scaling
Min-Max Normalization:
(value - min_value) / (max_value - min_value)
→ Scales value to range [0, 1]
Percentage Calculation:
(actual_value / target_value) * 100
→ Expresses actual as percentage of target
Geometric Calculations
Distance Formula:
sqrt((x2 - x1)^2 + (y2 - y1)^2)
→ 2D distance between points
Circle Area and Circumference:
pi * radius^2 → Area
2 * pi * radius → Circumference
☑ Troubleshooting Guide
Identify and resolve common problems when working with the expression parser.
Syntax Errors
Parentheses Mismatches
❌ Problem:
sin(pi/4 + cos(pi/3) → Missing closing parenthesis
✅ Solution:
sin(pi/4 + cos(pi/3)) → Every opening parenthesis needs a closing one
Invalid Function Names
❌ Problem:
sine(pi/4) → Function name misspelled
✅ Solution:
sin(pi/4) → Use correct function name
Mathematical Errors
Division by Zero
❌ Problem:
1 / (x - 5) when x = 5 → Division by zero
✅ Solution:
if(x != 5, 1 / (x - 5), inf) → Guard against division by zero
Domain Errors
❌ Problem:
sqrt(-4) → Square root of negative number
✅ Solution:
if(x >= 0, sqrt(x), 0) → Check domain before calculation
🔍 Debugging Checklist:
- Check parentheses are balanced
- Verify all variables are defined
- Confirm function names are spelled correctly
- Validate function argument counts
- Test with simple known values
- Break complex expressions into parts
- Check for mathematical domain issues
☑ Best Practices
Follow these best practices to create maintainable, efficient, and reliable expressions.
Code Organization
Use Descriptive Variable Names
❌ Poor naming:
a * b + c / d
✅ Descriptive naming:
force * distance + work_done / time_elapsed
Document Units and Assumptions
// ✅ Well-documented setup
// All values in SI units unless noted
evaluator.SetVariable("mass", 1500.0); // kg
evaluator.SetVariable("velocity", 25.0); // m/s
evaluator.SetVariable("angle", deg(45)); // Convert 45° to radians
evaluator.SetVariable("pressure", 2.5e5); // Pa (250 kPa)
// Calculate kinetic energy (result in Joules)
double kinetic_energy = evaluator.Evaluate("0.5 * mass * velocity^2");
Error Prevention
Validate Inputs
// ✅ Input validation patterns
public double CalculateSafeSquareRoot(double value)
{
evaluator.SetVariable("input_value", value);
// Validate before calculation
bool isValid = evaluator.Evaluate("input_value >= 0") == 1;
if (!isValid)
{
throw new ArgumentException("Square root requires non-negative input");
}
return evaluator.Evaluate("sqrt(input_value)");
}
Use Safe Mathematical Operations
// ✅ Safe division with checks
evaluator.SetVariable("numerator", 100);
evaluator.SetVariable("denominator", getValue()); // Could be zero
// Safe division pattern
string safeExpression = "if(abs(denominator) > 1e-10, numerator / denominator, 0)";
double result = evaluator.Evaluate(safeExpression);
🎯 Key Takeaways
- Clarity over cleverness: Write expressions that others can understand
- Test thoroughly: Validate expressions with known results
- Document everything: Include units, assumptions, and examples
- Handle errors gracefully: Always consider edge cases
- Optimize when needed: Profile before optimizing