A single-header C/C++ library for parsing and evaluation of arithmetic expressions

Overview

ceval

A C/C++ header for parsing and evaluation of arithmetic expressions.

[README file is almost identical to that of the ceval library]

Functions accessibe from main()

Function Argument(s) Return Value
ceval_result() A mathematical expression in the form of a character array or a CPP string The result of the expression as a floating point number
ceval_tree() A mathematical expression in the form of a character array or a CPP string The function prints the parse tree with each node properly indented depending on it's location in the tree structure

Supported expressions

Any valid combination of the following operators and functions, with floating point numbers as operands can be parsed by ceval. Parenthesis can be used to override the default operator precedences.

  • Arithematic operators

+ (addition), - (subtraction), * (multiplication), / (division), % (modulo), ** (exponentiation), // (quotient)

  • Relational operators

== (equal), != (not equal), < (strictly less), > (strictly greater), <= (less or equal), >= (greater or equal) to compare the results of two expressions

  • Single-argument functions

exp(), sqrt(), cbrt(), sin(), cos(), tan(), asin(), acos(), atan(), sinh(), cosh(), tanh(), abs(), ceil(), floor(), log10(), ln(), deg2rad(), rad2deg(), signum(), int(), frac(), fact()

  • Two-argument functions

pow(), atan2(), gcd(), hcf(), lcm(), log() (generalized log(b, x) to any base b)

  • Pre-defined math constants

_pi, _e ...pre-defined constants are prefixed with an underscore

  • Logical operators

&&, || and !

  • Bitwise operators

&, |, ^

  • Other operators

    • , (Comma operator) Comma operator returns the result of it's rightmost operand Ex: 2,3 would give 3; 4,3,0 would be equal to 0; and cos(_pi/2,_pi/3,_pi) would return cos(_pi) i.e, -1
    • e (e-operator for scientific notation) Using the binary e operator, we can use scientific notation in our arithmetic expressions Ex: 0.0314 could be written as 3.14e-2; 1230000 could be subsituted by 1.23e6

Usage

Include the ceval library using the #include "PATH_TO_CEVAL.H" directive your C/C++ project.

The code snippet given below is a console based interpreter that interactively takes in math expressions from stdin, and prints out their parse trees and results.

//lang=c
#include<stdio.h>
#include<stdlib.h>

#include "ceval.h"

int main(int argc, char ** argv) {
  char expr[100];
  while (1) {
    printf("In = ");
    fgets(expr, 100, stdin);
    if (!strcmp(expr, "exit\n")) {
      break;
    } else if (!strcmp(expr, "clear\n")) {
      system("clear");
      continue;
    } else {
      ceval_tree(expr);
      printf("\nOut = %f\n\n", ceval_result(expr));
    }
  }
  return 0;
}

Test Run

In = 3*7^2
                2
        ^
                7
*
        3

Out = 147.000000


In = (3.2+2.8)/2
        2
/
                2.80
        +
                3.20

Out = 3.000000


In = _e^_pi>_pi^_e
                2.72
        ^
                3.14
>
                3.14
        ^
                2.72

Out = 1.000000


In = 5.4%2
        2
%
        5.40

Out = 1.400000


In = 5.4//2
        2
//
        5.40

Out = 2.000000


In = 2*2.0+1.4
        1.40
+
                2
        *
                2

Out = 5.400000


In = (5/4+3*-5)+(sin(_pi))^2+(cos(_pi))^2
                2
        ^
                        3.14
                cos
+
                        2
                ^
                                3.14
                        sin
        +
                                        5
                                -
                        *
                                3
                +
                                4
                        /
                                5

Out = -12.750000


In = 3,4,5,6
        6
,
                5
        ,
                        4
                ,
                        3

Out = 6.000000


In = tanh(2/3)==(sinh(2/3)/cosh(2/3))
                                3
                        /
                                2
                cosh
        /
                                3
                        /
                                2
                sinh
==
                        3
                /
                        2
        tanh

Out = 1.000000


In = (2+3/3+(3+9.7))
                9.70
        +
                3
+
                        3
                /
                        3
        +
                2

Out = 15.700000


In = sin(_pi/2)+cos(_pi/2)+tan(_pi/2)
                        2
                /
                        3.14
        tan
+
                                2
                        /
                                3.14
                cos
        +
                                2
                        /
                                3.14
                sin

[ceval]: tan() is not defined for odd-integral multiples of _pi/2

Out = nan


In = asin(2)
        2
asin

[ceval]: Numerical argument out of domain

Out = nan


In = exit
... Program finished with exit code 0

Note

When the ceval.h file is included in a C-program, you might require the -lm flag to link math.h

gcc file.c -lm 
You might also like...
The given files contains a coded algorithm for a program of "OMR Evaluation" With negative marking below are brief info regarding its feature

OMR-Evalution The given files contains a coded algorithm for a program of "OMR Evaluation" With negative marking below are brief info regarding its fe

Tuibox - A single-header terminal UI (TUI) library, capable of creating mouse-driven, interactive applications on the command line.
Tuibox - A single-header terminal UI (TUI) library, capable of creating mouse-driven, interactive applications on the command line.

tuibox tuibox ("toybox") is a single-header terminal UI library, capable of creating mouse-driven, interactive applications on the command line. It is

A single header C++ wasm frontend library leveraging Emscripten
A single header C++ wasm frontend library leveraging Emscripten

Livid Livid is a single header C++ wasm frontend library leveraging Emscripten. Usage The code looks something like this: #include "livid/livid.hpp" #

Single-header multi-platform tablet library

EasyTab Single-header multi-platform tablet library, for easy integration of drawing tablets (e.g. Wacom) into your code. Features Single-file header-

C++ single-header entity component system library

