### Build libqalculate from source Source: https://github.com/qalculate/libqalculate/blob/master/README.md Standard sequence of commands to compile and install the library from the source directory. ```bash ./autogen.sh ``` ```bash ./configure ``` ```bash make ``` ```bash make install ``` ```bash ldconfig ``` -------------------------------- ### Execute qalc commands Source: https://github.com/qalculate/libqalculate/blob/master/README.md Examples for running the qalc CLI tool in non-interactive and interactive modes. ```bash qalc mathematical expression ``` ```bash qalc 5+2 ``` ```bash qalc --help ``` ```bash qalc ``` ```bash man qalc ``` -------------------------------- ### Basic Math Operations in Qalculate! Source: https://github.com/qalculate/libqalculate/blob/master/README.md Demonstrates basic mathematical functions like square root, cube root, logarithms, factorials, integer division, modulo, factorization, fractions, GCD, trigonometric functions, summation, product, and variable assignment. ```R sqrt 4 # = sqrt(4) = 4^(0.5) = 4^(1/2) = 2 ``` ```R sqrt(25; 16; 9; 4) # = [5 4 3 2] ``` ```R sqrt(32) # = 4 × √(2) (in exact mode) ``` ```R cbrt(-27) # = root(-27; 3) = −3 (real root) ``` ```R (-27)^(1/3) # ≈ 1.5 + 2.5980762i (principal root) ``` ```R ln 25 # = log(25; e) ≈ 3.2188758 ``` ```R log2(4)/log10(100) # = log(4; 2)/log(100; 10) = 1 ``` ```R 5! # = 1 × 2 × 3 × 4 × 5 = 120 ``` ```R 5\2 # = 5//2 = trunc(5 / 2) = 2 (integer division) ``` ```R 5 mod 3 # = mod(5; 3) = 2 ``` ```R 52 to factors # = 2^2 × 13 ``` ```R 25/4 * 3/5 to fraction # = 3 + 3/4 ``` ```R gcd(63; 27) # = 9 ``` ```R sin(pi/2) - cos(pi) # = sin(90 deg) − cos(180 deg) = 2 ``` ```R sum(x; 1; 5) # = 1 + 2 + 3 + 4 + 5 = 15 ``` ```R sum(\'i^2+sin(\'i); 1; 5; \'i) # = 1^2 + sin(1) + 2^2 + sin(2) + … ≈ 55.176162 ``` ```R product(x; 1; 5) # = 1 × 2 × 3 × 4 × 5 = 120 ``` ```R var1:=5 # stores value 5 in variable var1 ``` ```R var1 * 2 # = 10 ``` ```R sinh(0.5) where sinh()=cosh() # = cosh(0.5) ≈ 1.1276260 ``` ```R plot(x^2; -5; 5) # plots the function y=x^2 from -5 to 5 ``` -------------------------------- ### Physical Constants and Calculations in Qalculate! Source: https://github.com/qalculate/libqalculate/blob/master/README.md Demonstrates using fundamental physical constants and planetary data for calculations. Supports symbolic representation and conversion to base units. ```bash k_e / G * a_0 # = (CoulombsConstant / NewtonianConstant) × BohrRadius ≈ 7.126e9 kg·H·m^−1 ``` ```bash ℎ / (λ_C * c) # = planck ∕ (ComptonWavelength × SpeedOfLight) ≈ 9.1093837e-31 kg ``` ```bash 5 ns * rydberg to c # ≈ 6.0793194E-8c ``` ```bash atom(Hg; weight) + atom(C; weight) * 4 to g # ≈ 4.129e-22 g ``` ```bash (G * planet(earth; mass) * planet(mars; mass))/(54.6e6 km)^2 # ≈ 8.58e16 N (gravitational attraction between earth and mars) ``` -------------------------------- ### Compile Libqalculate Programs Source: https://context7.com/qalculate/libqalculate/llms.txt Provides commands and configuration snippets for building applications using pkg-config with C++, Autoconf, and CMake. ```bash # Simple compilation c++ `pkg-config --cflags --libs libqalculate` myprogram.cc -o myprogram # For autoconf projects, add to configure.ac: # PKG_CHECK_MODULES(QALCULATE, [libqalculate >= 5.0.0]) # AC_SUBST(QALCULATE_CFLAGS) # AC_SUBST(QALCULATE_LIBS) # Then in Makefile.am: # myprogram_CFLAGS = $(QALCULATE_CFLAGS) # myprogram_LDADD = $(QALCULATE_LIBS) # For CMake projects: # find_package(PkgConfig REQUIRED) # pkg_check_modules(QALCULATE REQUIRED libqalculate) # target_link_libraries(myprogram ${QALCULATE_LIBRARIES}) # target_include_directories(myprogram PRIVATE ${QALCULATE_INCLUDE_DIRS}) ``` -------------------------------- ### Calculator Initialization Source: https://context7.com/qalculate/libqalculate/llms.txt Describes how to instantiate the global Calculator class and load necessary definitions for mathematical operations. ```APIDOC ## Calculator Initialization ### Description The Calculator class is the central component that must be instantiated before using any other library features. It manages all variables, functions, units, and handles expression parsing and evaluation. ### Method Constructor: new Calculator() ### Usage - Initialize the calculator instance. - Load global definitions (functions, units, variables, constants). - Load exchange rates for currency conversion. - Load user-specific definitions from local configuration. ``` -------------------------------- ### Initialize the Calculator Instance Source: https://context7.com/qalculate/libqalculate/llms.txt Instantiate the global Calculator object and load necessary definitions and exchange rates before performing any calculations. ```cpp #include int main() { // Create the global calculator instance new Calculator(); // Load exchange rates for currency conversion CALCULATOR->loadExchangeRates(); // Load all standard definitions (functions, units, variables, constants) CALCULATOR->loadGlobalDefinitions(); // Load user-specific definitions from ~/.qalculate/definitions CALCULATOR->loadLocalDefinitions(); // Calculator is now ready to use // Access via CALCULATOR macro anywhere in your code return 0; } ``` -------------------------------- ### Unit Conversions in Qalculate! Source: https://github.com/qalculate/libqalculate/blob/master/README.md Shows how to perform unit conversions, including volume, speed, length, force, power, resistance, and data size. The 'to' keyword or arrow symbols can be used for conversion. ```R 5 dm3 to l # = 5 dm^3 to L = 5 L ``` ```R 20 miles / 2 h to km/h # = 16.09344 km/h ``` ```R 1.74 to ft # = 1.74 m to ft ≈ 5 ft + 8.5039370 in ``` ```R 1.74 m to -ft # ≈ 5.7086614 ft ``` ```R 100 lbf * 60 mph to hp # ≈ 16 hp ``` ```R 50 Ω * 2 A # = 100 V ``` ```R 50 Ω * 2 A to base # = 100 kg·m²/(s³·A) ``` ```R 10 N / 5 Pa # = (10 N)/(5 Pa) = 2 m² ``` ```R 5 m/s to s/m # = 0.2 s/m ``` ```R €500 - 20% to £ # ≈ £347.12 ``` ```R 500 megabit/s * 2 h to b?byte # ≈ 419.09516 gibibytes ``` -------------------------------- ### Define Custom Variables Source: https://context7.com/qalculate/libqalculate/llms.txt Shows how to create KnownVariable and UnknownVariable instances, including setting assumptions for unknown variables and adding them to the calculator. ```cpp #include #include int main() { new Calculator(); CALCULATOR->loadGlobalDefinitions(); // Create a known variable with numeric value KnownVariable *gravity = new KnownVariable( "Physics", // Category "g_local", // Name "9.81", // Value (as string) "Local Gravity", // Title true, // Is local (user-defined) false, // Is builtin true // Is active ); CALCULATOR->addVariable(gravity); // Use the variable in calculations std::cout << CALCULATOR->calculateAndPrint("10 kg * g_local", 2000) << std::endl; // Output: 98.1 kg*m/s^2 or 98.1 N // Create an unknown variable with assumptions UnknownVariable *myvar = new UnknownVariable( "Custom", "n", "Integer n", true, false, true ); // Set assumptions Assumptions *assumptions = new Assumptions(); assumptions->setType(ASSUMPTION_TYPE_INTEGER); assumptions->setSign(ASSUMPTION_SIGN_POSITIVE); myvar->setAssumptions(assumptions); CALCULATOR->addVariable(myvar); // Simplification will use assumptions EvaluationOptions eo; eo.approximation = APPROXIMATION_EXACT; std::cout << CALCULATOR->calculateAndPrint("(-1)^(2n)", 2000, eo) << std::endl; // Output: 1 (because n is a positive integer) // Variable from expression KnownVariable *expr_var = new KnownVariable( "Custom", "speed_of_sound", "343 m/s", "Speed of sound in air" ); CALCULATOR->addVariable(expr_var); std::cout << CALCULATOR->calculateAndPrint("1000 m / speed_of_sound", 2000) << std::endl; // Output: 2.9154519 s return 0; } ``` -------------------------------- ### Uncertainty and Interval Arithmetic in Qalculate! Source: https://github.com/qalculate/libqalculate/blob/master/README.md Illustrates how to perform calculations with uncertainties and intervals. Results with interval arithmetic are shown in parentheses. The '+/-' symbol can replace '±'. ```R sin(5±0.2)^2/2±0.3 # ≈ 0.460±0.088 (0.46±0.12) ``` ```R (2±0.02 J)/(523±5 W) # ≈ 3.824±0.053 ms (3.825±0.075 ms) ``` ```R interval(-2; 5)^2 # ≈ interval(−8.2500000; 12.750000) (interval(0; 25)) ``` -------------------------------- ### Generate Plots with Libqalculate Source: https://context7.com/qalculate/libqalculate/llms.txt Demonstrates how to check for gnuplot availability, generate plot data vectors, and configure plot parameters for output. ```cpp #include #include int main() { new Calculator(); CALCULATOR->loadGlobalDefinitions(); // Check if gnuplot is available if (!CALCULATOR->canPlot()) { std::cout << "Gnuplot not available for plotting" << std::endl; return 1; } // Simple plot using expression string std::cout << CALCULATOR->calculateAndPrint("plot(x^2, -5, 5)", 10000) << std::endl; // Generate plot data vectors for custom plotting MathStructure x_vector, y_vector; y_vector = CALCULATOR->expressionToPlotVector( "sin(x)", // Expression MathStructure(-10), // Min x MathStructure(10), // Max x 100, // Number of steps &x_vector, // Store x values "x", // Variable name default_parse_options, 5000 // Timeout ); // Configure plot parameters PlotParameters pp; pp.title = "Sine Function"; pp.x_label = "x"; pp.y_label = "y"; pp.color = true; pp.grid = true; pp.filename = "sine_plot.png"; // Save to file pp.filetype = PLOT_FILETYPE_PNG; // Configure data series parameters PlotDataParameters pdp; pdp.title = "sin(x)"; pdp.style = PLOT_STYLE_LINES; pdp.smoothing = PLOT_SMOOTHING_NONE; // Create vectors for plotting std::vector y_vectors; std::vector x_vectors; std::vector pdps; y_vectors.push_back(y_vector); x_vectors.push_back(x_vector); pdps.push_back(&pdp); // Generate the plot CALCULATOR->plotVectors(&pp, y_vectors, x_vectors, pdps, false, 10000); std::cout << "Plot saved to sine_plot.png" << std::endl; return 0; } ``` -------------------------------- ### Perform Symbolic Algebra and Calculus Operations Source: https://context7.com/qalculate/libqalculate/llms.txt Demonstrates how to use the Calculator class to perform differentiation, integration, equation solving, and factorization using exact evaluation options. ```cpp #include #include int main() { new Calculator(); CALCULATOR->loadGlobalDefinitions(); EvaluationOptions eo; eo.approximation = APPROXIMATION_EXACT; // Differentiation std::string diff_result = CALCULATOR->calculateAndPrint("diff(x^3 + 2x^2 - 5x + 1, x)", 5000, eo); std::cout << "Derivative: " << diff_result << std::endl; // Output: 3x^2 + 4x - 5 // Integration std::string int_result = CALCULATOR->calculateAndPrint("integrate(3x^2 + 4x - 5, x)", 5000, eo); std::cout << "Integral: " << int_result << std::endl; // Output: x^3 + 2x^2 - 5x // Definite integral std::string def_int = CALCULATOR->calculateAndPrint("integrate(x^2, x, 0, 1)", 5000, eo); std::cout << "Definite integral: " << def_int << std::endl; // Output: 1/3 // Solve equations std::string solution = CALCULATOR->calculateAndPrint("solve(x^2 - 5x + 6 = 0, x)", 5000, eo); std::cout << "Solutions: " << solution << std::endl; // Output: x = 2 or x = 3 // Solve system of equations std::string sys_solution = CALCULATOR->calculateAndPrint( "multisolve([2x + y = 5, x - y = 1], [x, y])", 5000, eo); std::cout << "System solution: " << sys_solution << std::endl; // Output: [2, 1] // Factorization std::string factored = CALCULATOR->calculateAndPrint("x^2 - 5x + 6 to factors", 5000, eo); std::cout << "Factored: " << factored << std::endl; // Output: (x - 2)(x - 3) // Limits std::string limit = CALCULATOR->calculateAndPrint("limit(sin(x)/x, x, 0)", 5000, eo); std::cout << "Limit: " << limit << std::endl; // Output: 1 return 0; } ``` -------------------------------- ### Perform RPN Stack Operations in C++ Source: https://context7.com/qalculate/libqalculate/llms.txt Demonstrates pushing values to the RPN stack, performing arithmetic operations, and applying functions to stack registers. ```cpp #include #include int main() { new Calculator(); CALCULATOR->loadGlobalDefinitions(); EvaluationOptions eo; // Push values onto the RPN stack CALCULATOR->RPNStackEnter("5", eo); CALCULATOR->RPNStackEnter("3", eo); std::cout << "Stack size: " << CALCULATOR->RPNStackSize() << std::endl; // Output: 2 // Perform operation (applies to top two items) CALCULATOR->calculateRPN(OPERATION_ADD, 1000, eo); // Get result from stack MathStructure *top = CALCULATOR->getRPNRegister(1); std::cout << "5 + 3 = " << top->print() << std::endl; // Output: 8 // More complex RPN sequence: (4 + 5) * 3 CALCULATOR->clearRPNStack(); CALCULATOR->RPNStackEnter("4", eo); CALCULATOR->RPNStackEnter("5", eo); CALCULATOR->calculateRPN(OPERATION_ADD, 1000, eo); CALCULATOR->RPNStackEnter("3", eo); CALCULATOR->calculateRPN(OPERATION_MULTIPLY, 1000, eo); top = CALCULATOR->getRPNRegister(1); std::cout << "(4 + 5) * 3 = " << top->print() << std::endl; // Output: 27 // Apply function to top of stack CALCULATOR->clearRPNStack(); CALCULATOR->RPNStackEnter("2", eo); CALCULATOR->calculateRPN(CALCULATOR->f_sqrt, 1000, eo); top = CALCULATOR->getRPNRegister(1); std::cout << "sqrt(2) = " << top->print() << std::endl; // Output: 1.4142136 return 0; } ``` -------------------------------- ### Convert Units using Libqalculate Source: https://context7.com/qalculate/libqalculate/llms.txt Perform unit conversions using string identifiers, Unit objects, or automatic base unit conversion. Requires an evaluated MathStructure. ```cpp #include #include int main() { new Calculator(); CALCULATOR->loadGlobalDefinitions(); // Simple unit conversion MathStructure value = CALCULATOR->parse("100 km/h"); EvaluationOptions eo; value.eval(eo); MathStructure converted = CALCULATOR->convert(value, "m/s", eo); std::cout << converted.print() << std::endl; // Output: 27.777778 m/s // Convert using Unit object Unit *mph = CALCULATOR->getUnit("mph"); if (mph) { MathStructure result = CALCULATOR->convert(value, mph, eo); std::cout << result.print() << std::endl; // Output: 62.137119 mph } // Temperature conversion (non-linear) MathStructure temp = CALCULATOR->calculate("100 degC to degF", eo); std::cout << temp.print() << std::endl; // Output: 212 degF // Mixed units conversion MathStructure length = CALCULATOR->parse("1.75 m"); length.eval(eo); MathStructure mixed = CALCULATOR->convertToMixedUnits(length, eo); std::cout << mixed.print() << std::endl; // Output: 5 ft + 8.89764 in // Convert to SI base units MathStructure force = CALCULATOR->parse("100 lbf"); force.eval(eo); MathStructure base = CALCULATOR->convertToBaseUnits(force, eo); std::cout << base.print() << std::endl; // Output in kg*m/s^2 return 0; } ``` -------------------------------- ### Configure Precision and Evaluation Options in C++ Source: https://context7.com/qalculate/libqalculate/llms.txt Sets global precision, enables interval arithmetic, and configures evaluation and print options for high-precision calculations. ```cpp #include #include int main() { new Calculator(); CALCULATOR->loadGlobalDefinitions(); // Set global precision (number of significant digits) CALCULATOR->setPrecision(50); // 50 significant digits // High precision calculation of pi std::cout << "pi = " << CALCULATOR->calculateAndPrint("pi", 5000) << std::endl; // Enable interval arithmetic for uncertainty tracking CALCULATOR->useIntervalArithmetic(true); // Configure evaluation options EvaluationOptions eo; eo.approximation = APPROXIMATION_TRY_EXACT; // Prefer exact results eo.allow_complex = true; // Allow complex numbers eo.allow_infinite = true; // Allow infinity eo.auto_post_conversion = POST_CONVERSION_OPTIMAL; // Smart unit conversion eo.structuring = STRUCTURING_SIMPLIFY; // Simplify results // Configure parse options eo.parse_options.angle_unit = ANGLE_UNIT_RADIANS; eo.parse_options.base = BASE_DECIMAL; // Calculation with uncertainty std::cout << CALCULATOR->calculateAndPrint("sin(1.5 +/- 0.01)", 2000, eo) << std::endl; // Output: approximately 0.9975 +/- 0.0007 // Configure print options PrintOptions po; po.number_fraction_format = FRACTION_DECIMAL; po.max_decimals = 10; po.use_max_decimals = true; po.min_exp = EXP_SCIENTIFIC; // Use scientific notation MathStructure result = CALCULATOR->calculate("avogadro", eo); std::cout << "Avogadro: " << CALCULATOR->print(result, 1000, po) << std::endl; // Output: 6.0221408e23 return 0; } ``` -------------------------------- ### Calculus Operations Source: https://github.com/qalculate/libqalculate/blob/master/README.md Perform differentiation, integration, and limit calculations. ```ruby diff(6x^2) # = 12x diff(sinh(x^2)/(5x) + 3xy/sqrt(x)) # = (2/5) × cosh(x^2) − sinh(x^2)/(5x^2) + (3y)/(2 × √(x)) integrate(6x^2) # = 2x^3 + C integrate(6x^2; 1; 5) # = 248 integrate(sinh(x^2)/(5x) + 3xy/sqrt(x)) # = 2x × √(x) × y + Shi(x^2) / 10 + C integrate(sinh(x^2)/(5x) + 3xy/sqrt(x); 1; 2) # ≈ 3.6568542y + 0.87600760 limit(ln(1 + 4x)/(3^x - 1); 0) # = 4 / ln(3) ``` -------------------------------- ### Parse and Manipulate Expressions with MathStructure Source: https://context7.com/qalculate/libqalculate/llms.txt Parse string expressions into a manipulatable MathStructure or build them programmatically. Requires loading global definitions via the Calculator instance. ```cpp #include #include int main() { new Calculator(); CALCULATOR->loadGlobalDefinitions(); // Parse an expression ParseOptions po; po.angle_unit = ANGLE_UNIT_DEGREES; // Interpret angles as degrees MathStructure mstruct = CALCULATOR->parse("5x + 2y - 3", po); // Inspect structure type std::cout << "Is addition: " << mstruct.isAddition() << std::endl; std::cout << "Number of terms: " << mstruct.size() << std::endl; // Access children (0-indexed with operator[]) for (size_t i = 0; i < mstruct.size(); i++) { std::cout << "Term " << i << ": " << mstruct[i].print() << std::endl; } // Build expression programmatically MathStructure expr(5); // Start with 5 expr.multiply(CALCULATOR->v_x); // 5 * x expr.add(2); // 5x + 2 expr.raise(MathStructure(2)); // (5x + 2)^2 // Evaluate the structure EvaluationOptions eo; expr.eval(eo); std::cout << "Expanded: " << expr.print() << std::endl; // Output: 25x^2 + 20x + 4 return 0; } ``` -------------------------------- ### Handle Calculation Errors and Messages Source: https://context7.com/qalculate/libqalculate/llms.txt Shows how to process the message queue for errors and warnings, and how to temporarily suppress messages during specific calculations. ```cpp #include #include int main() { new Calculator(); CALCULATOR->loadGlobalDefinitions(); // Perform a calculation that might generate messages EvaluationOptions eo; MathStructure result = CALCULATOR->calculate("1/0", eo); // Process all messages in the queue CalculatorMessage *msg; while ((msg = CALCULATOR->message())) { switch (msg->type()) { case MESSAGE_ERROR: std::cerr << "ERROR: " << msg->message() << std::endl; break; case MESSAGE_WARNING: std::cout << "WARNING: " << msg->message() << std::endl; break; case MESSAGE_INFORMATION: std::cout << "INFO: " << msg->message() << std::endl; break; } // Move to next message CALCULATOR->nextMessage(); } // Temporarily suppress messages for a section of code CALCULATOR->beginTemporaryStopMessages(); // These calculations won't add messages to the queue CALCULATOR->calculate("sqrt(-1)", eo); // Would normally warn about complex // Get count of suppressed messages int error_count = 0, warning_count = 0; int total = CALCULATOR->endTemporaryStopMessages(&error_count, &warning_count); std::cout << "Suppressed " << total << " messages (" << error_count << " errors, " << warning_count << " warnings)" << std::endl; // Clear any remaining messages CALCULATOR->clearMessages(); return 0; } ``` -------------------------------- ### calculate() Source: https://context7.com/qalculate/libqalculate/llms.txt Advanced evaluation method using MathStructure for detailed control over the calculation process. ```APIDOC ## calculate(result, expression, timeout, options, parsed) ### Description Performs advanced evaluation of an expression, allowing for specific evaluation options and returning a MathStructure object for further processing. ### Parameters - **result** (MathStructure*) - Required - Pointer to store the calculation result. - **expression** (string) - Required - The expression to evaluate. - **timeout** (int) - Required - Maximum time in milliseconds. - **options** (EvaluationOptions) - Required - Configuration for approximation, unit synchronization, and structuring. - **parsed** (MathStructure*) - Optional - Pointer to store the parsed expression. ### Response - Returns a boolean indicating success or failure. ``` -------------------------------- ### Matrix and Vector Operations Source: https://github.com/qalculate/libqalculate/blob/master/README.md Handle matrix creation, dot products, cross products, and matrix inversion. ```R [1, 2, 3; 4, 5, 6] # = [1 2 3; 4 5 6] (2×3 matrix) 1…5 = (1:5) = (1:1:5) # = [1 2 3 4 5] (1; 2; 3) * 2 - 2 # = [(1 × 2 − 2), (2 × 2 − 2), (3 × 2 − 2)] = [0 2 4] [1 2 3].[4 5 6] = dot([1 2 3]; [4 5 6]) # = 32 (dot product) cross([1 2 3]; [4 5 6]) # = [−3 6 −3] (cross product) [1 2 3; 4 5 6].*[7 8 9; 10 11 12] # = [7 16 27; 40 55 72] (hadamard product) [1 2 3; 4 5 6] * [7 8; 9 10; 11 12] # = [58 64; 139 154] (matrix multiplication) [1 2; 3 4]^-1 # = inverse([1 2; 3 4]) = [−2 1; 1.5 −0.5] ``` -------------------------------- ### Perform Advanced Calculations with MathStructure Source: https://context7.com/qalculate/libqalculate/llms.txt Utilize MathStructure for granular control over evaluation options, result formatting, and error handling. ```cpp #include #include int main() { new Calculator(); CALCULATOR->loadGlobalDefinitions(); // Set up evaluation options EvaluationOptions eo; eo.approximation = APPROXIMATION_TRY_EXACT; // Try to get exact results eo.sync_units = true; // Convert compatible units eo.structuring = STRUCTURING_SIMPLIFY; // Simplify the result // Calculate an expression MathStructure result; MathStructure parsed; // Optional: stores the parsed expression // Calculate with timeout (5000ms) bool success = CALCULATOR->calculate(&result, "integrate(x^2, x)", 5000, eo, &parsed); if (success && !result.isAborted()) { // Set up print options PrintOptions po; po.number_fraction_format = FRACTION_FRACTIONAL; // Show fractions po.use_unicode_signs = true; // Use Unicode symbols // Print the result with timeout std::string result_str = CALCULATOR->print(result, 1000, po); std::cout << "Result: " << result_str << std::endl; // Output: Result: x^3/3 } // Check for messages (warnings, errors) CalculatorMessage *msg; while ((msg = CALCULATOR->nextMessage())) { std::cout << msg->message() << std::endl; } return 0; } ``` -------------------------------- ### Algebraic Operations Source: https://github.com/qalculate/libqalculate/blob/master/README.md Perform symbolic algebra, equation solving, and partial fraction decomposition. ```ruby (5x^2 + 2)/(x - 3) # = 5x + 15 + 47/(x − 3) (\a + \b)(\a - \b) # = 'a'^2 − 'b'^2 (x + 2)(x - 3)^3 # = x^4 − 7x^3 + 9x^2 + 27x − 54 x^4 - 7x^3 + 9x^2 + 27x - 54 to factors # = (x + 2)(x − 3)^3 cos(x)+3y^2 where x=pi; y=2 # = 11 gcd(25x; 5x^2) # = 5x 1/(x^2+2x-3) to partial fraction # = 1/(4x − 4) − 1/(4x + 12) x+x^2+4 = 16 # x = 3 or x = −4 x^2/(5 m) - hypot(x; 4 m) = 2 m where x > 0 # x ≈ 7.1340411 m cylinder(20cm; x) = 20l # x = (1 / (2π)) m ≈ 16 cm asin(sqrt(x)) = 0.2 # x = sin(0.2)^2 ≈ 0.039469503 x^2 > 25x # x > 25 or x < 0 solve(x = y+ln(y); y) # = lambertw(e^x) solve2(5x=2y^2; sqrt(y)=2; x; y) # = 32/5 multisolve([5x=2y+32, y=2z, z=2x]; [x, y, z]) # = [−32/3 −128/3 −64/3] dsolve(diff(y; x) - 2y = 4x; 5) # = 6e^(2x) − 2x − 1 ``` -------------------------------- ### Perform Arithmetic and Mathematical Operations with Number Source: https://context7.com/qalculate/libqalculate/llms.txt Use the Number class for arbitrary precision arithmetic, complex number support, and property checking. Requires initialization of the Calculator object. ```cpp #include #include int main() { new Calculator(); // Create numbers in various ways Number n1(3, 4); // 3/4 (rational) Number n2(2, 1, 3); // 2 * 10^3 = 2000 Number n3("3.14159265358979323846"); // From string, arbitrary precision // Arithmetic operations (modify in place) Number result = n1; result.add(n2); // result = 3/4 + 2000 Number product(5); product.multiply(n1); // product = 5 * 3/4 = 15/4 // Mathematical functions Number sqrt_val(2); sqrt_val.sqrt(); // sqrt(2) Number log_val(100); log_val.log(10); // log10(100) = 2 // Complex numbers Number complex_num(3); complex_num.setImaginaryPart(4); // 3 + 4i Number magnitude = complex_num; magnitude.abs(); // |3 + 4i| = 5 // Check properties Number test(7); std::cout << "Is prime: " << test.isPrime() << std::endl; // true std::cout << "Is integer: " << test.isInteger() << std::endl; // true // Print with options PrintOptions po; po.number_fraction_format = FRACTION_FRACTIONAL; std::cout << product.print(po) << std::endl; // Output: 15/4 return 0; } ``` -------------------------------- ### Time and Date Calculations Source: https://github.com/qalculate/libqalculate/blob/master/README.md Perform arithmetic on time durations and date conversions. ```ruby 10:31 + 8:30 to time # = 19:01 10h 31min + 8h 30min to time # = 19:01 now to utc # = "2020-07-10T07:50:40Z" "2020-07-10T07:50CET" to utc+8 # = "2020-07-10T14:50:00+08:00" "2020-05-20" + 523d # = addDays(2020-05-20; 523) = "2021-10-25" today - 5 days # = "2020-07-05" "2020-10-05" - today # = days(today; 2020-10-05) = 87 d timestamp(2020-05-20) # = 1 589 925 600 stamptodate(1 589 925 600) # = "2020-05-20T00:00:00" "2020-05-20" to calendars # returns date in Hebrew, Islamic, Persian, Indian, Chinese, Julian, Coptic, and Ethiopian calendars ``` -------------------------------- ### Statistical Functions Source: https://github.com/qalculate/libqalculate/blob/master/README.md Calculate mean, standard deviation, quartiles, and normal distributions. ```R mean(5; 6; 4; 2; 3; 7) # = 4.5 stdev(5; 6; 4; 2; 3; 7) # ≈ 1.87 quartile([5 6 4 2 3 7]; 1) # = percentile((5; 6; 4; 2; 3; 7); 25) ≈ 2.9166667 normdist(7; 5) # ≈ 0.053990967 spearman(column(load(test.csv); 1); column(load(test.csv); 2)) # ≈ −0.33737388 (depends on the data in the CSV file) ``` -------------------------------- ### Perform Linear Algebra Operations Source: https://context7.com/qalculate/libqalculate/llms.txt Use the Calculator instance to evaluate vector and matrix operations including dot products, cross products, determinants, and eigenvalues. ```cpp #include #include int main() { new Calculator(); CALCULATOR->loadGlobalDefinitions(); EvaluationOptions eo; // Create vectors std::cout << CALCULATOR->calculateAndPrint("[1, 2, 3] + [4, 5, 6]", 2000) << std::endl; // Output: [5, 7, 9] // Dot product std::cout << CALCULATOR->calculateAndPrint("dot([1, 2, 3], [4, 5, 6])", 2000) << std::endl; // Output: 32 // Cross product std::cout << CALCULATOR->calculateAndPrint("cross([1, 2, 3], [4, 5, 6])", 2000) << std::endl; // Output: [-3, 6, -3] // Create matrix (semicolons separate rows) std::cout << CALCULATOR->calculateAndPrint("[1, 2; 3, 4]", 2000) << std::endl; // Output: [[1, 2], [3, 4]] // Matrix multiplication std::cout << CALCULATOR->calculateAndPrint("[1, 2; 3, 4] * [5, 6; 7, 8]", 2000) << std::endl; // Output: [[19, 22], [43, 50]] // Determinant std::cout << CALCULATOR->calculateAndPrint("det([1, 2; 3, 4])", 2000) << std::endl; // Output: -2 // Matrix inverse std::cout << CALCULATOR->calculateAndPrint("inverse([1, 2; 3, 4])", 2000) << std::endl; // Output: [[-2, 1], [1.5, -0.5]] // Transpose std::cout << CALCULATOR->calculateAndPrint("transpose([1, 2, 3; 4, 5, 6])", 2000) << std::endl; // Output: [[1, 4], [2, 5], [3, 6]] // Identity matrix std::cout << CALCULATOR->calculateAndPrint("identity(3)", 2000) << std::endl; // Output: [[1, 0, 0], [0, 1, 0], [0, 0, 1]] // Eigenvalues (requires numeric approximation for general case) eo.approximation = APPROXIMATION_APPROXIMATE; MathStructure eigenvalues = CALCULATOR->calculate("eigenvalues([4, -2; 1, 1])", eo); std::cout << "Eigenvalues: " << CALCULATOR->print(eigenvalues, 1000) << std::endl; return 0; } ``` -------------------------------- ### Evaluate Expressions with calculateAndPrint Source: https://context7.com/qalculate/libqalculate/llms.txt Use calculateAndPrint for simple string-based evaluation, including arithmetic, unit conversions, and function calls. ```cpp #include #include int main() { new Calculator(); CALCULATOR->loadGlobalDefinitions(); // Simple arithmetic - timeout after 2000ms std::cout << CALCULATOR->calculateAndPrint("1 + 1", 2000) << std::endl; // Output: 2 // Complex expression with units std::cout << CALCULATOR->calculateAndPrint("5 kg * 9.8 m/s^2", 2000) << std::endl; // Output: 49 N // Unit conversion using "to" syntax std::cout << CALCULATOR->calculateAndPrint("100 km/h to mph", 2000) << std::endl; // Output: 62.137119 mph // Mathematical functions std::cout << CALCULATOR->calculateAndPrint("sqrt(2) + sin(pi/4)", 2000) << std::endl; // Output: 2.1213203 // Currency conversion (requires loaded exchange rates) CALCULATOR->loadExchangeRates(); std::cout << CALCULATOR->calculateAndPrint("100 USD to EUR", 2000) << std::endl; // Output: approximately 92 EUR (varies with exchange rates) return 0; } ``` -------------------------------- ### Number Base Conversions Source: https://github.com/qalculate/libqalculate/blob/master/README.md Convert between binary, octal, hexadecimal, and other bases. ```R 52 to bin # = 0011 0100 52 to bin16 # = 0000 0000 0011 0100 52 to oct # = 064 52 to hex # = 0x34 0x34 = hex(34) # = base(34; 16) = 52 523<<2&250 to bin # = 0010 1000 52.345 to float # ≈ 0100 0010 0101 0001 0110 0001 0100 1000 float(01000010010100010110000101001000) # = 1715241/32768 ≈ 52.345001 floatError(52.345) # ≈ 1.2207031e-6 52.34 to sexa # = 52°20′24″ 1978 to roman # = MCMLXXVIII 52 to base 32 # = 1K sqrt(32) to base sqrt(2) # ≈ 100000 0xD8 to unicode # = Ø code(Ø) to hex # = 0xD8 ``` -------------------------------- ### calculateAndPrint() Source: https://context7.com/qalculate/libqalculate/llms.txt Evaluates a mathematical expression string and returns the result as a formatted string. ```APIDOC ## calculateAndPrint(expression, timeout) ### Description Evaluates a mathematical expression string and returns the result as a string. This method automatically handles unit conversions and basic mathematical functions. ### Parameters - **expression** (string) - Required - The mathematical expression to evaluate. - **timeout** (int) - Required - Maximum time in milliseconds to wait for the calculation. ### Response - Returns a string representation of the calculated result. ```