Show pageOld revisionsBacklinksBack to top This page is read only. You can view the source, but not change it. Ask your administrator if you think this is wrong. ====== 1.5.1 Mathematical expressions syntax ====== <tabs> * [[#tab-ua|UA]] * [[#tab-en|EN]] <pane id="tab-ua"> Математичний движок TechEditor використовує синтаксичні правила, загальноприйняті у математиці і комп'ютерних обчисленнях. Базуючись на цих правилах, ви можете виконувати обрахунки, аналізувати математичні вирази, працювати з фізичними величинами та багато іншого. ===== Синтаксис математичних виразів ===== TechEditor використовує відкриту текстову нотацію. Це означає, що всі математичні вирази набираються простим текстом. Це підвищує інтероперабельність програми і надає широкі можливості для взаємодії з іншими пакетами (наприклад, MS Excel), але вимагає уважності щодо синтаксису та правил написання формул. ==== Основні синтаксичні елементи ==== Математичні вирази можуть містити: * літерали (дійсні або комплексні числа): 1, 7.6, -2.45e+5, 2+3.2I * змінні: a, x1, MyVar * оператори: a+b, x^3, i>100 * функції: f(t), x(a b), y{1}(t) ==== Типи даних ==== Літерали, змінні та функції в TechEditor можуть бути наступних типів: * Real (дійсне число): 1, 2.4, -10.2e3 * Complex (комплексне число): 2+3.2I, -4I * Boolean (логічний тип): True, False * Array (вектор): %%[1 4.5 -2.3]%% * Matrix (матриця / багатовимірний вектор): %%[[a b -1] [0 c -c]]%% * Physical quantity (фізична величина): 2.5 kN; -6.8 MPa; 200 mm ===== Літерали, змінні, оператори, функції ===== ==== Літерали ==== Літерал це безіменна константа або символ, що має незмінне значення. TechEditor розпізнає літерали у вигляді дійсних чисел, комплексних чисел, фізичних величин. Наприклад, у виразі "2*(x+y)" символ "2" є числовим літералом. === Дійсні числа === Числові літерали можуть бути записані в звичайній або експоненціальній (науковій) формі, залежно від величини і обраного формату. Приклади чисел в звичайному форматі: "100", "1.23", "-45.67". Приклад чисел в експоненціальному форматі: "1.23E-3", "-2.45e+5". === Комплексні числа === Комплексні числа мають дійсну ти уявну частини, розділені символом "+" або "–". Дійсна частина є звичайним дійсним числом, а уявна — це дійсне число з символом уявної одиниці "I" (символ "I" є незмінним і не може бути використаний в інших цілях, як-от для змінної чи функції). ВАЖЛИВО: символ добутку між дійсною частиною та символом "I" в комплексному літералі не вказується. Приклади комплексних чисел: "I", "-4I", "2+3.2I", "-2e2-4.45I", "2.45+I", "-1.2e-3+4.5e+2I". === Системні константи === TechEditor має наступні попередньо визначені константи: * **e** (Euler number) * **π**, **Pi** (Pi number) * **∞** (positive infinity) ==== Змінні ==== Змінна це іменований параметр математичної моделі. Ім'я змінної може містити лише алфавітно-цифрові символи та символ підкреслення (першим символом завжди має бути літера). TechEditor допускає використання латинських, грецьких, кириличних літер в іменах змінних. Протягом життєвого циклу, змінна може неодноразово змінювати своє значення або тип. Коли змінній присвоюється нове значення або змінюється її тип, попередня інформація втрачається. \\ \\ В математичні вирази величина змінної потрапляє через її ім'я. Наприклад, якщо змінна "A" дійсного числового типу має величину "1.0", то результат обчислення математичного виразу "A+1" буде "2.0". Змінюючи величину змінної, ви тим самим впливаєте на усі вирази в математичній моделі, де вона використовується. ==== Оператори ==== Синтаксично, оператор це символ для позначення певної математичної операції. Наприклад, у виразі "x+y" оператор "+" визначає операцію додавання. З функціональної точки зору, оператор виконує певну дію над даними (вони звуться операндами) і вертає результат цієї операції. === Унарні та бінарні оператори === Класифікація операторів може бути різною. Поширеним є поділ операторів на унарні та бінарні. Унарний оператор має один операнд та може бути префіксом (йти поперед операнду) або суфіксом (після операнду). Приклад унарного префікс-оператору це віднімання ("-x", де "-" це оператор, "x" — операнд). Приклад унарного суфікс-оператора це факторіал ("n!", де "!" це оператор, "n" — операнд). Бінарний оператор має два операнди і зазвичай розташовується між ними. Прикладом бінарного оператору є операція додавання ("x+y", де "+" це оператор, а "x" and "y" — операнди). === Пріоритетність та асоціативність === Кожен оператор має такі атрибути, як пріоритет і асоціативність. Пріоритет визначає порядок обчислення в математичному виразі: оператори з вищим пріоритетом застосовуються до їхніх операндів раніше за оператори з нижчим пріоритетом. Наприклад, у виразі "x+y*z" першою буде виконана операція множення "y" та "z", а потім — операція додавання "x" до результату попереднього множення. Це тому, що оператор "*" має пріоритет вищий, ніж оператор "+". \\ \\ Порядок обчислень може бути змінено використанням круглих дужок "()". Як саме оператори з однаковим пріоритетом будуть виконуватися під час обчислень, визначає їхня асоціативність. Розглянемо вираз "2^3^4" (де символ "^" є оператором піднесення числа до ступеня). Результат обчислення такого виразу залежить від того, як його інтерпретувати: "(2^3)^4=8^4" або "2^(3^4)=2^81". Асоціативність "зліва-направо" визначає, що оператори виконуються послідовно в напрямку від найлівішого до найправішого у виразі (перший варіант). Асоціативність "справа-наліво" визначає, що оператори виконуються від найправішого до найлівішого у виразі (другий варіант). TechEditor використовує перший варіант, тобто всі оператори у математичних виразах є ліво-асоціативними (завжди виконуються "зліва-направо"). === Синтаксичні правила для операторів === TechEditor підтримує: * базові алгебраїчні операції: "+", "-", "*", "/", "^" * логічні операції: "&", "\", "¬" * умовні операції: "=", ">", "<", "≤", "≥", "≡", "≠", "≈" Існують також деякі спеціальні оператори, які можна використовувати у складних випадках. Загалом, TechEditor визначає наступні синтаксичні правила для операторів: * алгебраїчні бінарні оператори мають пріоритет, визначений загальними правилами математики; * умовні оператори (бінарні) мають нижчий пріоритет, ніж алгебраїчні; * бінарні логічні оператори мають нижчий пріоритет, ніж умовні; * оператори зі стрілками (бінарні) мають вищий пріоритет, ніж оператор степеня; * унарні оператори мають вищий пріоритет, ніж бінарні; * суфіксні оператори мають вищий пріоритет, ніж префіксні; * всі бінарні оператори є ліво-асоціативними. Повний перелік операторів можна знайти в Додатку А. ==== Функції ==== Синтаксично, функція є іменованою операцією над певними даними, що звуться аргументами. Прикладом функції є синус "sin(x)", де "sin" це ім'я функції, а "x" — її аргумент. Ім'я функції визначає, які саме операції потрібно провести з аргументом(-ми). \\ \\ Окрім аргументів, функція може мати параметри. Наприклад, функція логарифму "a" з основою "b" log<sub>b</sub>(a) має один аргумент "a" та один параметр "b". За семантикою, параметри ідентичні аргументам, адже також визначають операції над даними. В TechEditor параметри функцій записуються у фігурних дужках "{}". === Синтаксичні правила для функцій === Основні правила, які визначають роботу функцій в математичній моделі TechEditor: * аргументи функції записуються у круглих дужках "()"; * параметри функції записуються у фігурних дужках "{}"; * аргументи і параметри розділяються пробілами " "; * якщо функція не має параметрів, фігурні дужки можна не вказувати; * круглі дужки (для аргументів) потрібні завжди; * функція може мати кілька параметрів та/або аргументів; * в одній моделі можуть використовуватись функції з однаковими іменами, але різною кількістю аргументів та/або параметрів, або для роботи з різними типами даних. === Приклади функцій === Ось приклади деяких синтаксично коректних функцій: * max(a b) — максимум з двох аргументів; * random() — випадкове число (функція без аргументів); * log{b}(a) — логарифм "a" з основою "b" (один параметр "b", один аргумент "a"); * P{n m}(x) — асоційована функція Лежандра (два параметри "n" та "m", один аргумент "x"). Повний перелік функцій можна знайти в Додатку А. ===== Structured data ===== ==== Indexing ==== TechEditor allows using indexing in expressions. Indexing is a method of accessing separate elements of a structured data. An example of a structured data is the array. Each array element has an unique index (or several indexes) by which the element value is accessed. \\ \\ By syntax rules of TechEditor, the indexes are written in square brackets "[]". For example, the i-th array element can be written as "A[i]". For multiple indexes, each index must be written in separate brackets. For example, a matrix element can be written as "M[i][j]". \\ \\ TechEditor syntax rules allow slicing implementation. Slicing is a method to get some part of a structured data, which is also a structure. Slicing syntax is implemented via index omitting. Let we have a matrix (two-dimensional array) "M". Then, according to the slicing syntax, "M[i][]" is the i-th matrix’ row and "M[][j]" is the j-th matrix’ column. The "trail" indexes can be omitted with their brackets. Thus, the matrix’ row can be written as "M[i]" (which is equivalent to "M[i][]" of the previous example). \\ \\ General indexing rules: * indexing can be applied to variables only, the variables must implement indexing interface; * many indexes allowed, each index must be enclosed in separate brackets "[]"; * all index expressions must return values of real type only, the values must be close to integer numbers; * some indexes can be omitted that means slicing, slicing can only be applied to variables those implement slicing interface. The array variables can contain data of any type and have default indexing and slicing implementation for arrays up to the third dimension. ==== Arrays ==== TechEditor supports using array expressions. Array expression is a structured expression that contains other expressions as its components. An example of array expression is vector — one-dimensional set of ordered items. Array expressions has the dimension — the number of indexes by which the components of the array are ordered. \\ \\ By syntax rules of TechEditor, the array expression must be enclosed by square brackets "[]" and its components are separated by spaces. For example, the vector expression with three components can be written as "[i+1 j*2 k]". For multiple dimensions, the components for each dimension must be written in separate brackets. For example, the 2x3 matrix expression can be written as "[[a b c] [d e f]]". Only rectangular array expressions allowed. \\ \\ General rules for array expressions: * array expressions enclosed with square brackets; * each dimension of array expression must be enclosed with its own brackets; * array expression’s components are separated by spaces; * only rectangular array expressions allowed. TechEditor supports vector and matrix expressions for boolean, real, and complex components. ===== Syntax summary ===== * Any math expression can contain literals, arrays, variables, operators, functions and indexing. * Real and complex literals supported. Some common named math constants supported, like Euler number, Pi. * Variable names can include only alphanumeric symbols and underscore symbol. * Only predefined operators can be used in expressions, new operators cannot be defined. * Operations are performed in order of the precedence. Operations order can be changed using parentheses "()". * Functions have parameters and arguments. Parameters are enclosed in braces "{}", arguments are enclosed in parentheses "()". Parameters and arguments are separated by spaces " ". * Indexing can only be applied to variables those implement special interface. Indexes are enclosed in brackets "[]" (each index in separate brackets). Slicing is implemented by omitting some of the indexes. * Array expressions enclosed with square brackets for each dimension. Array components are separated by spaces. Only rectangular arrays allowed. ===== Приклади ===== ==== Змінна і функція з однаковим ім'ям ==== В прикладі показано, що математична модель допускає одночасне використання змінної і функції з ім'ям "sin". sin:=4.5 sin(90*Pi/180) =1 2*sin =9 </pane> <pane id="tab-en"> ===== Literals, variables, operators, functions ===== ==== Literals ==== A literal is an unnamed constant value or a symbol, standing for "standard" constant value. For example, in the expression "2*(x+y)" — "2" is a numerical literal. TechEditor recognizes Real literals, Complex literals, Physical quantity literals. === Real Literals === Real literals can be written in simple or exponential form, depending on the value and selected format. Simple form examples: "100", "1.23", "-45.67". Exponential form examples: "1.23E-3", "-2.45e+5". === Complex Literals === A complex literal consists of a real and an imaginary parts separated by "+" or "-" symbol. A real part is just a real literal. An imaginary part is a real literal plus imaginary unit symbol "I". This symbol stands for the imaginary unit value. NOTE: there is no multiplication symbol between a real literal and the imaginary unit symbol. Complex literal examples: "I", "-4I", "2+3.2I", "-2e2-4.45I", "2.45+I", "-1.2e-3+4.5e+2I". === Predefined constants === TechEditor supports the following constants: * **e** (Euler number) * **π**, **Pi** (Pi number) * **∞** (positive infinity) ==== Variables ==== A variable is a named value. A variable name can include alphanumeric symbols only and underscore symbol (the first symbol can be letter only). TechEditor allows the use of Latin, Greek, and Cyrillic letters in variable names. The value and type of a variable can be changed during its lifetime. When a variable is assigned a new value or its type is changed, the previous information is lost. \\ \\ In mathematical expressions, a variable value is accessed via the variable name. That is, in an expression the variable name stands for the current variable value. For example, let the variable "A" is a real variable whose current value is "1.0", then the result of "A+1" expression evaluation is "2.0". Changing variable values allows calculation of the same expression for various variable values. ==== Operators ==== Syntactically an operator is a symbol standing for some mathematical operation. For example, in the expression "x+y" the operator "+" stands for the addition operation. From the functional point of view, an operator implements some action with data value(s), called operand(s), and returns the result of the operation. === Unary and binary operators === All operators can be divided into many categories. The most common used are unary and binary operators. An unary operator has one operand and can be prefix (stands in front of its operand) and postfix (stands behind its operand). An example of an unary prefix operator is the negation operator ("-x", "-" is the operator, "x" is the operand). An example of an unary postfix operator is the factorial operator ("n!", "!" is the operator, "n" is the operand). Binary operators have two operands and commonly stand between them. An example of a binary operator is the addition operator ("x+y", "+" is the operator, "x" and "y" are the operands). === Precedence and associativity === Each operator has such attributes as precedence and associativity. The precedence determines the order of expression calculation. The operators with higher precedence applied to their operands before the operators with lower precedence. For example, in the expression "x+y*z" the first operation performed is the multiplication of "y" and "z", then the sum of "x" and the product's result is calculated. This is because the "*" operator is of higher precedence than the "+" is. \\ \\ The order of calculation can be changed by using parentheses "()". The associativity determines how operators with the same precedence are grouped in an expression. Let us consider the expression "2^3^4" (where the "^" operator stands for the power). The result of the expression evaluation depends on how it is interpreted: "(2^3)^4=8^4" or "2^(3^4)=2^81". Left associativity means that operators are grouped from left to right (the first case), right associativity means grouping from right to left (the second case). === Syntax rules for the operators === TechEditor supports: * basic algebraic operators: "+", "-", "*", "/", "^" * logical operators: "&", "\", "¬" * relational operators: "=", ">", "<", "≤", "≥", "≡", "≠", "≈" There are also some special operators those can be used in advanced cases. TechEditor introduces the following syntax rules for the operators: * algebraic binary operators have precedence as determined with common math rules; * relational operators (binary) have lower precedence than algebraic ones; * binary logical operators have lower precedence than relational ones; * arrow operators (binary) have higher precedence than power operator; * unary operators have higher precedence than binary operators; * postfix operators have higher precedence than prefix operators; * binary operators are all left-associative. Total list of defined operators can be found in Appendix A. ==== Functions ==== Syntactically a function is a named operation with some data value(s) called argument(s). An example is the sine function "sin(x)", where "sin" is the name of the function and "x" is the argument. The function name determines what operation is performed with the argument. \\ \\ In addition to arguments, a function can have parameters. For example, the logarithm of "a" to base "b" function logb(a) has one argument "a" and one parameter "b". Semantically parameters have the same meaning as arguments have — data values on which the operation is performed. Syntactically (in TechEditor) parameters are enclosed in braces "{}". === Syntax rules for functions === General rules for functions: * function arguments are enclosed in parentheses "()"; * function parameters are enclosed in braces "{}"; * function arguments and parameters are separated by spaces " "; * if some function has no parameter, parameter braces are not mandatory; * argument parentheses are always mandatory; * a function can have many parameters and/or many arguments; * there can be many functions with the same name but different number and/or type of arguments and/or parameters. === Function examples === Some examples of syntactically correct function expressions: * max(a b) — maximum function of two arguments; * random() — random function with no arguments; * log{b}(a) — logarithm of "a" to base "b" (one parameter "b", one argument "a"); * P{n m}(x) — associated Legendre function (two parameters "n" and "m", one argument "x"). Total list of functions in TechEditor can be found in Appendix A. ===== Structured data ===== ==== Indexing ==== TechEditor allows using indexing in expressions. Indexing is a method of accessing separate elements of a structured data. An example of a structured data is the array. Each array element has an unique index (or several indexes) by which the element value is accessed. \\ \\ By syntax rules of TechEditor, the indexes are written in square brackets "[]". For example, the i-th array element can be written as "A[i]". For multiple indexes, each index must be written in separate brackets. For example, a matrix element can be written as "M[i][j]". \\ \\ TechEditor syntax rules allow slicing implementation. Slicing is a method to get some part of a structured data, which is also a structure. Slicing syntax is implemented via index omitting. Let we have a matrix (two-dimensional array) "M". Then, according to the slicing syntax, "M[i][]" is the i-th matrix’ row and "M[][j]" is the j-th matrix’ column. The "trail" indexes can be omitted with their brackets. Thus, the matrix’ row can be written as "M[i]" (which is equivalent to "M[i][]" of the previous example). \\ \\ General indexing rules: * indexing can be applied to variables only, the variables must implement indexing interface; * many indexes allowed, each index must be enclosed in separate brackets "[]"; * all index expressions must return values of real type only, the values must be close to integer numbers; * some indexes can be omitted that means slicing, slicing can only be applied to variables those implement slicing interface. The array variables can contain data of any type and have default indexing and slicing implementation for arrays up to the third dimension. ==== Arrays ==== TechEditor supports using array expressions. Array expression is a structured expression that contains other expressions as its components. An example of array expression is vector — one-dimensional set of ordered items. Array expressions has the dimension — the number of indexes by which the components of the array are ordered. \\ \\ By syntax rules of TechEditor, the array expression must be enclosed by square brackets "[]" and its components are separated by spaces. For example, the vector expression with three components can be written as "[i+1 j*2 k]". For multiple dimensions, the components for each dimension must be written in separate brackets. For example, the 2x3 matrix expression can be written as "[[a b c] [d e f]]". Only rectangular array expressions allowed. \\ \\ General rules for array expressions: * array expressions enclosed with square brackets; * each dimension of array expression must be enclosed with its own brackets; * array expression’s components are separated by spaces; * only rectangular array expressions allowed. TechEditor supports vector and matrix expressions for boolean, real, and complex components. ===== Syntax summary ===== * Any math expression can contain literals, arrays, variables, operators, functions and indexing. * Real and complex literals supported. Some common named math constants supported, like Euler number, Pi. * Variable names can include only alphanumeric symbols and underscore symbol. * Only predefined operators can be used in expressions, new operators cannot be defined. * Operations are performed in order of the precedence. Operations order can be changed using parentheses "()". * Functions have parameters and arguments. Parameters are enclosed in braces "{}", arguments are enclosed in parentheses "()". Parameters and arguments are separated by spaces " ". * Indexing can only be applied to variables those implement special interface. Indexes are enclosed in brackets "[]" (each index in separate brackets). Slicing is implemented by omitting some of the indexes. * Array expressions enclosed with square brackets for each dimension. Array components are separated by spaces. Only rectangular arrays allowed. <text type="warning"> This section is under development. </text> </pane> </tabs> Last modified: 20.08.2023 23:%iby dystlab-wiki-admin