ECS This is a simple C++ header-only type-safe entity component system library. It makes heavy use of C++11 constructs, so make sure you have an up to

An 802.11 Frame Generation and Parsing Library in C

libwifi 802.11 Parsing / Generation library Build Status OS Architecture Linux x86_64 What is this? libwifi is a C library with a permissive license f

Just a basic mini library for parsing simple files that only have variables written and with Lua extension.

C++ Parser Lua file config Just a basic mini library for parsing simple files that only have variables written and with Lua extension. Note: At the mo

ZSV/lib: a fast CSV parsing library and standalone utility
ZSV/lib: a fast CSV parsing library and standalone utility

Please note: this code is still alpha / pre-production. Everything here should be considered preliminary. If you like ZSVlib, please give it a star! Z

This project contains a library for C++ AST parsing, metaprogramming and reflection

Meta C++ This project contains a library for C++ AST parsing, metaprogramming and reflection. Also included is a tool for generating the necessary met

Releases(1.0.1)
  • 1.0.1(Dec 30, 2021)

  • 1.0.0(Sep 13, 2021)

    • [feature] addition of stoic mode to suppress error messages (https://github.com/erstan/ceval-single-header/commit/b751b3718f2c054d92b2865cc6cca472640ddaf9)
    • [desupported] _e and _pi are replaced by e and pi without the underscore prefix (https://github.com/erstan/ceval-single-header/commit/ece88c43998a01b0da07646c183b3e48e700d858)
    • [fix] fixed warnings from clang (https://github.com/erstan/ceval-single-header/commit/c8163ab81fdaf22e68efc3e6595034b73d9ea240, https://github.com/erstan/ceval-single-header/commit/1ed80ae78ba7bef1744b1ccdffc6c6802eeec8fa)
    • [fix] inequality operators not working properly (https://github.com/erstan/ceval-single-header/commit/99bb2528f53e9d6bf52817db83876e23e314849e)
    Source code(tar.gz)
    Source code(zip)
  • 0.0.1(Aug 10, 2021)

    ceval-single-header(v0.0.1)

    • arithmetic operators { +, -, *, /, %, //, `** }

    • relational operators { ==, !=, <, >, <=, >= }

    • logical operators { &&, || and ! }

    • bitwise operators { &, |, ^, <<, >>, ~ }

    • other operators { , (comma operator), e (for scientific notation) }

    • functions { exp(), sqrt(), cbrt(), sin(), cos(), tan(), asin(), acos(), atan(), sinh(), cosh(), tanh(), abs(), ceil(), floor(), log10(), ln(), deg2rad(), rad2deg(), signum(), int(), frac(), fact(), pow(), atan2(), gcd(), hcf(), lcm(), log() }

    • pre-defined math constants { _pi, _e } ...math constants are prefixed with an underscore

    Source code(tar.gz)
    Source code(zip)
Owner
e_t
e_t
A C/C++ library for parsing and evaluation of arithmetic expressions.

ceval A C/C++ header for parsing and evaluation of arithmetic expressions. Functions accessibe from main() Function Argument(s) Return Value ceval_res

e_t 6 Nov 8, 2022
A simple implementation of a parser and its use to calculate simple mathematical expressions

Calculator C Parser A simple implementation of a parser and its use to calculate simple mathematical expressions I haven't written a detailed descript

Romes 14 Nov 8, 2021
Tests to check the determinism of the basic floating point arithmetic operations on different devices, using Unity and Rust.

This repo contains tests to check the determinism (consistency) of the basic floating point arithmetic operations (add, subtract, multiply, divide) on

Erik Roystan 9 Dec 20, 2022
A single file, single function, header to make notifications on the PS4 easier

Notifi Synopsis Adds a single function notifi(). It functions like printf however the first arg is the image to use (NULL and any invalid input should

Al Azif 9 Oct 4, 2022
Performance Evaluation of a Parallel Image Enhancement Technique for Dark Images on Multithreaded CPU and GPU Architectures

Performance Evaluation of a Parallel Image Enhancement Technique for Dark Images on Multithreaded CPU and GPU Architectures Image processing is a rese

Batuhan Hang√ľn 5 Nov 4, 2021
CPU Performance Evaluation and Execution Time Prediction Using Narrow Spectrum Benchmarking

This is a simple implementation of Saavedra-Barrera's paper SAAVEDRA-BARRERA R H. CPU Performance Evaluation and Execution Time Prediction Using Narrow Spectrum Benchmarking[D/OL]. UCB/CSD92-684. EECS Department, University of California, Berkeley, 1992.

null 9 Jan 27, 2022
Compile-time C Compiler implemented as C++14 constant expressions

constexpr-8cc: Compile-time C Compiler constexpr-8cc is a compile-time C compiler implemented as C++14 constant expressions. This enables you to compi

Keiichi Watanabe 762 Dec 12, 2022
An AI for playing NES Tetris at a high level. Based primarily on search & heuristic, with high quality board evaluation through value iteration.

StackRabbit An AI that plays NES Tetris at a high level. Primarily based on search & heuristic, with high-quality board eval through value iteration.

Greg Cannon 244 Jan 5, 2023
MAXREFDES1277 is a reference design that enables the evaluation of MAX17853/52 for battery management in a 48V system.

MAXREFDES1277 The MAXREFDES1277 reference design enables quick evaluation of MAX17853/52 for battery management in a 48V system. It can be used to tes

Maxim Integrated Training & Technical Support (TTS) Team 3 Dec 2, 2021
FlexOS: Towards Flexible OS Isolation (ASPLOS'22) Artifact Evaluation Repository

FlexOS ASPLOS'22 Artifact Evaluation This repository contains the artifacts, including experiments and graphs, for the paper: FlexOS: Towards Flexible

null 12 Aug 24, 2022