TechEditor використовує відкриту текстову нотацію. Це означає, що всі математичні вирази набираються простим текстом. Це підвищує інтероперабельність програми і надає широкі можливості для взаємодії з іншими пакетами (наприклад, MS Excel), але вимагає уважності щодо синтаксису та правил написання формул.
Математичні вирази можуть містити:
Літерали, змінні та функції в TechEditor можуть бути наступних типів:
Літерал це безіменна константа або символ, що має незмінне значення. 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 має наступні попередньо визначені константи:
Змінна це іменований параметр математичної моделі. Ім'я змінної може містити лише алфавітно-цифрові символи та символ підкреслення (першим символом завжди має бути літера). 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” logb(a) має один аргумент “a” та один параметр “b”. За семантикою, параметри ідентичні аргументам, адже також визначають операції над даними. В TechEditor параметри функцій записуються у фігурних дужках “{}”.
Основні правила, які визначають роботу функцій в математичній моделі TechEditor:
Ось приклади деяких синтаксично коректних функцій:
Повний перелік функцій можна знайти в Додатку А.
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:
The array variables can contain data of any type and have default indexing and slicing implementation for arrays up to the third dimension.
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 2×3 matrix expression can be written as “a b c] [d e f”. Only rectangular array expressions allowed.
General rules for array expressions:
TechEditor supports vector and matrix expressions for boolean, real, and complex components.
В прикладі показано, що математична модель допускає одночасне використання змінної і функції з ім'ям “sin”.
sin:=4.5 sin(90*Pi/180) =1 2*sin =9
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 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”.
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”.
TechEditor supports the following constants:
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.
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.
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).
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).
TechEditor supports:
There are also some special operators those can be used in advanced cases. TechEditor introduces the following syntax rules for the operators:
Total list of defined operators can be found in Appendix A.
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 “{}”.
General rules for functions:
Some examples of syntactically correct function expressions:
Total list of functions in TechEditor can be found in Appendix A.
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:
The array variables can contain data of any type and have default indexing and slicing implementation for arrays up to the third dimension.
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 2×3 matrix expression can be written as “a b c] [d e f”. Only rectangular array expressions allowed.
General rules for array expressions:
TechEditor supports vector and matrix expressions for boolean, real, and complex components.
This section is under development.