Maxima Manual

Short Table of Contents

Table of Contents

Next: , Previous: (dir), Up: (dir)   [Contents][Index]

Maxima – система аналитических вычислений, написанная на Lisp.

Maxima происходит от системы аналитических вычислений Macsyma, разрабатывавшейся в MIT в период 1968 по 1982 в рамках проекта MAC. В 1982 году MIT передала копию исходного кода Macsyma Министерству энергетики США (Department of Energy). Данная версия известна как DOE Macsyma. Копия DOE Macsyma поддерживалась профессором Вильямом Шелтером (William F. Schelter) из Техасского Университета с 1982 года вплоть до его смерти в 2001 году. В 1998 году Шелтер получил разрешение выпустить исходный код DOE Macsyma под публичной лицензией GNU и в 2000 году инициировал проект Maxima на SourceForge для поддержки и развития DOE Macsyma, переименованной в Maxima.


Next: , Previous: Top, Up: Top   [Contents][Index]

1 Введение в Maxima

Запустите Maxima с помощью команды "maxima". Maxima покажет информацию о версии и приглашение на ввод. Завершайте каждую команду Maxima символом ";" (или "$" в случае, если хотите подавить вывод команды). Завершите сессию командой "quit();". Пример сессии:

[wfs@chromium]$ maxima
Maxima 5.9.1 http://maxima.sourceforge.net
Using Lisp CMU Common Lisp 19a
Distributed under the GNU Public License. See the file COPYING.
Dedicated to the memory of William Schelter.
This is a development version of Maxima. The function bug_report()
provides bug reporting information.
(%i1) factor(10!);
                            8  4  2
(%o1)                      2  3  5  7
(%i2) expand ((x + y)^6);
       6        5       2  4       3  3       4  2      5      6
(%o2) y  + 6 x y  + 15 x  y  + 20 x  y  + 15 x  y  + 6 x  y + x
(%i3) factor (x^6 - 1);
                              2            2
(%o3)       (x - 1) (x + 1) (x  - x + 1) (x  + x + 1)
(%i4) quit();
[wfs@chromium]$

Maxima может искать в info страницах. Используйте команду describe для того, чтобы получить информацию об определенной команде или показать все команды и переменные, содержащие в имени заданную строку. Знак вопроса ? (точный поиск) и двойной вопрос ?? (поиск по подстроке) являются аббревиатурами для команды describe:

(%i1) ?? integ
 0: Functions and Variables for Elliptic Integrals
 1: Functions and Variables for Integration
 2: Introduction to Elliptic Functions and Integrals
 3: Introduction to Integration
 4: askinteger  (Functions and Variables for Simplification)
 5: integerp  (Functions and Variables for Miscellaneous Options)
 6: integer_partitions  (Functions and Variables for Sets)
 7: integrate  (Functions and Variables for Integration)
 8: integrate_use_rootsof  (Functions and Variables for Integration)
 9: integration_constant_counter  (Functions and Variables for
    Integration)
 10: nonnegintegerp  (Functions and Variables for linearalgebra)
Enter space-separated numbers, `all' or `none': 5 4

 -- Function: integerp (<expr>)
     Returns `true' if <expr> is a literal numeric integer, otherwise
     `false'.

     `integerp' returns false if its argument is a symbol, even if the
     argument is declared integer.

     Examples:

          (%i1) integerp (0);
          (%o1)                         true
          (%i2) integerp (1);
          (%o2)                         true
          (%i3) integerp (-17);
          (%o3)                         true
          (%i4) integerp (0.0);
          (%o4)                         false
          (%i5) integerp (1.0);
          (%o5)                         false
          (%i6) integerp (%pi);
          (%o6)                         false
          (%i7) integerp (n);
          (%o7)                         false
          (%i8) declare (n, integer);
          (%o8)                         done
          (%i9) integerp (n);
          (%o9)                         false


 -- Function: askinteger (<expr>, integer)
 -- Function: askinteger (<expr>)
 -- Function: askinteger (<expr>, even)
 -- Function: askinteger (<expr>, odd)
     `askinteger (<expr>, integer)' attempts to determine from the
     `assume' database whether <expr> is an integer.  `askinteger'
     prompts the user if it cannot tell otherwise, and attempt to
     install the information in the database if possible.  `askinteger
     (<expr>)' is equivalent to `askinteger (<expr>, integer)'.

     `askinteger (<expr>, even)' and `askinteger (<expr>, odd)'
     likewise attempt to determine if <expr> is an even integer or odd
     integer, respectively.

(%o1)                                true

Для того, чтобы использовать результат в последующих вычислениях, Вы можете присвоить его переменной или ссылаться на него через автоматически создаваемую ссылку. Кроме того, символ % относится к последнему вычисленному результату:

(%i1) u: expand ((x + y)^6);
       6        5       2  4       3  3       4  2      5      6
(%o1) y  + 6 x y  + 15 x  y  + 20 x  y  + 15 x  y  + 6 x  y + x
(%i2) diff (u, x);
         5         4       2  3       3  2       4        5
(%o2) 6 y  + 30 x y  + 60 x  y  + 60 x  y  + 30 x  y + 6 x
(%i3) factor (%o2);
                                    5
(%o3)                      6 (y + x)

Maxima знает о комплексных числах и численных константах:

(%i1) cos(%pi);
(%o1)                          - 1
(%i2) exp(%i*%pi);
(%o2)                          - 1

Maxima может производить дифференциальные и интегральные вычисления:

(%i1) u: expand ((x + y)^6);
       6        5       2  4       3  3       4  2      5      6
(%o1) y  + 6 x y  + 15 x  y  + 20 x  y  + 15 x  y  + 6 x  y + x
(%i2) diff (%, x);
         5         4       2  3       3  2       4        5
(%o2) 6 y  + 30 x y  + 60 x  y  + 60 x  y  + 30 x  y + 6 x
(%i3) integrate (1/(1 + x^3), x);
                                  2 x - 1
                2            atan(-------)
           log(x  - x + 1)        sqrt(3)    log(x + 1)
(%o3)    - --------------- + ------------- + ----------
                  6             sqrt(3)          3

Maxima может решать линейные системы и кубические уравнения:

(%i1) linsolve ([3*x + 4*y = 7, 2*x + a*y = 13], [x, y]);
                        7 a - 52        25
(%o1)              [x = --------, y = -------]
                        3 a - 8       3 a - 8
(%i2) solve (x^3 - 3*x^2 + 5*x = 15, x);
(%o2)       [x = - sqrt(5) %i, x = sqrt(5) %i, x = 3]

Maxima может решать нелинейные системы уравнений. Напомним, что если Вы не хотите, чтобы результат печатался, Вы можете завершить ввод символом $ вместо ;.

(%i1) eq_1: x^2 + 3*x*y + y^2 = 0$
(%i2) eq_2: 3*x + y = 1$
(%i3) solve ([eq_1, eq_2]);
              3 sqrt(5) + 7      sqrt(5) + 3
(%o3) [[y = - -------------, x = -----------], 
                    2                 2

                               3 sqrt(5) - 7        sqrt(5) - 3
                          [y = -------------, x = - -----------]]
                                     2                   2

Maxima может строить графики одной и более функций:

(%i1) eq_1: x^2 + 3*x*y + y^2 = 0$
(%i2) eq_2: 3*x + y = 1$
(%i3) solve ([eq_1, eq_2]);
              3 sqrt(5) + 7      sqrt(5) + 3
(%o3) [[y = - -------------, x = -----------], 
                    2                 2

                               3 sqrt(5) - 7        sqrt(5) - 3
                          [y = -------------, x = - -----------]]
                                     2                   2
(%i4) kill(labels);
(%o0)                         done
(%i1) plot2d (sin(x)/x, [x, -20, 20]);
(%o1) 
(%i2) plot2d ([atan(x), erf(x), tanh(x)], [x, -5, 5]);
(%o2) 
(%i3) plot3d (sin(sqrt(x^2 + y^2))/sqrt(x^2 + y^2), [x, -12, 12],
      [y, -12, 12]);
(%o3) 

Next: , Previous: Введение в Maxima, Up: Top   [Contents][Index]

2 Работа с ошибками


Up: Работа с ошибками   [Contents][Index]

2.1 Функции и переменные для работы с ошибками

Функция: run_testsuite ()
Функция: run_testsuite (boolean)
Функция: run_testsuite (boolean, boolean)
Функция: run_testsuite (boolean, boolean, list)

Запускает встроенный набор тестов программы Maxima. Тесты, дающие ожидаемый результат, рассматриваются как успешные. Сюда относятся также тесты не дающие ожидаемый результат но помеченные как "известные ошибки".

run_testsuite () показывает только неуспешные тесты.

run_testsuite (true) показывает неуспешные тесты и тесты помеченные как известные ошибки.

run_testsuite (true, true) показывает все тесты.

Если задан необязательный третий аргумент, то выполняется указанное подмножество тестов, определяемое списком имен. Полный список тестов хранится в переменной testsuite_files.

Выполнение run_testsuite изменяет окружение Maxima. Обычно тест сначала выполняет kill, чтобы восстановить стандартное окружение (окружение без определенных пользователем функций и переменных), и после этого определяет функции и переменные, необходимые для теста.

run_testsuite возвращает done.

Управляющая переменная: testsuite_files

testsuite_files набор тестов выполняемых run_testsuite. Это список имен файлов содержащих соответствующие тесты. Если известно, что определенные тесты дают неверный результат, то вместо имени файла используется список, содержащий имя файла и номера заведомо ошибочных тестов.

Например, это часть стандартного набора тестов

 ["rtest13s", ["rtest14", 57, 63]]

которая состоит из тестов находящихся в файлах "rtest13s" и "rtest14". При этом "rtest14" содержит два заведомо ошибочных теста с номерами 57 и 63.

Функция: bug_report ()

Печатает версию Maxima, версию используемого Lisp и ссылку на интернет страницу где можно заполнить сообщение об ошибке. Информация о версиях программ та же, что дается функцией build_info. При заполнении сообщения об ошибке желательно указать данную информацию.

bug_report возвращает пустую строку "".

Функция: build_info ()

Печатает информацию о сборке Maxima.

build_info возвращает пустую строку "".


Next: , Previous: Работа с ошибками, Up: Top   [Contents][Index]

3 Справка


Next: , Previous: Справка, Up: Справка   [Contents][Index]

3.1 Lisp и Maxima

Maxima написана на Lisp, поэтому легко получить доступ к Lisp функциям и переменным из Maxima и наоборот. Lisp и Maxima символы различают с помощью соглашения об именах. Lisp символ, который начинается со знака $ соответствует Maxima символу без знака доллара. Maxima символ, который начинается со знака ? соответствует Lisp символу без знака вопроса. Например, Maxima символ foo соответствует Lisp символу $foo, в то время как Maxima символ ?foo соответствует Lisp символу foo, Заметим, что ?foo записано без пробелов между ? и foo; иначе можно перепутать с describe ("foo").

-, *, и другие специальные знаки в Lisp символах должны быть экранированы \ везде, где они появляются в коде Maxima. Например, Lisp идентификатор *foo-bar* записывается как ?\*foo\-bar\* в Maxima.

Lisp код может быть выполнен из Maxima сессии. Простая строка с Lisp кодом (содержащая одну и более форм) может быть выполнена с помощью специальной команды :lisp. Например,

(%i1) :lisp (foo $x $y)

вызывает Lisp функцию foo с Maxima переменными x и y в качестве аргументов. :lisp конструкция может появляться в интерактивном приглашении или в файле, исполняемом командой batch или demo, но только не в файле исполняемом командами load, batchload, translate_file, или compile_file.

Функция to_lisp() открывает интегративную Lisp сессию. Ввод (to-maxima) закрывает Lisp сессию и возвращает к Maxima.

Lisp функции и переменные, которые, как известно, видны в Maxima как функции и переменные с обычными именами (без специальной пунктуации) должны иметь Lisp имена, начинающиеся со знака $.

Maxima чувствительна к регистру символов, различая буквы в нижнем и верхнем регистрах, в идентификаторах, в то время как Lisp - нет. Существуют некоторые правила, управляющие переводом имен между Lisp и Maxima.

  1. Lisp идентификатор не заключенный в вертикальные черты соответствует Maxima идентификатору в нижнем регистре. Является ли Lisp идентификатор в верхнем, нижнем, или смешанном регистре, регистр игнорируется. То есть, Lisp $foo, $FOO, и $Foo - все соответствуют Maxima foo.
  2. Lisp идентификатор, имеющий все знаки в нижнем или все знаки в верхнем регистре и заключенный в вертикальные черты, соответствует Maxima идентификатору с именем в обратном регистре. То есть, верхний регистр меняется в нижний и нижний регистр - в верхний. Например, Lisp |$FOO| и |$foo| соответствуют Maxima foo и FOO, в указанном порядке.
  3. Lisp идентификатор, который записан в смешанном регистре и заключенный в вертикальные черты соответствует Maxima идентификатору в том же регистре. Например, Lisp |$Foo| соответствует Maxima Foo.

#$ Lisp макрооператор позволяет использовать Maxima выражения в Lisp коде. #$expr$ превращается в Lisp выражение, эквивалентное Maxima выражению expr.

(msetq $foo #$[x, y]$)

Это имеет тот же самый эффект как при вводе:

(%i1) foo: [x, y];

Lisp функция displa печатает выражение в Maxima форме.

(%i1) :lisp #$[x, y, z]$ 
((MLIST SIMP) $X $Y $Z)
(%i1) :lisp (displa '((MLIST SIMP) $X $Y $Z))
[x, y, z]
NIL

Функции, заданные в Maxima не являются обычными Lisp функциями. Lisp функция mfuncall вызывает Maxima функцию. Например:

(%i1) foo(x,y) := x*y$
(%i2) :lisp (mfuncall '$foo 'a 'b)
((MTIMES SIMP) A B)

Некоторые Lisp функции скрыты в Maxima пакете, а именно такие как:

complement, continue, //, float, functionp, array, exp, listen, signum, atan, asin, acos, asinh, acosh, atanh, tanh, cosh, sinh, tan, break и gcd.


Next: , Previous: Lisp и Maxima, Up: Справка   [Contents][Index]

3.2 Сборка мусора

Вычисление в символьном виде имеют тенденцию создавать много “мусора”, и эффективное управление этим мусором может стать решающим для успешного выполнения некоторых программ.

Под GCL, на UNIX системах, где доступны вызовы системы “mprotect”, (включая SUN OS 4.0 и некоторые версии BSD) доступна прямая сборка мусора. Это ограничивает сборку страницами, в которые недавно производилась запись. См. документацию по GCL по ключевым словам ALLOCATE и GBC. На уровне Lisp, установка (setq si::*notify-gbc* t) поможет вам определить, какие области памяти, возможно, требуют больше пространства.


Next: , Previous: Сборка мусора, Up: Справка   [Contents][Index]

3.3 Документация

Руководство пользователя Maxima можно просматривать в различных форматах. Из интерактивного приглашения Maxima, руководство пользователя просматривается как обычный текст командой ? (то есть, функция describe). Руководство пользователя просматривается как info гипертекст с помощью info просмотрщиком и как веб-страница с помощью обычного веб-браузера.

example показывает примеры для многих Maxima функций. Например,

(%i1) example (integrate);

дает

(%i2) test(f):=block([u],u:integrate(f,x),ratsimp(f-diff(u,x)))
(%o2) test(f) := block([u], u : integrate(f, x), 

                                         ratsimp(f - diff(u, x)))
(%i3) test(sin(x))
(%o3)                           0
(%i4) test(1/(x+1))
(%o4)                           0
(%i5) test(1/(x^2+1))
(%o5)                           0

и дополнительный вывод.


Previous: Документация, Up: Справка   [Contents][Index]

3.4 Справочная система

Функция: demo (filename)

вычисляет Maxima выражения в filename и показывает результаты. demo останавливается после вычислений каждого выражения и продолжает после того, как пользователь нажмет “Enter”. (Если запущена Xmaxima, demo необходимо перед вводом ставить ;).

demo просматривает список директорий file_search_demo, чтобы найти filename. Если файл имеет расширение dem, то его можно опустить. См. также file_search.

demo вычисляет свои аргументы. demo возвращает имя демонстрационного файла.

Пример:

(%i1) demo ("disol");

batching /home/wfs/maxima/share/simplification/disol.dem
 At the _ prompt, type ';' followed by enter to get next demo
(%i2)                      load("disol")

_
(%i3)           exp1 : a (e (g + f) + b (d + c))
(%o3)               a (e (g + f) + b (d + c))

_
(%i4)                disolate(exp1, a, b, e)
(%t4)                         d + c

(%t5)                         g + f

(%o5)                   a (%t5 e + %t4 b)

_
(%i5) demo ("rncomb");

batching /home/wfs/maxima/share/simplification/rncomb.dem
 At the _ prompt, type ';' followed by enter to get next demo
(%i6)                     load("rncomb")

_
                             z         x
(%i7)               exp1 : ----- + ---------
                           y + x   2 (y + x)
                          z         x
(%o7)                   ----- + ---------
                        y + x   2 (y + x)

_
(%i8)                     combine(exp1)
                          z         x
(%o8)                   ----- + ---------
                        y + x   2 (y + x)

_
(%i9)                     rncombine(%)
                             2 z + x
(%o9)                       ---------
                            2 (y + x)

_
                             d   c   b   a
(%i10)                exp2 : - + - + - + -
                             3   3   2   2
                          d   c   b   a
(%o10)                    - + - + - + -
                          3   3   2   2

_
(%i11)                    combine(exp2)
                      2 d + 2 c + 3 (b + a)
(%o11)                ---------------------
                                6

_
(%i12)                   rncombine(exp2)
                      2 d + 2 c + 3 b + 3 a
(%o12)                ---------------------
                                6

_
(%i13) 
Функция: describe (string)
Функция: describe (string, exact)
Функция: describe (string, inexact)

describe(string) эквивалентно describe(string, exact).

describe(string, exact) ищет элемент, с заголовком равным (независимо от регистра) string, если такой элемент есть.

describe(string, inexact) ищет все документированные элементы, которые содержат string в своих заголовках. Если есть более чем один такой элемент, Maxima спросит пользователя выбрать элемент или несколько элементов для отображения.

В интерактивном приглашении, ? foo (с пробелом между ? и foo) эквивалентно describe("foo", exact), и ?? foo эквивалентно describe("foo", inexact).

describe("", inexact) дает список всех тем, документированных в руководстве пользователя.

describe не вычисляет свой аргумент. describe возвращает true если документация найдена, false в противном случае.

См. также Документация.

Пример:

(%i1) ?? integ
 0: Functions and Variables for Elliptic Integrals
 1: Functions and Variables for Integration
 2: Introduction to Elliptic Functions and Integrals
 3: Introduction to Integration
 4: askinteger  (Functions and Variables for Simplification)
 5: integerp  (Functions and Variables for Miscellaneous Options)
 6: integer_partitions  (Functions and Variables for Sets)
 7: integrate  (Functions and Variables for Integration)
 8: integrate_use_rootsof  (Functions and Variables for
    Integration)
 9: integration_constant_counter  (Functions and Variables for
    Integration)
 10: nonnegintegerp  (Functions and Variables for linearalgebra)
Enter space-separated numbers, `all' or `none': 7 8

 -- Function: integrate (<expr>, <x>)
 -- Function: integrate (<expr>, <x>, <a>, <b>)
     Attempts to symbolically compute the integral of <expr> with
     respect to <x>.  `integrate (<expr>, <x>)' is an indefinite
     integral, while `integrate (<expr>, <x>, <a>, <b>)' is a
     definite integral, [...]
     
 -- Option variable: integrate_use_rootsof
     Default value: `false'

     When `integrate_use_rootsof' is `true' and the denominator of
     a rational function cannot be factored, `integrate' returns
     the integral in a form which is a sum over the roots (not yet
     known) of the denominator.
     [...]

В этом примере, были выбраны элементы 7 и 8 (вывод команды сокращен, что обозначено [...]). Все элементы или ни один из элементов могут быть выбраны при помощи all или none, что можно также сократить до a и n соотвественно.

Функция: example (topic)
Функция: example ()

example (topic) показывает некоторые примеры для символа topic (не строки). Большинство topic являются именами функций. example () возвращает список всех доступных topic.

Имя файла содержащего эти примеры задано глобальной переменной manual_demo, которая исходно равна "manual.demo".

example не вычисляет свой аргумент. example возвращает done только если нет ошибки или отсутствия аргумента. example возвращает список всех подходящих тем.

Примеры:

(%i1) example (append);
(%i2) append([x+y,0,-3.2],[2.5E+20,x])
(%o2)             [y + x, 0, - 3.2, 2.5E+20, x]
(%o2)                         done
(%i3) example (coeff);
(%i4) coeff(b+tan(x)+2*a*tan(x) = 3+5*tan(x),tan(x))
(%o4)                      2 a + 1 = 5
(%i5) coeff(1+x*%e^x+y,x,0)
(%o5)                         y + 1
(%o5)                         done

Next: , Previous: Справка, Up: Top   [Contents][Index]

4 Командная строка


Next: , Previous: Командная строка, Up: Командная строка   [Contents][Index]

4.1 Введение в командную строку

Оператор: '

Оператор "одиночная кавычка" ' предотвращает вычисление, иными словами "экранирует" свой аргумент.

Примененный к символу, оператор "одиночная кавычка" предотвращает вычисление этого символа.

Примененный к вызову функции, оператор "одиночная кавычка" предотвращает вычисление этой функции, но не вычисление ее аргументов (если оно не предотвращено по другим причинам). Результатом является невычисляемая (noun) форма вызова функции.

Примененный к выражению в скобках, предотвращает вычисление всех функций и символов внутри скобок. Например, '(f(x)) означает – не вычислять выражение f(x), тогда как 'f(x) (кавычка примененная к f а не к f(x)) означает – невычисляемая форма f, примененная к [x].

Одиночная кавычка не предотвращает упрощение.

Когда глобальный флаг noundisp имеет значение true, невычисляемые формы функций выводятся с одиночной кавычкой. Этот переключатель всегда установлен равным true при печати определений функций.

См. также оператор "кавычка-кавычка" '' и nouns.

Примеры:

Примененный к символу, оператор "одиночная кавычка" предотвращает вычисление этого символа.

(%i1) aa: 1024;
(%o1)                         1024
(%i2) aa^2;
(%o2)                        1048576
(%i3) 'aa^2;
                                 2
(%o3)                          aa
(%i4) ''%;
(%o4)                        1048576

Примененный к вызову функции, оператор "одиночная кавычка" предотвращает вычисление этой функции. Результатом является невычисляемая форма вызова функции.

(%i1) x0: 5;
(%o1)                           5
(%i2) x1: 7;
(%o2)                           7
(%i3) integrate (x^2, x, x0, x1);
                               218
(%o3)                          ---
                                3
(%i4) 'integrate (x^2, x, x0, x1);
                             7
                            /
                            [   2
(%o4)                       I  x  dx
                            ]
                            /
                             5
(%i5) %, nouns;
                               218
(%o5)                          ---
                                3

Примененный к выражению в скобках, предотвращает вычисление всех функций и символов внутри скобок.

(%i1) aa: 1024;
(%o1)                         1024
(%i2) bb: 19;
(%o2)                          19
(%i3) sqrt(aa) + bb;
(%o3)                          51
(%i4) '(sqrt(aa) + bb);
(%o4)                     bb + sqrt(aa)
(%i5) ''%;
(%o5)                          51

Одиночная кавычка не предотвращает упрощение.

(%i1) sin (17 * %pi) + cos (17 * %pi);
(%o1)                          - 1
(%i2) '(sin (17 * %pi) + cos (17 * %pi));
(%o2)                          - 1
Оператор: ''

Оператор "кавычка-кавычка" '' (две одиночные кавычки) изменяет вычисление вводимого выражения.

Примененный к выражению общего вида expr, кавычка-кавычка вызывает подстановку значения expr вместо expr в вводимом выражении.

Примененный к оператору в выражении, кавычка-кавычка изменяет невычисляемую форму оператора на вычисляемую (если она не является таковой).

Оператор кавычка-кавычка применяется при синтаксическом анализе вводимого выражения и не сохраняется как часть этого выражения. Оператор кавычка-кавычка применяется сразу после распознавания и не может быть экранирован.

Оператор кавычка-кавычка распознается функциями batch и load.

См. также оператор "кавычка" ' и nouns.

Примеры:

Примененный к выражению общего вида expr, кавычка-кавычка вызывает подстановку значения expr вместо expr в вводимом выражении.

(%i1) expand ((a + b)^3);
                     3        2      2      3
(%o1)               b  + 3 a b  + 3 a  b + a
(%i2) [_, ''_];
                         3    3        2      2      3
(%o2)     [expand((b + a) ), b  + 3 a b  + 3 a  b + a ]
(%i3) [%i1, ''%i1];
                         3    3        2      2      3
(%o3)     [expand((b + a) ), b  + 3 a b  + 3 a  b + a ]
(%i4) [aa : cc, bb : dd, cc : 17, dd : 29];
(%o4)                   [cc, dd, 17, 29]
(%i5) foo_1 (x) := aa - bb * x;
(%o5)                 foo_1(x) := aa - bb x
(%i6) foo_1 (10);
(%o6)                      cc - 10 dd
(%i7) ''%;
(%o7)                         - 273
(%i8) ''(foo_1 (10));
(%o8)                         - 273
(%i9) foo_2 (x) := ''aa - ''bb * x;
(%o9)                 foo_2(x) := cc - dd x
(%i10) foo_2 (10);
(%o10)                        - 273
(%i11) [x0 : x1, x1 : x2, x2 : x3];
(%o11)                    [x1, x2, x3]
(%i12) x0;
(%o12)                         x1
(%i13) ''x0;
(%o13)                         x2
(%i14) '' ''x0;
(%o14)                         x3

Примененный к оператору в выражении, кавычка-кавычка изменяет невычисляемую форму оператора на вычисляемую (если она не является таковой).

(%i1) sin (1);
(%o1)                        sin(1)
(%i2) ''sin (1);
(%o2)                    0.8414709848079
(%i3) declare (foo, noun);
(%o3)                         done
(%i4) foo (x) := x - 1729;
(%o4)                 ''foo(x) := x - 1729
(%i5) foo (100);
(%o5)                       foo(100)
(%i6) ''foo (100);
(%o6)                        - 1629

Оператор кавычка-кавычка применяется при синтаксическом анализе вводимого выражения и не сохраняется как часть этого выражения.

(%i1) [aa : bb, cc : dd, bb : 1234, dd : 5678];
(%o1)                 [bb, dd, 1234, 5678]
(%i2) aa + cc;
(%o2)                        dd + bb
(%i3) display (_, op (_), args (_));
                           _ = cc + aa

                         op(cc + aa) = +

                    args(cc + aa) = [cc, aa]

(%o3)                         done
(%i4) ''(aa + cc);
(%o4)                         6912
(%i5) display (_, op (_), args (_));
                           _ = dd + bb

                         op(dd + bb) = +

                    args(dd + bb) = [dd, bb]

(%o5)                         done

Оператор кавычка-кавычка вызывает вычисление в случаях когда оно заблокировано, таких как определения функций, лямбда-выражения и выражения, экранированные оператором кавычка '.

(%i1) foo_1a (x) := ''(integrate (log (x), x));
(%o1)               foo_1a(x) := x log(x) - x
(%i2) foo_1b (x) := integrate (log (x), x);
(%o2)           foo_1b(x) := integrate(log(x), x)
(%i3) dispfun (foo_1a, foo_1b);
(%t3)               foo_1a(x) := x log(x) - x

(%t4)           foo_1b(x) := integrate(log(x), x)

(%o4)                      [%t3, %t4]
(%i4) integrate (log (x), x);
(%o4)                     x log(x) - x
(%i5) foo_2a (x) := ''%;
(%o5)               foo_2a(x) := x log(x) - x
(%i6) foo_2b (x) := %;
(%o6)                    foo_2b(x) := %
(%i7) dispfun (foo_2a, foo_2b);
(%t7)               foo_2a(x) := x log(x) - x

(%t8)                    foo_2b(x) := %

(%o8)                      [%t7, %t8]
(%i8) F : lambda ([u], diff (sin (u), u));
(%o8)             lambda([u], diff(sin(u), u))
(%i9) G : lambda ([u], ''(diff (sin (u), u)));
(%o9)                  lambda([u], cos(u))
(%i10) '(sum (a[k], k, 1, 3) + sum (b[k], k, 1, 3));
(%o10)         sum(b , k, 1, 3) + sum(a , k, 1, 3)
                    k                  k
(%i11) '(''(sum (a[k], k, 1, 3)) + ''(sum (b[k], k, 1, 3)));
(%o11)             b  + a  + b  + a  + b  + a
                    3    3    2    2    1    1

Previous: Введение в командную строку, Up: Командная строка   [Contents][Index]

4.2 Функции и переменные для работы в командной строке

Функция: alias (new_name_1, old_name_1, ..., new_name_n, old_name_n)

создает альтернативное имя для пользовательской или системной функции, переменной, массива и т.п. Данная функция может иметь любое число парных аргументов.

Управляющая переменная: debugmode

Значение по умолчанию: false

Если во время работы Maxima возникла ошибка, Maxima запускает отладчик если значение переключателя debugmode равно true. В отладчике пользователь может исследовать значения стека, установить точки останова, просматривать код и т.д. См. debugging для списка команд отладчика.

Отладчик Maxima, включаемый с помощью debugmode, не обрабатывает ошибки на уровне Lisp.

Функция: ev (expr, arg_1, ..., arg_n)

Вычисляет выражение expr в окружении определяемом аргументами arg_1, ..., arg_n. Данные аргументы могут быть переключателями (логические флаги), присваиваниями, уравнениями и функциями. ev возвращает результат вычисления (выражение).

Вычисление осуществляется в несколько шагов.

  1. Сначала окружение устанавливается в соответствии с аргументами, которые могут быть одним из следующего:
    • simp вызывает упрощение выражения expr вне зависимости от текущего значения переключателя simp (отключает упрощение если равен false).
    • noeval отключает вычисление для данной стадии ev (см. шаг (4) ниже). Это может быть полезно в комбинации с другими переключателями и вызывает повторное упрощение expr без перевычисления.
    • nouns вызывает вычисление невычисляемых (noun) форм (обычно это невычисляемые функции, такие как 'integrate или 'diff) в expr.
    • expand вызывает раскрытие скобок.
    • expand (m,n) вызывает раскрытие скобок при maxposex и maxnegex равным m и n соответственно.
    • detout при вычислении обратных матриц в expr, сохраняет определитель матрицы как общий множитель вместо того чтобы делить на него каждый элемент матрицы в отдельности.
    • diff вызывает вычисление всех производных в expr.
    • derivlist (x, y, z, ...) вызовет вычисление производных только относительно указанных переменных.
    • float вызывает преобразование нецелых рациональных чисел в числа с плавающей точкой.
    • numer вызывает численное вычисление математических функций (включая экспоненты), имеющих числовые аргументы. Вызывает замену переменных, имеющих числовые значения (см. numerval), этими значениями. Устанавливает значение переключателя float равным true.
    • pred вызывает вычисление предикатов (выражений, значение которых true или false).
    • eval вызывает дополнительное пост-вычисление expr (см. шаг (5) ниже). eval может встречаться несколько раз. Для каждого eval выражение вычисляется еще раз.
    • A, где A есть атом, являющийся флагом вычисления (см. evflag), устанавливает значение A равным true в процессе вычисления expr.
    • V: expression (или альтернативно V=expression) присваивает V значение expression в процессе вычисления expr. Если V является управляющей переменной (опцией) Maxima, тогда значение expression используется в качестве значения опции в процессе вычисления expr. Если имеется более одного аргумента ev данного типа, то присваивание осуществляется параллельно. Если V является не атомарным выражением, то вместо присваивания осуществляется подстановка.
    • F, где F есть имя функции, являющейся функцией вычисления (см. evfun) вызывает применение F к expr.
    • Любые другие имена функций (скажем sum) вызывают вычисление этих функций в expr, так как если бы они имели вычисляемую форму.
    • Кроме того, встречающаяся в expr функция (скажем F(x)) может быть локально определена для вычисления expr, путем задания аргумента в форме F(x) := expression.
    • Если в качестве аргумента указан любой, не указанный выше атом, или переменная с индексом, или выражение с индексом, то данный аргумент вычисляется. Если результатом вычисления является уравнение или присваивание, то выполняется соответствующее присваивание или подстановка. Если результатом вычисления является список, то элементы этого списка трактуются как дополнительные аргументы ev. Это, в частности, позволяет использовать список уравнений (например [X=1, Y=A**2]), или список имен уравнений (например [%t1, %t2], где %t1 и %t2 являются результатом работы функции solve.

    Аргументы ev могут быть указаны в произвольном порядке за исключением уравнений, которые выполняются последовательно слева направо, и составных вычисляющих функций (например ev (expr, ratsimp, realpart) выполняется как realpart (ratsimp (expr))).

    Переключатели simp, numer, float и pred могут быть установлены локально в блоке, или глобально. В последнем случае они будут действовать до переопределения.

    Если выражение expr является каноническим рациональным выражением (КРВ, canonical rational expression (CRE)), тогда результатом ev тоже является КРВ, если только переключатели numer и float оба не равны true.

  2. На шаге (1), составляется список не-индексированных переменных входящих в левые части аргументов, являющихся уравнениями, или в значения аргументов, если эти значения являются уравнениями. Переменные (индексированные, которые не имеют соответствующих функций массивов, и не-индексированные) в выражении expr заменяются на свои глобальные значения, за исключением тех, которые входят в вышеуказанный список. Обычно, expr это просто метка % (как %i2 в примере ниже), так что на данном шаге просто получается выражение, обозначаемое данной меткой.
  3. Если среди аргументов имеются подстановки, то они выполняются.
  4. Полученное выражение снова вычисляется (если одним из аргументов не является noeval) и упрощается в соответствии с заданными аргументами. Все вызовы функций в expr выполняются после вычисления переменных. Таким образом ev(F(x)) трактуется как F(ev(x)).
  5. Для каждого eval, шаги (3) и (4) повторяются.

Примеры:

(%i1) sin(x) + cos(y) + (w+1)^2 + 'diff (sin(w), w);
                                     d                    2
(%o1)              cos(y) + sin(x) + -- (sin(w)) + (w + 1)
                                     dw
(%i2) ev (%, sin, expand, diff, x=2, y=1);
                          2
(%o2)           cos(w) + w  + 2 w + cos(1) + 1.909297426825682

Имеется альтернативный синтаксис функции ev, который может использоваться только на верхнем уровне: аргументы ev() перечисляются через запятую после выражения. Т.е. можно просто написать

expr, arg_1, ..., arg_n

Такая конструкция недопустима как часть другого выражения, функции, блока и т.п.

Обратите внимание на параллельное присваивание в следующих примерах.

(%i3) programmode: false;
(%o3)                                false
(%i4) x+y, x: a+y, y: 2;
(%o4)                              y + a + 2
(%i5) 2*x - 3*y = 3$
(%i6) -3*x + 2*y = -4$
(%i7) solve ([%o5, %o6]);
Solution

                                          1
(%t7)                               y = - -
                                          5

                                         6
(%t8)                                x = -
                                         5
(%o8)                            [[%t7, %t8]]
(%i8) %o6, %o8;
(%o8)                              - 4 = - 4
(%i9) x + 1/x > gamma (1/2);
                                   1
(%o9)                          x + - > sqrt(%pi)
                                   x
(%i10) %, numer, x=1/2;
(%o10)                      2.5 > 1.772453850905516
(%i11) %, pred;
(%o11)                               true
Свойство: evflag

Если символ x имеет свойство evflag, то выражения ev(expr, x) и expr, x (в интерактивной командной строке) эквивалентны ev(expr, x = true). Т.е. x имеет значение true в процессе вычисления expr.

Выражение declare(x, evflag) устанавливает свойство evflag для переменной x.

Следующие переключатели имеют по умолчанию свойство evflag: algebraic, cauchysum, demoivre, dotscrules, %emode, %enumer, exponentialize, exptisolate, factorflag, float, halfangles, infeval, isolate_wrt_times, keepfloat, letrat, listarith, logabs, logarc, logexpand, lognegint, lognumer, m1pbranch, numer_pbranch, programmode, radexpand, ratalgdenom, ratfac, ratmx, ratsimpexpons, simp, simpsum, sumexpand и trigexpand.

Примеры:

(%i1) sin (1/2);
                                 1
(%o1)                        sin(-)
                                 2
(%i2) sin (1/2), float;
(%o2)                   0.479425538604203
(%i3) sin (1/2), float=true;
(%o3)                   0.479425538604203
(%i4) simp : false;
(%o4)                         false
(%i5) 1 + 1;
(%o5)                         1 + 1
(%i6) 1 + 1, simp;
(%o6)                           2
(%i7) simp : true;
(%o7)                         true
(%i8) sum (1/k^2, k, 1, inf);
                            inf
                            ====
                            \     1
(%o8)                        >    --
                            /      2
                            ====  k
                            k = 1
(%i9) sum (1/k^2, k, 1, inf), simpsum;
                                 2
                              %pi
(%o9)                         ----
                               6
(%i10) declare (aa, evflag);
(%o10)                        done
(%i11) if aa = true then YES else NO;
(%o11)                         NO
(%i12) if aa = true then YES else NO, aa;
(%o12)                         YES
Свойство: evfun

Если функция F имеет свойство evfun, то выражения ev(expr, F) и expr, F (в интерактивной командной строке) эквивалентны F(ev(expr)).

Если заданы две или более evfun функций F, G, то функции применяются в порядке задания.

Выражение declare(F, evfun) устанавливает свойство evfun для функции F.

Следующие функции имеют по умолчанию свойство evfun: bfloat, factor, fullratsimp, logcontract, polarform, radcan, ratexpand, ratsimp, rectform, rootscontract, trigexpand и trigreduce.

Примеры:

(%i1) x^3 - 1;
                              3
(%o1)                        x  - 1
(%i2) x^3 - 1, factor;
                                2
(%o2)                 (x - 1) (x  + x + 1)
(%i3) factor (x^3 - 1);
                                2
(%o3)                 (x - 1) (x  + x + 1)
(%i4) cos(4 * x) / sin(x)^4;
                            cos(4 x)
(%o4)                       --------
                               4
                            sin (x)
(%i5) cos(4 * x) / sin(x)^4, trigexpand;
                 4           2       2         4
              sin (x) - 6 cos (x) sin (x) + cos (x)
(%o5)         -------------------------------------
                                4
                             sin (x)
(%i6) cos(4 * x) / sin(x)^4, trigexpand, ratexpand;
                           2         4
                      6 cos (x)   cos (x)
(%o6)               - --------- + ------- + 1
                          2          4
                       sin (x)    sin (x)
(%i7) ratexpand (trigexpand (cos(4 * x) / sin(x)^4));
                           2         4
                      6 cos (x)   cos (x)
(%o7)               - --------- + ------- + 1
                          2          4
                       sin (x)    sin (x)
(%i8) declare ([F, G], evfun);
(%o8)                         done
(%i9) (aa : bb, bb : cc, cc : dd);
(%o9)                          dd
(%i10) aa;
(%o10)                         bb
(%i11) aa, F;
(%o11)                        F(cc)
(%i12) F (aa);
(%o12)                        F(bb)
(%i13) F (ev (aa));
(%o13)                        F(cc)
(%i14) aa, F, G;
(%o14)                      G(F(cc))
(%i15) G (F (ev (aa)));
(%o15)                      G(F(cc))
Управляющая переменная: infeval

Включает режим "бесконечного вычисления". ev вычисляет выражение повторно до тех пор пока оно не перестает изменяться. Чтобы предотвратить вычисление отдельной переменной, скажем X, в данном режиме следует указать X='X в качестве аргумента ev. Разумеется, выражения вроде ev (X, X=X+1, infeval) приводят к бесконечному циклу.

Функция: kill (a_1, ..., a_n)
Функция: kill (labels)
Функция: kill (inlabels, outlabels, linelabels)
Функция: kill (n)
Функция: kill ([m, n])
Функция: kill (values, functions, arrays, ...)
Функция: kill (all)
Функция: kill (allbut (a_1, ..., a_n))

Удаляет все связи (значение, функцию, массив или правило) аргументов a_1, ..., a_n. Аргумент a_k может быть символом или отдельным элементом массива. Если a_k является отдельным элементом массива, то kill удаляет значение одного этого элемента и не затрагивает другие элементы массива.

Распознается несколько специальных форм аргументов. При этом аргументы различных типов могут быть скомбинированы, например kill (inlabels, functions, allbut (foo, bar)).

kill (labels) очищает значение меток ввода, результата и меток промежуточных выражений, определенных на момент вызова. kill (inlabels) очищает значение меток ввода, имена которых начинаются с текущего значения inchar. Аналогично, kill (outlabels) очищает значение меток результата, имена которых начинаются с текущего значения outchar, и kill (linelabels) очищает значение меток промежуточных выражений, имена которых начинаются с текущего значения linechar.

kill (n), где n является целым числом, очищает значение n первых меток ввода и результата.

kill ([m, n]) очищает метки ввода и результата с номерами от m до n включительно.

kill (infolist), где infolist есть один из информационных списков infolists (например values, functions или arrays), очищает значение всех элементов в infolist. См. также infolists.

kill (all) очищает значения всех элементов во всех информационных списках (infolists). kill (all) не восстанавливает стандартные значения глобальных переменных. См. reset по поводу восстановления стандартных значений глобальных переменных.

kill (allbut (a_1, ..., a_n)) очищает все элементы во всех информационных списках кроме a_1, ..., a_n. kill (allbut (infolist)) очищает все элементы кроме тех, которые принадлежат информационному списку infolist, где infolist есть values, functions, arrays и т.д.

Отметим, что для освобождения памяти, занимаемой значением символа, необходимо очистить все объекты ссылающиеся на это значение. Необходимо не только очистить сам символ, но и результирующую метку указывающую на его значение.

Функция kill не вычисляет свои аргументы. Для их вычисления можно использовать оператор кавычка-кавычка ''.

kill (symbol) очищает все свойства символа symbol в отличии от remvalue, remfunction, remarray и remrule, которые очищают только определенное свойство.

kill всегда возвращает done даже если аргументы не имели значения.

Функция: labels (symbol)
Системная переменная: labels

Возвращает список меток ввода, результата или меток промежуточных выражений, имена которых начинаются с символа symbol. Обычно symbol это значение inchar, outchar или linechar. Значение symbol может быть указано с или без знака процента, например i и %i дадут одинаковый результат.

Если ни одна из меток не начинается с symbol, то возвращается пустой список.

Функция labels не вычисляет свои аргументы. Для их вычисления можно использовать оператор кавычка-кавычка ''. Например, labels (''inchar) возвращает список меток ввода, имена которых начинаются с текущего значения символа ввода.

Переменная labels есть список всех меток ввода, результата и меток промежуточных выражений, включая все предыдущие метки если значение inchar, outchar или linechar изменялось.

По умолчанию Maxima выводит результат каждого входного выражения присваивая ему результирующую метку. Печать результата можно подавить используя для окончания выражения символ $ вместо обычного ;. В этом случае метка результата создается но сам результат вычисления не печатается. Тем не менее значение метки результата запоминается и в дальнейшем может быть использовано как обычно. См. также %, %% и %th.

Метки промежуточных выражений создаются некоторыми функциями. Переключатель programmode определяет будет ли команда solve, и некоторые другие функции, создавать промежуточные метки или возвращать список выражений. Некоторые другие функции, такие как ldisplay, всегда создают метки промежуточных выражений.

См. также inchar, outchar, linechar и infolists.

Системная переменная: linenum

Порядковый номер текущей пары входного и результирующего выражений.

Системная переменная: myoptions

Значение по умолчанию: []

myoptions есть список всех переключателей (флагов) переопределенных пользователем вне зависимости от того имеет ли в данный момент переключатель значение по умолчанию или нет.

Управляющая переменная: nolabels

Значение по умолчанию: false

Если nolabels равна true, то метки ввода и результата (%i и %o, соответственно) печатаются но результирующее значение этим меткам не присваивается а сами метки не добавляются к списку labels. Поскольку результаты вычислений не присваиваются меткам, то сборщик мусора может освободить занимаемую ими память для дальнейшего использования.

В противном случае меткам ввода и меткам результата присваиваются соответствующие значения а сами метки добавляются к списку labels.

Флаг nolabels не влияет на метки промежуточных выражений (%t). Независимо от значения nolabels равного true или false, меткам промежуточных выражений присваиваются значение и они добавляются к списку labels.

См. также batch, load и labels.

Управляющая переменная: optionset

Значение по умолчанию: false

Если optionset равно true, Maxima печатает сообщение при изменении значения любого переключателя (опция, флаг) Maxima. Это может быть полезно, когда пользователь не уверен в написании названия опции и хочет быть уверен, что он переопределил значение правильной переменной.

Функция: playback ()
Функция: playback (n)
Функция: playback ([m, n])
Функция: playback ([m])
Функция: playback (input)
Функция: playback (slow)
Функция: playback (time)
Функция: playback (grind)

Выводит значения входных, результирующих и промежуточных выражений без их перевычисления. playback выводит только выражения связанные с метками – любой другой вывод (текст выведенный print или describe, сообщения об ошибках) не отображается. См. также labels.

Функция playback не вычисляет свои аргументы. Для их вычисления можно использовать оператор кавычка-кавычка ''. playback возвращает значение done.

playback () (без аргументов) печатает все входные, результирующие и промежуточные выражения. Результирующие выражения печатаются даже в случае, когда во время первоначальных вычислений использовался $ для подавления печати результата.

playback (n) печатает n последних выражений. Каждое входное, результирующее и промежуточное выражение считается за одно.

playback ([m, n]) печатает входные, результирующие и промежуточные выражения с номерами от m до n включительно.

playback ([m]) эквивалентно playback ([m, m]) и обычно печатает одну пару из входного и результирующего выражений.

playback (input) печатает все входные выражения.

playback (slow) останавливается между выражениями и ожидает пока пользователь нажмет "ввод" (enter). Данное поведение аналогично команде demo. playback (slow) полезно в сочетании с save или stringout для выбора выражений, которые надо сохранить в файле.

playback (time) показывает время вычисления для каждого выражения.

playback (grind) печатает входные выражения в формате функции grind. На результирующие выражения данная опция не влияет. См. grind.

Аргументы функции playback могут быть скомбинированы, например playback ([5, 10], grind, time, slow).

Функция: printprops (a, i)
Функция: printprops ([a_1, ..., a_n], i)
Функция: printprops (all, i)

Печатает свойство с именем i, ассоциированное с атомом a. a может быть списком атомов или all. В последнем случае будут использованы все атомы имеющие данное свойство. Например, printprops ([f, g], atvalue). Функция printprops предназначена для свойств, которые не могут быть отображены другим способом, например для atvalue, atomgrad, gradef и matchdeclare.

Управляющая переменная: prompt

Значение по умолчанию: _

prompt символ приглашения для функции demo, playback (slow) и диалога прерывания Maxima (break loop) (см. break).

Функция: quit ()

Завершает сессию Maxima. Команда должна быть введена именно как quit(); или quit()$, а не просто quit.

Для прерывания длительных вычислений можно нажать control-C. При этом по умолчанию Maxima возвращается на верхний уровень к приглашению ввода следующей команды. Если значение Lisp-переменной *debugger-hook* равно nil, тогда нажатие control-C запускает Lisp отладчик. См. также debugging.

Функция: remfunction (f_1, ..., f_n)
Функция: remfunction (all)

Удаляет определенные пользователем функции f_1, ..., f_n. Аргументы могут быть именами обычных функций, созданных при помощи := или define, или макро функций, созданных при помощи ::=.

remfunction (all) – удаляет все определенные пользователем функции.

remfunction не вычисляет свои аргументы.

remfunction возвращает список символов, для которых было удалено определение функции. Для символов, у которых не было соответствующих определений функций, возвращается false.

Функция remfunction не применима к функциям массивам и переменным с индексом, к этим типам функций применима remarray.

Функция: reset ()

Восстанавливает значения по умолчанию для глобальных переменных, опций и некоторых других переменных.

reset восстанавливает значения переменных хранящихся в Lisp списке *variable-initial-values*. Lisp макрос defmvar добавляет переменные в этот список (вместе с выполнением других действий). Многие, но не все, глобальные переменные и опции определены с помощью defmvar; некоторые, определенные с помощью defmvar переменные, не являются глобальными переменными или опциями.

Управляющая переменная: showtime

Значение по умолчанию: false

Если showtime равно true Maxima печатает время вычисления для каждого результирующего выражения.

Время вычисления всегда запоминается, так что time и playback могут показать это время даже если showtime равно false.

См. также timer.

Функция: sstatus (feature, package)

Устанавливает статус feature в package. После выполнения sstatus (feature, package), status (feature, package) возвращает true. Этот механизм может быть полезен при работе с пакетами для того, чтобы иметь возможность проверять какие опции пакета загружены.

Функция: to_lisp ()

Запускает интерпретатор используемой Lisp системы. Lisp функция (to-maxima) возвращает на уровень командной строки Maxima.

Function: eval_string_lisp (str)

Sequentially read lisp forms from the string str and evaluate them. Any values produced from the last form are returned as a Maxima list.

Examples:

(%i1) eval_string_lisp ("");
(%o1) []
(%i2) eval_string_lisp ("(values)");
(%o2) []
(%i3) eval_string_lisp ("69");
(%o3) [69]
(%i4) eval_string_lisp ("1 2 3");
(%o4) [3]
(%i5) eval_string_lisp ("(values 1 2 3)");
(%o5) [1,2,3]
(%i6) eval_string_lisp ("(defun $foo (x) (* 2 x))");
(%o6) [foo]
(%i7) foo (5);
(%o7) 10

See also eval_string.

Системная переменная: values

Начальное значение: []

values содержит список всех пользовательских переменных, которым присвоено значение (не Maxima опций и переключателей). Этот список состоит из символов, которым было присвоено значение при помощи операторов :, :: или :=.


Next: , Previous: Командная строка, Up: Top   [Contents][Index]

5 Операторы


Next: , Previous: Операторы, Up: Операторы   [Contents][Index]

5.1 N-арные операторы (nary)

N-арный nary оператор используется для того, чтобы задать функцию любого числа аргументов, каждый из которых разделен оператором, например A+B или A+B+C. Функция nary("x") - синтаксическое расширение функции для объявления x как n-арный оператор. Функции могут быть объявлены n-арными. Если declare(j,nary); выполнено, это указывает упрощателю (simplifier) то, что требуется упрощение, то есть, например, j(j(a,b),j(c,d)) упростится до j(a, b, c, d).

См. также Синтаксис.


Next: , Previous: N-арные операторы (nary), Up: Операторы   [Contents][Index]

5.2 Безфиксные операторы (nofix)

Безфиксные операторы (nofix, операторы без аргументов) используются, чтобы обозначить функции без аргументов. Простое присутствие такого оператора в команде вызовет то, что соответствующая функция будет вычислена. Например, когда набирают "exit;" для выхода из Maxima, "exit" ведет себя аналогично безфиксному оператору. Функция nofix("x") - это функция расширения, которая объявляет x как безфиксный оператор.

См. также Синтаксис.


Next: , Previous: Безфиксные операторы (nofix), Up: Операторы   [Contents][Index]

5.3 Постфиксные операторы (postfix)

Постфиксные операторы (postfix), как и префиксные операторы, обозначают функции одного аргумента, но в этом случае этот аргумент непосредственно предшествует появлению этого оператора в входной строке, например 3!. Функция postfix("x") - это функция синтаксического расширения, которая объявлять x как постфиксный оператор.

См. также Синтаксис.


Next: , Previous: Постфиксные операторы (postfix), Up: Операторы   [Contents][Index]

5.4 Префиксные операторы (prefix)

Префиксный оператор (prefix) обозначает функцию одного аргумента, который непосредственно идет за вхождением оператора. prefix("x") - это функция синтаксического расширения, которая объявляет x как префиксный оператор.

См. также Синтаксис.


Next: , Previous: Префиксные операторы (prefix), Up: Операторы   [Contents][Index]

5.5 Арифметические операторы

Оператор: +
Оператор: -
Оператор: *
Оператор: /
Оператор: ^

Символы +, *, / и ^ обозначают суммирование, умножение, деление и возведение в степень, соответственно. Имена этих операторов "+", "*", "/" и "^" могут появляться там, где требуется имя функции или оператора.

Символы + и - представляют унарное суммирование и вычитание, соответственно, и имена этих операторов: "+" и "-", соответственно.

Вычитание a - b представляется в Maxima как суммирование a + (- b). Выражения, такие как a + (- b), отображаются как вычитание. Maxima распознает "-" только как имя унарного оператора вычитания, а не как имя бинарного оператора вычитания.

Деление a / b представляется в Maxima как умножение, a * b^(- 1). Выражения, такие как a * b^(- 1), отображаются как деление. Maxima распознает "/" как имя оператора деления.

Суммирование и умножение - n-арные (n-ary), коммутативные операторы. Деление и возведение в степень - бинарные, некоммутативные операторы.

Maxima сортирует операнды коммутативных операторов для конструирования канонического представления. Во внутреннем хранилище упорядочивание управляется с помощью orderlessp. Для отображения, упорядочивание при суммировании управляется с помощью ordergreatp, а для умножения, флаг тот же, что и для внутреннего упорядочивания.

Арифметические вычисления выполняются для буквальных чисел (целых, рациональных, обыкновенных чисел с плавающей точкой и чисел с плавающей точкой повышенной точности (bigfloat)). За исключением возведения в степень, все арифметические операции для чисел упрощаются до чисел. Возведение в степень упрощается до числа, в случае если, либо операнд является обыкновенным числом с плавающей точкой или числом с плавающей точкой повышенной точности (bigfloat), или если результат есть точное целое или рациональное число; иначе возведение в степень может быть упрощено до sqrt или другого возведения в степень, или оставлено неизменным.

В арифметических вычислениях имеет место приведение типов значений результата: если любой операнд есть bigfloat, то результат будет bigfloat; или же, если любой операнд есть обыкновенное число с плавающей точкой, результат будет обыкновенным числом с плавающей точкой; или же, если операнды являются рациональными или целыми значениями, то результат будет рациональным или целым.

Арифметические вычисления являются упрощением, а не в вычислением. Таким образом, арифметические операции выполняется в экранированных (но упрощенных) выражениях.

Арифметические операции применяются элемент-за-элементом к спискам, когда глобальный флаг listarith есть true, и всегда применяется элемент-за-элементом к матрицам. Когда один операнд есть список или матрица и другой есть операнд некоторого другого типа, то другой операнд объединяется с каждым из элементом списка или матрицы.

Примеры:

Суммирование и умножение являются n-арными (n-ary) коммутативными операторами. Maxima сортирует операнды для того, чтобы сконструировать каноническое представление. Имена этих операторов "+" и "*".

(%i1) c + g + d + a + b + e + f;
(%o1)               g + f + e + d + c + b + a
(%i2) [op (%), args (%)];
(%o2)              [+, [g, f, e, d, c, b, a]]
(%i3) c * g * d * a * b * e * f;
(%o3)                     a b c d e f g
(%i4) [op (%), args (%)];
(%o4)              [*, [a, b, c, d, e, f, g]]
(%i5) apply ("+", [a, 8, x, 2, 9, x, x, a]);
(%o5)                    3 x + 2 a + 19
(%i6) apply ("*", [a, 8, x, 2, 9, x, x, a]);
                                 2  3
(%o6)                       144 a  x

Деление и возведение в степень - бинарные, некоммутативные операторы. Имена этих операторов "/" и "^".

(%i1) [a / b, a ^ b];
                              a   b
(%o1)                        [-, a ]
                              b
(%i2) [map (op, %), map (args, %)];
(%o2)              [[/, ^], [[a, b], [a, b]]]
(%i3) [apply ("/", [a, b]), apply ("^", [a, b])];
                              a   b
(%o3)                        [-, a ]
                              b

Вычитание и деление внутренне представляются в терминах суммирования и умножения, соответственно.

(%i1) [inpart (a - b, 0), inpart (a - b, 1), inpart (a - b, 2)];
(%o1)                      [+, a, - b]
(%i2) [inpart (a / b, 0), inpart (a / b, 1), inpart (a / b, 2)];
                                   1
(%o2)                       [*, a, -]
                                   b

Вычисления выполняются над буквальными числами. Выполняется приведение типов значений результата.

(%i1) 17 + b - (1/2)*29 + 11^(2/4);
                                       5
(%o1)                   b + sqrt(11) + -
                                       2
(%i2) [17 + 29, 17 + 29.0, 17 + 29b0];
(%o2)                   [46, 46.0, 4.6b1]

Арифметические вычисления являются упрощением, а не вычислением.

(%i1) simp : false;
(%o1)                         false
(%i2) '(17 + 29*11/7 - 5^3);
                              29 11    3
(%o2)                    17 + ----- - 5
                                7
(%i3) simp : true;
(%o3)                         true
(%i4) '(17 + 29*11/7 - 5^3);
                                437
(%o4)                         - ---
                                 7

Арифметические операции выполняется элемент-за-элементом для списков (в зависимости от значения listarith) и матриц.

(%i1) matrix ([a, x], [h, u]) - matrix ([1, 2], [3, 4]);
                        [ a - 1  x - 2 ]
(%o1)                   [              ]
                        [ h - 3  u - 4 ]
(%i2) 5 * matrix ([a, x], [h, u]);
                          [ 5 a  5 x ]
(%o2)                     [          ]
                          [ 5 h  5 u ]
(%i3) listarith : false;
(%o3)                         false
(%i4) [a, c, m, t] / [1, 7, 2, 9];
                          [a, c, m, t]
(%o4)                     ------------
                          [1, 7, 2, 9]
(%i5) [a, c, m, t] ^ x;
                                      x
(%o5)                     [a, c, m, t]
(%i6) listarith : true;
(%o6)                         true
(%i7) [a, c, m, t] / [1, 7, 2, 9];
                              c  m  t
(%o7)                     [a, -, -, -]
                              7  2  9
(%i8) [a, c, m, t] ^ x;
                          x   x   x   x
(%o8)                   [a , c , m , t ]
Оператор: **

Оператор возведения в степень. Maxima распознает ** как тот же оператор, что и ^ при вводе, и он отображается как ^ в 1D (одномерном) выводе, или в виде показателя степени как верхний индекс в 2D (двумерном) выводе.

Функция fortran выводит оператор возведения в степень как **, не в зависимости от того, как он был задан при вводе, как ** или ^.

Примеры:

(%i1) is (a**b = a^b);
(%o1)                         true
(%i2) x**y + x^z;
                              z    y
(%o2)                        x  + x
(%i3) string (x**y + x^z);
(%o3)                        x^z+x^y
(%i4) fortran (x**y + x^z);
      x**z+x**y
(%o4)                         done

Next: , Previous: Арифметические операторы, Up: Операторы   [Contents][Index]

5.6 Операторы отношения

Оператор: <
Оператор: <=
Оператор: >=
Оператор: >

Символы < , <= , >= и > представляют отношения меньше, меньше или равно, больше или равно и больше, соответственно. Имена этих операторов есть "<" , "<=" , ">=" и ">". Эти имена могут применяться в случае, если требуется имя функции или оператора.

Данные операторы отношения являются бинарными. Конструкции типа a < b < c недопустимы в Maxima.

Операторы отношения вычисляются до логических значений функциями is и maybe, и программными конструкциями if, while и unless. В других случаях операторы отношения не вычисляются или упрощаются до логических значений, хотя аргументы операторов отношения вычисляются (если вычисление не блокировано при помощи оператора кавычка).

Если выражение отношения не может быть вычислено до логического значения true или false, то поведение is и if управляется глобальным флагом prederror. Если значение prederror равно true, то is и if вызывает ошибку. Если значение prederror равно false, то is возвращает unknown а if возвращает частично-вычисленное условное выражение.

maybe всегда ведет себя так, если бы prederror равнялось false, а while и unless всегда ведут себя так, если бы prederror равнялось true.

Операторы отношения не дистрибутивны по отношению к спискам и другим конструкциям.

См. также = , # , equal и notequal.

Примеры:

Операторы отношения вычисляются до логических значений некоторыми функциями и программными конструкциями.

(%i1) [x, y, z] : [123, 456, 789];
(%o1)                    [123, 456, 789]
(%i2) is (x < y);
(%o2)                         true
(%i3) maybe (y > z);
(%o3)                         false
(%i4) if x >= z then 1 else 0;
(%o4)                           0
(%i5) block ([S], S : 0, for i:1 while i <= 100 do S : S + i, return (S));
(%o5)                         5050

Во всех других случаях операторы отношения не вычисляются или упрощаются до логических значений, хотя их аргументы вычисляются.

(%o1)                    [123, 456, 789]
(%i2) [x < y, y <= z, z >= y, y > z];
(%o2)    [123 < 456, 456 <= 789, 789 >= 456, 456 > 789]
(%i3) map (is, %);
(%o3)               [true, true, true, false]

Previous: Операторы отношения, Up: Операторы   [Contents][Index]

5.7 Общие операторы

Оператор: ^^

Оператор некоммутативного возведение в степень. ^^ - оператор некоммутативного возведение в степень, соответствующий некоммутативному умножению ., ровно так же как обычный оператор возведение в степень ^ соответствует коммутативному умножению *.

Некоммутативное возведение в степень отображается как ^^ в 1D (одномерном) выводе, и в виде показателя степени как верхний индекс в угловых скобка < > в 2D (двумерном) выводе.

Примеры:

(%i1) a . a . b . b . b + a * a * a * b * b;
                        3  2    <2>    <3>
(%o1)                  a  b  + a    . b
(%i2) string (a . a . b . b . b + a * a * a * b * b);
(%o2)                  a^3*b^2+a^^2 . b^^3
Оператор: !

Оператор факториала. Для всех комплексных чисел x (включая целые, рациональные, и вещественные числа), за исключением отрицательных целых, x! задается как gamma(x+1).

Для целого x, x! упрощается до произведения целых чисел от 1 до x включительно. 0! упрощается до 1. Для чисел с плавающей точкой x, x! упрощается до значения gamma (x+1). Для x равных n/2, где n - нечетное целое, x! упрощается до рационального множителя, умноженного на sqrt (%pi) (т. к. gamma (1/2) равно sqrt (%pi)). Если x - что то еще, то x! не упрощается.

Переменные factlim, minfactorial и factcomb управляют упрощением выражений, содержащих факториалы.

Функции gamma, bffac и cbffac являются разновидностями гамма функции. makegamma заменяет gamma для факториалов и связанных функций.

См. также binomial.

Факториал целого, полуцелого или аргумента с плавающей точкой, упрощается если операнд не больше чем factlim.

(%i1) factlim : 10;
(%o1)                          10
(%i2) [0!, (7/2)!, 4.77!, 8!, 20!];
            105 sqrt(%pi)
(%o2)   [1, -------------, 81.44668037931199, 40320, 20!]
                 16

Факториал комплексного числа, известной константы, или выражение общего вида не упрощается. Но в этом случае возможно упростить факториал после вычисления операнда.

(%i1) [(%i + 1)!, %pi!, %e!, (cos(1) + sin(1))!];
(%o1)      [(%i + 1)!, %pi!, %e!, (sin(1) + cos(1))!]
(%i2) ev (%, numer, %enumer);
(%o2) [(%i + 1)!, 7.188082728976037, 4.260820476357, 
                                               1.227580202486819]

Факториал символа, не имеющего значения, не упрощается.

(%i1) kill (foo);
(%o1)                         done
(%i2) foo!;
(%o2)                         foo!

Факториалы упрощаются, а не вычисляются. Таким образом, x! можно заменять даже в экранированном (quoted) выражении.

(%i1) '([0!, (7/2)!, 4.77!, 8!, 20!]);
          105 sqrt(%pi)
(%o1) [1, -------------, 81.44668037931199, 40320, 
               16
                                             2432902008176640000]
Оператор: !!

Оператор двойного факториала.

Для целого, числа с плавающей точкой или рационального числа n, n!! вычисляется как произведение n (n-2) (n-4) (n-6) ... (n - 2 (k-1)) где k равно entier (n/2), то есть, наибольшее целое меньше или равное n/2. Заметим, что это определение не совпадает с другими опубликованными определениями для нецелых аргументов.

Для четного (или нечетного) целого n, n!! вычисляется как произведение всех последовательных четных (или нечетных) целых от 2 (или 1) до n включительно.

Для аргумента n, который не является целым, числом с плавающей точкой, или рациональным числом, n!! дает невычисляемую форму genfact (n, n/2, 2).

Оператор: #

Обозначает отрицание синтаксического равенства =.

Заметим, что из-за правил для вычисления предикатных выражений (в частности из-за того, что not expr вызывает вычисление expr), not a = b эквивалентно is(a # b), вместо a # b.

Примеры:

(%i1) a = b;
(%o1)                         a = b
(%i2) is (a = b);
(%o2)                         false
(%i3) a # b;
(%o3)                         a # b
(%i4) not a = b;
(%o4)                         true
(%i5) is (a # b);
(%o5)                         true
(%i6) is (not a = b);
(%o6)                         true
Оператор: .

Оператор "точка" предназначен для матричного (некоммутативного) умножения. Когда "." используется таким образом, пробелы должны присутствовать с обеих сторон, то есть A . B. Это позволяет различать оператор от десятичной точки в числе с плавающей точкой.

См. также dot, dot0nscsimp, dot0simp, dot1simp, dotassoc, dotconstrules, dotdistrib, dotexptsimp, dotident, и dotscrules.

Оператор: :

Оператор присваивания.

Если левая сторона есть простая переменная (не переменная с индексом), то : вычисляет правую сторону присваивания и присваивает значение с левой частью.

Если левая строна есть индексированный элемент списка, матрица, объявленного Maxima массива или Lisp массива, то значение правой части присваивается этому элементу. Индекс должен выделять существующий элемент. Подобные конструкции нельзя расширить на несуществующие элементы.

Если левая сторона есть индексированный элемент необъявленного массива, то значение правой части присваивается этому элементу, если таковой уже существует, или вновь созданному объекту, если он еще не существует.

Если левая строна присваивания есть список простых переменных и/или переменных с индексом, то правая часть должна вычисляться в список, и элементы этого списка присваиваются элементам левой части параллельно.

См. также kill и remvalue, которые отменяют присваивание.

Примеры:

Присваивание простой переменной.

(%i1) a;
(%o1)                           a
(%i2) a : 123;
(%o2)                          123
(%i3) a;
(%o3)                          123

Присваивание элементу списка.

(%i1) b : [1, 2, 3];
(%o1)                       [1, 2, 3]
(%i2) b[3] : 456;
(%o2)                          456
(%i3) b;
(%o3)                      [1, 2, 456]

Присваивание создает необъявленный массив.

(%i1) c[99] : 789;
(%o1)                          789
(%i2) c[99];
(%o2)                          789
(%i3) c;
(%o3)                           c
(%i4) arrayinfo (c);
(%o4)                   [hashed, 1, [99]]
(%i5) listarray (c);
(%o5)                         [789]

Множественные присваивания.

(%i1) [a, b, c] : [45, 67, 89];
(%o1)                     [45, 67, 89]
(%i2) a;
(%o2)                          45
(%i3) b;
(%o3)                          67
(%i4) c;
(%o4)                          89

Множественные присваивания выполняются параллельно. В этом примере переменные a и b обмениваются значениями.

(%i1) [a, b] : [33, 55];
(%o1)                       [33, 55]
(%i2) [a, b] : [b, a];
(%o2)                       [55, 33]
(%i3) a;
(%o3)                          55
(%i4) b;
(%o4)                          33
Оператор: ::

Оператор присваивания.

Оператор :: аналогичен оператору присваивания : за исключением того, что :: вычисляет свою левую часть наряду с вычислением правой части.

Примеры:

(%i1) x : 'foo;
(%o1)                          foo
(%i2) x :: 123;
(%o2)                          123
(%i3) foo;
(%o3)                          123
(%i4) x : '[a, b, c];
(%o4)                       [a, b, c]
(%i5) x :: [11, 22, 33];
(%o5)                     [11, 22, 33]
(%i6) a;
(%o6)                          11
(%i7) b;
(%o7)                          22
(%i8) c;
(%o8)                          33
Оператор: ::=

Оператор определения макро функции. ::= задает функцию (называемую "макрос" по историческим причинам) которое экранирует (quote) свои аргументы, и выражение, которое она возвращает (называемое "макро расширение"), вычисляется в том контексте, из которого этот макрос был вызван. В других отношениях макро функция такая же как и обыкновенная функция.

Функция macroexpand возвращает макро расширение (без ее вычисления). macroexpand (foo (x)) следующее за ''% эквивалентно foo (x), где foo есть макро функция.

Оператор ::= помещает имя новой макро функции в глобальный список macros. Функции kill, remove и remfunction удаляет определения макро функций и удаляет имена из macros.

Функции fundef или dispfun, соответственно, возвращает определение макро функции или присваивает его метке.

Макро функции обычно содержат buildq и splice выражения для конструирования выражения, которое затем вычисляется.

Примеры.

Макро функция экранирует свои аргументы, так что сообщение (1) показывает выражение y - z, а не значение y - z. Макро расширение (экранированное выражение '(print ("(2) x равно ", x)) вычисляется в том контексте, из которого этот макрос был вызван, печатая сообщение (2).

(%i1) x: %pi;
(%o1)                          %pi
(%i2) y: 1234;
(%o2)                         1234
(%i3) z: 1729 * w;
(%o3)                        1729 w
(%i4) printq1 (x) ::= block (print ("(1) x is equal to", x),
      '(print ("(2) x is equal to", x)));
(%o4) printq1(x) ::= block(print("(1) x is equal to", x), 
                                '(print("(2) x is equal to", x)))
(%i5) printq1 (y - z);
(1) x is equal to y - z 
(2) x is equal to %pi 
(%o5)                          %pi

Обыкновенная функция вычисляет свои аргументы, так что сообщение (1) показывает значение y - z. Возвращаемое значение не вычисляется, так что сообщение (2) не печатается до момента явного вычисления ''%.

(%i1) x: %pi;
(%o1)                          %pi
(%i2) y: 1234;
(%o2)                         1234
(%i3) z: 1729 * w;
(%o3)                        1729 w
(%i4) printe1 (x) := block (print ("(1) x is equal to", x),
      '(print ("(2) x is equal to", x)));
(%o4) printe1(x) := block(print("(1) x is equal to", x), 
                                '(print("(2) x is equal to", x)))
(%i5) printe1 (y - z);
(1) x is equal to 1234 - 1729 w 
(%o5)              print((2) x is equal to, x)
(%i6) ''%;
(2) x is equal to %pi 
(%o6)                          %pi

Функция macroexpand возвращает макро расширение. Выражение macroexpand (foo (x)), идущее перед ''% эквивалентно foo (x), когда foo есть макро функция.

(%i1) x: %pi;
(%o1)                          %pi
(%i2) y: 1234;
(%o2)                         1234
(%i3) z: 1729 * w;
(%o3)                        1729 w
(%i4) g (x) ::= buildq ([x], print ("x is equal to", x));
(%o4)    g(x) ::= buildq([x], print("x is equal to", x))
(%i5) macroexpand (g (y - z));
(%o5)              print(x is equal to, y - z)
(%i6) ''%;
x is equal to 1234 - 1729 w 
(%o6)                     1234 - 1729 w
(%i7) g (y - z);
x is equal to 1234 - 1729 w 
(%o7)                     1234 - 1729 w
Оператор: :=

Оператор определения функции.

f(x_1, ..., x_n) := expr определяет функцию с именем f, аргументами x_1, ..., x_n и телом функции expr. Оператор := никогда не вычисляет тело функции (если только вычисление не задано явно оператором кавычка-кавычка ''). Функция заданная таким образом может быть обыкновенной Maxima функцией (с аргументами, заключенными в скобки) или функцией массивом (с аргументами, заключенными в квадратные скобки).

Когда последний или единственный аргумент функции x_n есть список из одного элемента, функция, заданная := принимает переменное число аргументов. Фактические аргументы присваиваются один-в-один формальным аргументам x_1, ..., x_(n - 1), и любые дальнейшие фактические аргументы, если присутствуют, присваиваются к x_n как список.

Все определения функций появляются в том же пространстве имен; задав функцию f внутри другой функции g, определение не ограничивает зону видимости f в g.

Если некоторый формальный аргумент x_k есть экранированный (quoted) символ, функция, заданная с помощью :=, не вычисляет соответствующий фактический аргумент. В противном случае, все фактические аргументы вычисляются.

См. также define и ::=.

Примеры:

:= никогда не вычисляет тело функции (если только явно не задано вычисление).

(%i1) expr : cos(y) - sin(x);
(%o1)                    cos(y) - sin(x)
(%i2) F1 (x, y) := expr;
(%o2)                   F1(x, y) := expr
(%i3) F1 (a, b);
(%o3)                    cos(y) - sin(x)
(%i4) F2 (x, y) := ''expr;
(%o4)              F2(x, y) := cos(y) - sin(x)
(%i5) F2 (a, b);
(%o5)                    cos(b) - sin(a)

Функция, заданная :=, может быть обыкновенной Maxima функцией или функцией массивом.

(%i1) G1 (x, y) := x.y - y.x;
(%o1)               G1(x, y) := x . y - y . x
(%i2) G2 [x, y] := x.y - y.x;
(%o2)                G2     := x . y - y . x
                       x, y

Когда последний или единственный аргумент функции x_n есть список из одного элемента, функция, заданная :=, принимает переменное число аргументов.

(%i1) H ([L]) := apply ("+", L);
(%o1)                H([L]) := apply("+", L)
(%i2) H (a, b, c);
(%o2)                       c + b + a
Оператор: =

Оператор равенства.

Выражение a = b, само по себе, представляет собой невычисляемое уравнение, которое может или может не выполняться. Невычисляемые уравнения могут появляться как аргументы в solve и algsys, или в некоторых других функциях.

Функция is вычисляет = до логического значения. is(a = b) вычисляет a = b в true, когда a и b тождественны. То есть, a и b есть атомы, которые идентичны, или они не атомы и их операторы идентичны и их аргументы идентичны. В противном случае, is(a = b) вычисляется в false; он никогда не вычисляется в unknown. Когда is(a = b) есть true, говорят что a и b синтаксически равны, в противоположность эквивалентным выражениям, для которых is(equal(a, b)) есть true. Выражения могут быть равны, но синтаксически не равны.

Отрицание = представляется как #. Как и в случае с =, выражение a # b, само по себе, не вычисляется. is(a # b) вычисляется a # b до true или false.

Кроме is, некоторые другие операторы вычисляют = и # до true или false, а именно if, and, or и not.

Заметим, что из-за правил для вычисления предикатных выражений (в частности из-за того, что not expr вызывает вычисление expr), not a = b эквивалентно is(a # b), а не a # b.

rhs и lhs возвращают правую и левую часть уравнения или неравенства соответственно.

См. также equal или notequal.

Примеры:

Выражение a = b, само по себе, представляет невычисляемое уравнение, которое может или может не выполняться.

(%i1) eq_1 : a * x - 5 * y = 17;
(%o1)                    a x - 5 y = 17
(%i2) eq_2 : b * x + 3 * y = 29;
(%o2)                    3 y + b x = 29
(%i3) solve ([eq_1, eq_2], [x, y]);
                        196         29 a - 17 b
(%o3)          [[x = ---------, y = -----------]]
                     5 b + 3 a       5 b + 3 a
(%i4) subst (%, [eq_1, eq_2]);
         196 a     5 (29 a - 17 b)
(%o4) [--------- - --------------- = 17, 
       5 b + 3 a      5 b + 3 a
                                  196 b     3 (29 a - 17 b)
                                --------- + --------------- = 29]
                                5 b + 3 a      5 b + 3 a
(%i5) ratsimp (%);
(%o5)                  [17 = 17, 29 = 29]

is(a = b) вычисляет a = b в true, когда a и b тождественны (синтаксически равны). Выражения могут быть равны, но синтаксически не равны.

(%i1) a : (x + 1) * (x - 1);
(%o1)                    (x - 1) (x + 1)
(%i2) b : x^2 - 1;
                              2
(%o2)                        x  - 1
(%i3) [is (a = b), is (a # b)];
(%o3)                     [false, true]
(%i4) [is (equal (a, b)), is (notequal (a, b))];
(%o4)                     [true, false]

Некоторые операторы вычисляют = и # до true или false.

(%i1) if expand ((x + y)^2) = x^2 + 2 * x * y + y^2 then FOO else
      BAR;
(%o1)                          FOO
(%i2) eq_3 : 2 * x = 3 * x;
(%o2)                       2 x = 3 x
(%i3) eq_4 : exp (2) = %e^2;
                              2     2
(%o3)                       %e  = %e
(%i4) [eq_3 and eq_4, eq_3 or eq_4, not eq_3];
(%o4)                  [false, true, true]

Из-за того, что not expr вызывает вычисление expr, not a = b эквивалентно is(a # b).

(%i1) [2 * x # 3 * x, not (2 * x = 3 * x)];
(%o1)                   [2 x # 3 x, true]
(%i2) is (2 * x # 3 * x);
(%o2)                         true
Оператор: and

Оператор логического умножения. Оператор and есть n-арный инфиксный оператор. Его операнды есть логические выражения и его результат есть логическое значение.

Оператор and вызывает вычисление (как и is) одного или более операндов, и может вызвать вычисление всех операндов.

Операнды вычисляются в том же порядка, к котором они встречаются. Оператор and вычисляет только столько своих операндов, сколько необходимо для того, чтобы определить результат. Если хотя бы один операнд есть false, результат есть false, и более ни один из операндов не вычисляется.

Глобальный флаг prederror управляет поведением and, когда вычисляемый операнд не может быть определен как true или false. Оператор and печатает сообщение об ошибке, когда prederror есть true. Иначе, операнды, которые не могут быть вычислены как true или false, принимаются, и результат есть логическое выражение.

Оператор and не является коммутативным: a and b может быть не равно b and a из-за трактовки неопределенных операндов.

Оператор: or

Оператор логического сложения. or есть n-арный инфиксный оператор. Его операнды есть логические выражения и его результат есть логическое значение.

or вызывает вычисление (как и is) одного или более операндов, и может вызвать вычисление всех операндов.

Операнды вычисляются в том же порядка, к котором они встречаются. or вычисляет только столько своих операндов, сколько необходимо для того, чтобы определить результат. Если хотя бы один операнд есть true, результат есть true, и более ни один из операндов не вычисляется.

Глобальный флаг prederror управляет поведением or, когда вычисляемый операнд не может быть определен как true или false. Оператор or печатает сообщение об ошибке, когда prederror есть true. Иначе, операнды, которые не могут быть вычислены как true или false, принимаются, и результат есть логическое выражение.

Оператор or не является коммутативным: a or b может быть не равно b or a из-за трактовки неопределенных операндов.

Оператор: not

Оператор логического отрицания. Оператор not есть префиксный оператор. Его операнд есть логическое выражение и его результат есть логическое значение.

Оператор not вызывает вычисление (как и is) своего операнда.

Глобальный флаг prederror управляет поведением not, когда его операнд не может быть определен как значения true или false. Оператор not печатает сообщение об ошибке, когда prederror есть true. Иначе, операнды, которые не могут быть вычислены как true или false, принимаются, и результат есть логическое выражение.

Функция: abs (expr)

Возвращает абсолютное значение expr (модуль выражения). Если expr - комплексное, возвращается комплексный модуль expr.

Ключевое слово: additive

Если declare(f,additive) было выполнено, то:

(1) Если f одномерно, пока упрощение не столкнулось с f примененному к сумме, f будет распространено вдоль этой суммы. То есть, f(y+x) будет упрощено как f(y)+f(x).

(2) Если f есть функция двух или более аргументов, аддитивность задается как аддитивность по первому аргументу f, как в случае sum или integrate, то есть f(h(x)+g(x),x) будет упрощено как f(h(x),x)+f(g(x),x). Это упрощение не произойдет, когда f применена к выражению вида sum(x[i],i,lower-limit,upper-limit).

Ключевое слово: allbut

Работает с командами part (например, part, inpart, substpart, substinpart, dpart и lpart). Например:

(%i1) expr : e + d + c + b + a;
(%o1)                   e + d + c + b + a
(%i2) part (expr, [2, 5]);
(%o2)                         d + a

хотя

(%i1) expr : e + d + c + b + a;
(%o1)                   e + d + c + b + a
(%i2) part (expr, allbut (2, 5));
(%o2)                       e + c + b

allbut также распознается kill.

(%i1) [aa : 11, bb : 22, cc : 33, dd : 44, ee : 55];
(%o1)                 [11, 22, 33, 44, 55]
(%i2) kill (allbut (cc, dd));
(%o0)                         done
(%i1) [aa, bb, cc, dd];
(%o1)                   [aa, bb, 33, 44]

kill(allbut(a_1, a_2, ...)) имеет тот же эффект, что kill(all) за исключением того, что это не очищает символы a_1, a_2, ... .

Декларация: antisymmetric

Если declare(h,antisymmetric) выполнена, этот говорит упрощателю, что h - антисимметричная. Например, h(x,z,y) упростится до - h(x, y, z). То есть, это дает (-1)^n умноженное на symmetric или commutative результат, где n есть число перестановок двух аргументов необходимых для того, чтобы перевести к конечной форме.

Функция: cabs (expr)

Возвращает комплексное абсолютное значение (комплексный модуль) expr.

Функция: ceiling (x)

Когда x есть вещественное число - возвращает наименьшее целое, которое больше чем или равно x.

Если x - константное выражение (10 * %pi, например), ceiling вычисляет x используя большие числа с плавающей точкой и применяет ceiling к конечному большому числу с плавающей точкой. Из-за того, что ceiling использует вычисления с числами с плавающей точкой, возможно, хотя маловероятно, что ceiling может вернуть ошибочное значение для константных входных данных. Чтобы защититься от ошибок, вычисление с числами с плавающей точкой выполняется с использованием трех значений для fpprec.

Для неконстантных входных данных, ceiling пытается вернуть упрощенное значение. Вот примеры упрощений, о которых ceiling знает:

(%i1) ceiling (ceiling (x));
(%o1)                      ceiling(x)
(%i2) ceiling (floor (x));
(%o2)                       floor(x)
(%i3) declare (n, integer)$
(%i4) [ceiling (n), ceiling (abs (n)), ceiling (max (n, 6))];
(%o4)                [n, abs(n), max(n, 6)]
(%i5) assume (x > 0, x < 1)$
(%i6) ceiling (x);
(%o6)                           1
(%i7) tex (ceiling (a));
$$\left \lceil a \right \rceil$$
(%o7)                         false

Функция ceiling автоматически не распространяется (map) для списков или матриц. Наконец, для всех входных данных, которые объявлены комплексными, ceiling возвращает невычисляемую форму.

Если диапазон функции есть подмножество целых, она может быть объявлена как integervalued. Обе функции ceiling и floor могут использовать эту информацию. Например:

(%i1) declare (f, integervalued)$
(%i2) floor (f(x));
(%o2)                         f(x)
(%i3) ceiling (f(x) - 1);
(%o3)                       f(x) - 1
Функция: charfun (p)

Возвращает 0, когда предикат p вычисляется как false; возвращает 1, когда предикат вычисляется как true. Когда предикат вычисляется до чего-то другого, чем true или false (unknown), возвращает невычисляемую форму.

Примеры:

(%i1) charfun (x < 1);
(%o1)                    charfun(x < 1)
(%i2) subst (x = -1, %);
(%o2)                           1
(%i3) e : charfun ('"and" (-1 < x, x < 1))$
(%i4) [subst (x = -1, e), subst (x = 0, e), subst (x = 1, e)];
(%o4)                       [0, 1, 0]
Декларация: commutative

Если declare(h,commutative) выполнено, это говорит упрощателю, что h есть коммутативная функция. То есть h(x,z,y) упроститься до h(x, y, z). Это тоже самое, что и symmetric.

Функция: compare (x, y)

Возвращает оператор отношения op (<, <=, >, >=, = или #) так что is (x op y) вычисляется до true; когда x или y зависит от %i и x # y, возвращает notcomparable; когда нет такого оператора или Maxima не может определить оператор, возвращает unknown.

Примеры:

(%i1) compare (1, 2);
(%o1)                           <
(%i2) compare (1, x);
(%o2)                        unknown
(%i3) compare (%i, %i);
(%o3)                           =
(%i4) compare (%i, %i + 1);
(%o4)                     notcomparable
(%i5) compare (1/x, 0);
(%o5)                           #
(%i6) compare (x, abs(x));
(%o6)                          <=

Функция compare не пытается определить, действительно ли области определения ее аргументов непусты. Таким образом

(%i1) compare (acos (x^2 + 1), acos (x^2 + 1) + 1);
(%o1)                           <

Действительная область определения acos (x^2 + 1) пуста.

Функция: entier (x)

Возвращает наибольшее целое меньше или равное чем x, где x - численное. Функция fix (как и в fixnum) есть синоним, так что fix(x) в точности тоже самое.

Функция: equal (a, b)

Представляет эквивалентность, то есть, равное значение.

Само по себе, equal не вычисляется или упрощается. Функция is пытается вычислить equal до логического значения. Функция is(equal(a, b)) возвращает true (или false), если и только если, a и b равны (или не равны) для всех возможных значений своих переменных, как определено вычислением ratsimp(a - b). Если ratsimp возвращает 0, два выражения рассматриваются эквивалентными. Два выражения могут быть эквивалентными даже если они не являются синтаксически равными (то есть, идентичными).

Когда is не может упростить equal до true или false, результат управляется глобальным флагом prederror. Когда prederror есть true, is выдает сообщение об ошибке. Иначе, is возвращает unknown.

В добавление к is, некоторые другие операторы вычисляют equal и notequal до true или false, а именно if, and, or и not.

Отрицанием equal является notequal.

Примеры:

Само по себе, equal не вычисляет и не упрощает.

(%i1) equal (x^2 - 1, (x + 1) * (x - 1));
                        2
(%o1)            equal(x  - 1, (x - 1) (x + 1))
(%i2) equal (x, x + 1);
(%o2)                    equal(x, x + 1)
(%i3) equal (x, y);
(%o3)                      equal(x, y)

Функция is пытается вычислить equal до логического значения. is(equal(a, b)) возвращает true когда ratsimp(a - b) возвращает 0. Два выражения могут быть эквивалентными даже если они синтаксически не равны (то есть, не идентичны).

(%i1) ratsimp (x^2 - 1 - (x + 1) * (x - 1));
(%o1)                           0
(%i2) is (equal (x^2 - 1, (x + 1) * (x - 1)));
(%o2)                         true
(%i3) is (x^2 - 1 = (x + 1) * (x - 1));
(%o3)                         false
(%i4) ratsimp (x - (x + 1));
(%o4)                          - 1
(%i5) is (equal (x, x + 1));
(%o5)                         false
(%i6) is (x = x + 1);
(%o6)                         false
(%i7) ratsimp (x - y);
(%o7)                         x - y
(%i8) is (equal (x, y));
(%o8)                        unknown
(%i9) is (x = y);
(%o9)                         false

Когда is не может упростить equal до true или false, результат управляется глобальным флагом prederror.

(%i1) [aa : x^2 + 2*x + 1, bb : x^2 - 2*x - 1];
                    2             2
(%o1)             [x  + 2 x + 1, x  - 2 x - 1]
(%i2) ratsimp (aa - bb);
(%o2)                        4 x + 2
(%i3) prederror : true;
(%o3)                         true
(%i4) is (equal (aa, bb));
Maxima was unable to evaluate the predicate:
       2             2
equal(x  + 2 x + 1, x  - 2 x - 1)
 -- an error.  Quitting.  To debug this try debugmode(true);
(%i5) prederror : false;
(%o5)                         false
(%i6) is (equal (aa, bb));
(%o6)                        unknown

Некоторые операторы вычисляют equal или notequal до true или false.

(%i1) if equal (y, y - 1) then FOO else BAR;
(%o1)                          BAR
(%i2) eq_1 : equal (x, x + 1);
(%o2)                    equal(x, x + 1)
(%i3) eq_2 : equal (y^2 + 2*y + 1, (y + 1)^2);
                         2                   2
(%o3)             equal(y  + 2 y + 1, (y + 1) )
(%i4) [eq_1 and eq_2, eq_1 or eq_2, not eq_1];
(%o4)                  [false, true, true]

Из-за того, что not expr вызывает вычисление expr, not equal(a, b) эквивалентно is(notequal(a, b)).

(%i1) [notequal (2*z, 2*z - 1), not equal (2*z, 2*z - 1)];
(%o1)            [notequal(2 z, 2 z - 1), true]
(%i2) is (notequal (2*z, 2*z - 1));
(%o2)                         true
Функция: floor (x)

Когда x есть вещественное число - возвращает наибольшее целое, которое меньше или равно x.

Если x есть константное выражение (10 * %pi, например), floor вычисляет x используя большие числа с плавающей точкой и применяет floor к результирующему значению. Из-за того, что floor использует вычисления с числами с плавающей точкой, возможно, хотя маловероятно, что floor может вернуть ошибочное значение для константных входных данных. Чтобы застраховаться от ошибок, вычисление с числами с плавающей точкой выполняется, используя три значения для fpprec.

Для неконстантных входных данных, floor пытается вернуть упрощенное значение. Вот примеры упрощений, о которых floor знает:

(%i1) floor (ceiling (x));
(%o1)                      ceiling(x)
(%i2) floor (floor (x));
(%o2)                       floor(x)
(%i3) declare (n, integer)$
(%i4) [floor (n), floor (abs (n)), floor (min (n, 6))];
(%o4)                [n, abs(n), min(n, 6)]
(%i5) assume (x > 0, x < 1)$
(%i6) floor (x);
(%o6)                           0
(%i7) tex (floor (a));
$$\left \lfloor a \right \rfloor$$
(%o7)                         false

Функция floor автоматически не распространяется (map) для списков или матриц. Наконец, для всех входных данных, которые заданы как комплексные, floor возвращает невычисляемую форму.

Если диапазон функции есть подмножество целых, она может быть объявлена как integervalued. Обе функции ceiling и floor могут использовать эту информацию. Например:

(%i1) declare (f, integervalued)$
(%i2) floor (f(x));
(%o2)                         f(x)
(%i3) ceiling (f(x) - 1);
(%o3)                       f(x) - 1
Функция: notequal (a, b)

Представляет собой отрицание equal(a, b).

Примеры:

(%i1) equal (a, b);
(%o1)                      equal(a, b)
(%i2) maybe (equal (a, b));
(%o2)                        unknown
(%i3) notequal (a, b);
(%o3)                    notequal(a, b)
(%i4) not equal (a, b);
(%o4)                    notequal(a, b)
(%i5) maybe (notequal (a, b));
(%o5)                        unknown
(%i6) assume (a > b);
(%o6)                        [a > b]
(%i7) equal (a, b);
(%o7)                      equal(a, b)
(%i8) maybe (equal (a, b));
(%o8)                         false
(%i9) notequal (a, b);
(%o9)                    notequal(a, b)
(%i10) maybe (notequal (a, b));
(%o10)                        true
Оператор: eval

Как аргумент в вызове к ev (expr), eval вызывает дополнительное вычисление expr. См. ev.

Функция: evenp (expr)

Возвращает true если expr есть четное целое. false возвращается во всех других случаях.

Функция: fix (x)

Синоним для entier (x).

Функция: fullmap (f, expr_1, ...)

Аналогично map, но fullmap продолжает процедуру распространения для всех подвыражений до тех пор, пока основные операторы более не остаются теми же самыми.

Функция fullmap используется Maxima упрощателем для некоторых матричных манипуляций. Таким образом, Maxima иногда генерирует сообщение об ошибке, касающееся fullmap хотя fullmap явно не вызывалась пользователем.

Примеры:

(%i1) a + b * c;
(%o1)                        b c + a
(%i2) fullmap (g, %);
(%o2)                   g(b) g(c) + g(a)
(%i3) map (g, %th(2));
(%o3)                     g(b c) + g(a)
Функция: fullmapl (f, list_1, ...)

Аналогично fullmap, но fullmapl только распространяется на списки и матрицы.

Пример:

(%i1) fullmapl ("+", [3, [4, 5]], [[a, 1], [0, -1.5]]);
(%o1)                [[a + 3, 4], [4, 3.5]]
Функция: is (expr)

Пытается определить, является ли предикат expr доказуемым из фактов в базе данных assume.

Если этот предикат является доказуемым как true или false, is возвращает true или false, соответственно. Иначе, возвращаемое значение управляется глобальным флагом prederror. Когда prederror есть true, is выдает сообщение об ошибке. Иначе, is возвращает unknown.

Выражение ev(expr, pred) (который можно переписать как expr, pred в интерактивной строке) эквивалентно is(expr).

См. также assume, facts и maybe.

Примеры:

is вызывает вычисление предикатов.

(%i1) %pi > %e;
(%o1)                       %pi > %e
(%i2) is (%pi > %e);
(%o2)                         true

is пытается вывести предикаты из базы данных assume.

(%i1) assume (a > b);
(%o1)                        [a > b]
(%i2) assume (b > c);
(%o2)                        [b > c]
(%i3) is (a < b);
(%o3)                         false
(%i4) is (a > c);
(%o4)                         true
(%i5) is (equal (a, c));
(%o5)                         false

Если is не может доказать или опровергнуть предикат из базы данных assume, глобальный флаг prederror управляет поведением is.

(%i1) assume (a > b);
(%o1)                        [a > b]
(%i2) prederror: true$
(%i3) is (a > 0);
Maxima was unable to evaluate the predicate:
a > 0
 -- an error.  Quitting.  To debug this try debugmode(true);
(%i4) prederror: false$
(%i5) is (a > 0);
(%o5)                        unknown
Функция: maybe (expr)

Пытается определить, является ли предикат expr доказуемым исходя из фактов в базе данных assume.

Если этот предикат доказуем как true или false, maybe возвращает true или false, соответственно. Иначе, maybe возвращает unknown.

maybe функционально эквивалентен is с prederror: false, но результат вычислен без реального присвоение значения prederror.

См. также assume, facts и is.

Примеры:

(%i1) maybe (x > 0);
(%o1)                        unknown
(%i2) assume (x > 1);
(%o2)                        [x > 1]
(%i3) maybe (x > 0);
(%o3)                         true
Функция: isqrt (x)

Возвращает "целый квадратный корень" абсолютного значения x, которое есть целое.

Функция: lmax (L)

Когда L есть список или множество, возвращает apply ('max, args (L)). Когда L не является списком или множеством, выдает ошибку.

Функция: lmin (L)

Когда L есть список или множество, возвращает apply ('min, args (L)). Когда L не является списком или множеством, выдает ошибку.

Функция: max (x_1, ..., x_n)

Возвращает упрощенное значение максимума выражений от x_1 до x_n. Когда get (trylevel, maxmin) есть 2 или больше, max использует упрощение max (e, -e) --> |e|. Когда get (trylevel, maxmin) есть 3 или больше, max старается исключить выражения, заключенные по значению между двумя другими аргументами. Например, max (x, 2*x, 3*x) --> max (x, 3*x). Для установки значения trylevel в 2, используется put (trylevel, 2, maxmin).

Функция: min (x_1, ..., x_n)

Возвращает упрощенное значение минимума выражений от x_1 до x_n. Когда get (trylevel, maxmin) есть 2 или больше, min использует упрощение min (e, -e) --> -|e|. Когда get (trylevel, maxmin) есть 3 или больше, min старается исключить выражения, заключенные по значению между двумя другими аргументами. Например, min (x, 2*x, 3*x) --> min (x, 3*x). Для установки значения trylevel в 2, используется put (trylevel, 2, maxmin).

Функция: polymod (p)
Функция: polymod (p, m)

Конвертирует многочлен p в модулярное представление, с учетом текущего модуля, которое является значением переменной modulus.

polymod (p, m) определяет модуль m, который будет использоваться вместо текущего значения modulus.

См. modulus.

Функция: mod (x, y)

Если x и y есть вещественные числа и y не отрицательно, возвращает x - y * floor(x / y). Далее для всех вещественных x имеем mod (x, 0) = x. Подробное обсуждение определения mod (x, 0) = x есть в разделе 3.4 "Concrete Mathematics," авторов Graham, Knuth и Patashnik. Функция mod (x, 1) есть пилообразная функция с периодом 1, mod (1, 1) = 0 и mod (0, 1) = 0.

Чтобы найти главный аргумент (число в интервале (-%pi, %pi]) для комплексного числа, используется функция x |-> %pi - mod (%pi - x, 2*%pi), где x есть аргумент.

Когда x и y есть константные выражения (например 10 * %pi), mod использует то же вычисления с числами с плавающей точкой повышенной точности, что и, floor и ceiling. Опять же, возможно, хотя маловероятно, что mod может вернуть ошибочное значение в таких случаях.

Для не численных аргументов x или y, mod знает несколько правил упрощения:

(%i1) mod (x, 0);
(%o1)                           x
(%i2) mod (a*x, a*y);
(%o2)                      a mod(x, y)
(%i3) mod (0, x);
(%o3)                           0
Функция: oddp (expr)

есть true если expr есть нечетное целое. false возвращается во всех других случаях.

Оператор: pred

В качестве аргумента в вызове ev (expr), pred вызывает вычисление предикатов (выражений, которые вычисляются в true или false) . См. ev.

Функция: make_random_state (n)
Функция: make_random_state (s)
Функция: make_random_state (true)
Функция: make_random_state (false)

Объект случайного состояния представляет собой состояние генератора случайных чисел. Оно содержит 627 32-битных слова.

make_random_state (n) возвращает новое случайное состояние объекта созданного из затравочного целого числа, равного n по модулю 2^32. n может быть отрицательным.

make_random_state (s) возвращает копию случайного состояния s.

make_random_state (true) возвращает новое случайное состояние объекта, используя текущее значение часов компьютера в качестве затравочного числа.

make_random_state (false) возвращает копию текущего состояния генератора случайных чисел.

Функция: set_random_state (s)

Копирует s в состояние генератора случайных чисел.

set_random_state всегда возвращает done.

Функция: random (x)

Возвращает псевдослучайное число. Если x есть целое, random (x) возвращает целое в пределах от 0 до x - 1 включительно. Если x есть число с плавающей точкой, random (x) возвращает неотрицательное число с плавающей точкой меньше чем x. Функция random выдает сообщение об ошибке, если x не есть целое, или не число с плавающей точкой, или если x неположительное.

Функции make_random_state и set_random_state сохраняют состояние генератора случайных чисел.

Генератор случайных чисел Maxima - это реализация Mersenne twister MT 19937.

Примеры:

(%i1) s1: make_random_state (654321)$
(%i2) set_random_state (s1);
(%o2)                         done
(%i3) random (1000);
(%o3)                          768
(%i4) random (9573684);
(%o4)                        7657880
(%i5) random (2^75);
(%o5)                11804491615036831636390
(%i6) s2: make_random_state (false)$
(%i7) random (1.0);
(%o7)                   .2310127244107132
(%i8) random (10.0);
(%o8)                   4.394553645870825
(%i9) random (100.0);
(%o9)                   32.28666704056853
(%i10) set_random_state (s2);
(%o10)                        done
(%i11) random (1.0);
(%o11)                  .2310127244107132
(%i12) random (10.0);
(%o12)                  4.394553645870825
(%i13) random (100.0);
(%o13)                  32.28666704056853
Функция: rationalize (expr)

Конвертирует все числа с плавающей точкой двойной точности и повышенной точности в выражении expr в рациональные эквивалентны. Если вы не знакомы с бинарным представлением чисел с плавающей точкой, вы может быть удивлены тем, что rationalize (0.1) не равно 1/10. Это поведение имеет место не только в Maxima – число 1/10 имеет периодическое, не заканчивающееся, двоичное представление.

(%i1) rationalize (0.5);
                                1
(%o1)                           -
                                2
(%i2) rationalize (0.1);
                               1
(%o2)                          --
                               10
(%i3) fpprec : 5$
(%i4) rationalize (0.1b0);
                             209715
(%o4)                        -------
                             2097152
(%i5) fpprec : 20$
(%i6) rationalize (0.1b0);
                     236118324143482260685
(%o6)                ----------------------
                     2361183241434822606848
(%i7) rationalize (sin (0.1*x + 5.6));
                              x    28
(%o7)                     sin(-- + --)
                              10   5

Пример использования:

(%i1) unitfrac(r) := block([uf : [], q],
    if not(ratnump(r)) then
       error("The input to 'unitfrac' must be a rational number"),
    while r # 0 do (
        uf : cons(q : 1/ceiling(1/r), uf),
        r : r - q),
    reverse(uf));
(%o1) unitfrac(r) := block([uf : [], q], 
if not ratnump(r) then
   error("The input to 'unitfrac' must be a rational number"),
                                  1
while r # 0 do (uf : cons(q : ----------, uf), r : r - q), 
                                      1
                              ceiling(-)
                                      r
reverse(uf))
(%i2) unitfrac (9/10);
                            1  1  1
(%o2)                      [-, -, --]
                            2  3  15
(%i3) apply ("+", %);
                               9
(%o3)                          --
                               10
(%i4) unitfrac (-9/10);
                                  1
(%o4)                       [- 1, --]
                                  10
(%i5) apply ("+", %);
                                9
(%o5)                         - --
                                10
(%i6) unitfrac (36/37);
                        1  1  1  1    1
(%o6)                  [-, -, -, --, ----]
                        2  3  8  69  6808
(%i7) apply ("+", %);
                               36
(%o7)                          --
                               37
Функция: round (x)

Если x является вещественным числом, то возвращает ближайшее к x целое. Числа, кратные 1/2, округляются до ближайшего четного целого. Вычисление x аналогично функциям floor и ceiling.

Функция: sign (expr)

Пытается определить знак expr на основе фактов в текущей базе данных. Она возвращает один из следующих ответов: pos (положительное), neg (отрицательное), zero (нулевое), pz (положительное или ноль), nz (отрицательное или ноль), pn (положительное или отрицательное), или pnz (положительное, отрицательное или ноль, т.е. ничего не известно).

Функция: signum (x)

Для численного значения x, возвращает 0, если x есть 0, иначе возвращает -1 или +1, когда x меньше чем или больше чем 0, соответственно.

Если x не есть численное значение, то возвращается эквивалентная, но упрощенная форма. Например, signum(-x) дает -signum(x).

Функция: sort (L, P)
Функция: sort (L)

Сортирует список L согласно предикату P двух аргументов, так чтобы P (L[k], L[k + 1]) было равно true для любых двух последовательных элементов. Предикат может быть задан как имя функции или бинарный инфиксный оператор, или как лямбда-выражение. Если он задан как имя оператора, это имя берется в "двойные кавычки".

Отсортированный список возвращается как новый объект; аргумент L не изменяется. При возврате значения, sort делает копию верхнего уровня (shallow copy) элементов L.

Если предикат P не задает полное упорядочивание элементов L, то sort может пробежать до конца без ошибки, но результат будет неопределенный. sort выдает сообщение, если предикат вычисляется до чего-то отличного от true или false.

sort (L) эквивалентно sort (L, orderlessp). То есть, порядок сортировки по умолчанию будет восходящим, как определено для orderlessp. Все Maxima атомы и выражения сравнимы по orderlessp, хотя есть отдельные примеры выражений, для которых orderlessp не транзитивна (это ошибка).

Примеры:

(%i1) sort ([11, -17, 29b0, 7.55, 3, -5/2, b + a, 9 * c,
      19 - 3 * x]);
               5
(%o1) [- 17, - -, 3, 7.55, 11, 2.9b1, b + a, 9 c, 19 - 3 x]
               2
(%i2) sort ([11, -17, 29b0, 7.55, 3, -5/2, b + a, 9*c, 19 - 3*x],
      ordergreatp);
                                                   5
(%o2) [19 - 3 x, 9 c, b + a, 2.9b1, 11, 7.55, 3, - -, - 17]
                                                   2
(%i3) sort ([%pi, 3, 4, %e, %gamma]);
(%o3)                [3, 4, %e, %gamma, %pi]
(%i4) sort ([%pi, 3, 4, %e, %gamma], "<");
(%o4)                [%gamma, %e, 3, %pi, 4]
(%i5) my_list: [[aa,hh,uu], [ee,cc], [zz,xx,mm,cc], [%pi,%e]];
(%o5) [[aa, hh, uu], [ee, cc], [zz, xx, mm, cc], [%pi, %e]]
(%i6) sort (my_list);
(%o6) [[%pi, %e], [aa, hh, uu], [ee, cc], [zz, xx, mm, cc]]
(%i7) sort (my_list, lambda ([a, b], orderlessp (reverse (a),
      reverse (b))));
(%o7) [[%pi, %e], [ee, cc], [zz, xx, mm, cc], [aa, hh, uu]]
Функция: sqrt (x)

Квадратный корень x. Внутренне представляется как x^(1/2). См. также rootscontract.

radexpand, если true, вызовет то, что n-ные корни множителей произведения, которые есть степени n, будут вынесены за пределы радикала. Например, sqrt(16*x^2) станет 4*x, только если radexpand есть true.

Управляющая переменная: sqrtdispflag

Значение по умолчанию: true

Когда sqrtdispflag есть false, то sqrt выводится как степень с показателем 1/2.

Функция: sublis (list, expr)

Производит множественные параллельные подстановки в выражение.

Переменная sublis_apply_lambda управляет упрощением после sublis.

Пример:

(%i1) sublis ([a=b, b=a], sin(a) + cos(b));
(%o1)                    sin(b) + cos(a)
Функция: sublist (list, p)

Возвращает список элементов list, для которого предикат p возвращает true.

Пример:

(%i1) L: [1, 2, 3, 4, 5, 6];
(%o1)                  [1, 2, 3, 4, 5, 6]
(%i2) sublist (L, evenp);
(%o2)                       [2, 4, 6]
Управляющая переменная: sublis_apply_lambda

Значение по умолчанию: true

Управляет, будет ли подстановки для lambda применены в упрощении, после того как используется sublis или нужно ли выполнить ev, чтобы эти элементы применились. true означает - выполнить применение.

Функция: subst (a, b, c)

Делает подстановку a для b в c. b должен быть атомом или полным подвыражением в c. Например, x+y+z есть полное подвыражение 2*(x+y+z)/w, а x+y нет. Когда b не имеет эти характеристики, можно иногда использовать substpart или ratsubst (см. ниже). Альтернативно, если b задано в форме e/f, то можно использовать subst (a*f, e, c), в то время как, если b задано в форме e^(1/f), то можно использовать subst (a^f, e, c). subst также различает x^y в x^-y, так что subst (a, sqrt(x), 1/sqrt(x)) дает 1/a. Аргументы a и b могут также быть операторами выражения, заключенными в двойные кавычки ", или могут быть именами функций. Если есть желание подставить независимую переменную в производных формах, то следует использовать функцию at (см. ниже).

subst - это псевдоним для substitute.

Выражения subst (eq_1, expr) или subst ([eq_1, ..., eq_k], expr) - есть другие допустимые формы. eq_i - уравнения, указывающие какие подстановки нужно сделать. Для каждого уравнения, правая сторона будет подставлена вместо левой в выражении expr.

Если exptsubst равно true, то позволяются подстановки, на подобии y для %e^x в %e^(a*x).

Когда opsubst есть false, subst не пытается подставить в оператор выражения. Например, (opsubst: false, subst (x^2, r, r+r[0])) будет работать.

Примеры:

(%i1) subst (a, x+y, x + (x+y)^2 + y);
                                    2
(%o1)                      y + x + a
(%i2) subst (-%i, %i, a + b*%i);
(%o2)                       a - %i b

Чтобы узнать о других примерах, выполните example (subst).

Функция: substinpart (x, expr, n_1, ..., n_k)

Аналогично substpart, но substinpart работает с внутренним представление expr.

Примеры:

(%i1) x . 'diff (f(x), x, 2);
                              2
                             d
(%o1)                   x . (--- (f(x)))
                               2
                             dx
(%i2) substinpart (d^2, %, 2);
                                  2
(%o2)                        x . d
(%i3) substinpart (f1, f[1](x + 1), 0);
(%o3)                       f1(x + 1)

Если последний аргумент функции part есть список индексов, то будут выбраны несколько подвыражений, каждый из которых будет соответствовать индексу в списке. Таким образом

(%i1) part (x + y + z, [1, 3]);
(%o1)                         z + x

Переменная piece содержит значение последнего выражения, выбранного при использовании функции part. Оно устанавливается во время выполнения функции и, таким образом, может быть передано в саму функцию как показано ниже. Если partswitch равно true, то end возвращается когда выбранная часть выражения не существует, иначе выдается сообщение об ошибке.

(%i1) expr: 27*y^3 + 54*x*y^2 + 36*x^2*y + y + 8*x^3 + x + 1;
              3         2       2            3
(%o1)     27 y  + 54 x y  + 36 x  y + y + 8 x  + x + 1
(%i2) part (expr, 2, [1, 3]);
                                  2
(%o2)                         54 y
(%i3) sqrt (piece/54);
(%o3)                        abs(y)
(%i4) substpart (factor (piece), expr, [1, 2, 3, 5]);
                               3
(%o4)               (3 y + 2 x)  + y + x + 1
(%i5) expr: 1/x + y/x - 1/z;
                             1   y   1
(%o5)                      - - + - + -
                             z   x   x
(%i6) substpart (xthru (piece), expr, [2, 3]);
                            y + 1   1
(%o6)                       ----- - -
                              x     z

Также, установка опции inflag в true и вызов part или substpart есть тоже самое, что и вызов inpart или substinpart.

Функция: substpart (x, expr, n_1, ..., n_k)

Делает подстановку x в подвыражение, выбираемое последними аргументами, как в part. Возвращает новое значение expr. x может быть некоторым оператором для подстановки вместо оператора в expr. В некоторых случаях x нужно заключать в двойной кавычки " (Например, substpart ("+", a*b, 0) дает b + a).

(%i1) 1/(x^2 + 2);
                               1
(%o1)                        ------
                              2
                             x  + 2
(%i2) substpart (3/2, %, 2, 1, 2);
                               1
(%o2)                       --------
                             3/2
                            x    + 2
(%i3) a*x + f(b, y);
(%o3)                     a x + f(b, y)
(%i4) substpart ("+", %, 1, 0);
(%o4)                    x + f(b, y) + a

Также, установка опции inflag в true и вызов part или substpart, есть тоже самое, что и вызов inpart или substinpart.

Функция: subvarp (expr)

Возвращает true, если expr есть переменная с индексом, например a[i].

Функция: symbolp (expr)

Возвращает true, если expr есть символ, иначе false. На самом деле, symbolp(x) эквивалентно предикату atom(x) and not numberp(x).

См. также Идентификаторы.

Функция: unorder ()

Блокирует связывания, созданные последним вызовом упорядочивающих команд ordergreat и orderless. ordergreat и orderless не могут использоваться больше одного раза каждый, без вызова unorder. См. также ordergreat и orderless.

Примеры:

(%i1) unorder();
(%o1)                          []
(%i2) b*x + a^2;
                                   2
(%o2)                       b x + a
(%i3) ordergreat (a);
(%o3)                         done
(%i4) b*x + a^2;
 %th(1) - %th(3);
                             2
(%o4)                       a  + b x
(%i5) unorder();
                              2    2
(%o5)                        a  - a
Функция: vectorpotential (givencurl)

Возвращает векторный потенциал заданного вектора кручения, в текущей системе координат. potentialzeroloc имеет аналогичную роль для potential, но порядок левосторонних частей уравнений должен быть циклической перестановкой координатных переменных.

Функция: xthru (expr)

Объединяет все члены expr (которое должно быть суммой) для общего знаменателя без раскрытия произведений и степеней сумм, что делает ratsimp. Функция xthru сокращает общие множители в числителе и знаменателе рациональных выражений, но только если эти множители явные.

Иногда лучше использовать xthru перед выражением, упрощенным с помощью ratsimp, для того чтобы вызывать сокращение явных множителей наибольшего общего делителя числителя и знаменателя, таким образом, упрощая выражение перед ratsimp.

(%i1) ((x+2)^20 - 2*y)/(x+y)^20 + (x+y)^(-19) - x/(x+y)^20;
                                20
                 1       (x + 2)   - 2 y       x
(%o1)        --------- + --------------- - ---------
                    19             20             20
             (y + x)        (y + x)        (y + x)
(%i2) xthru (%);
                                 20
                          (x + 2)   - y
(%o2)                     -------------
                                   20
                            (y + x)
Функция: zeroequiv (expr, v)

Проверяет эквивалентно ли выражение expr в переменной v нулю, возвращает true, false или dontknow.

zeroequiv имеет следующие ограничения:

  1. Не используйте функции, для которых Maxima не знает как их дифференцировать и вычислять.
  2. Если выражение имеет полюсы на вещественной прямой, могут быть ошибки в результате (это может произойти с малой вероятностью).
  3. Если выражение содержит функции, который не являются решением дифференциальных уравнений первого порядка (например, функции Бесселя), могут быть некорректные результаты.
  4. Этот алгоритм использует вычисление в случайно выбранных точках для аккуратно выбранных подвыражений. Это всегда, в некотором смысле, рискованное дело, хотя алгоритм пытается минимизировать возможность ошибки.

Например zeroequiv (sin(2*x) - 2*sin(x)*cos(x), x) возвращает true и zeroequiv (%e^x + x, x) возвращает false. С другой стороны zeroequiv (log(a*b) - log(a) - log(b), a) возвращает dontknow из-за присутствия дополнительного параметра b.


Next: , Previous: Операторы, Up: Top   [Contents][Index]

6 Выражения


Next: , Previous: Выражения, Up: Выражения   [Contents][Index]

6.1 Основные сведения о выражениях

Есть некоторое число зарезервированных слов, которые не могут быть использованы как имена переменных. Их использование может вызвать скрытую синтаксическую ошибку.

integrate            next           from                 diff            
in                   at             limit                sum             
for                  and            elseif               then            
else                 do             or                   if              
unless               product        while                thru            
step                                                                     

Большинство сущностей в Maxima являются выражениями. Последовательность выражений может превратиться в одно выражение, если элементы последовательности разделены запятыми и последовательность взята в скобки. Это аналогично подобным выражениям последовательного вычисления (comma expressions) в языке программирования C.

(%i1) x: 3$
(%i2) (x: x+1, x: x^2);
(%o2)                          16
(%i3) (if (x > 17) then 2 else 4);
(%o3)                           4
(%i4) (if (x > 17) then x: 2 else y: 4, y+x);
(%o4)                          20

Даже циклы в Maxima являются выражениями, хотя то значение, которое они возвращают, не слишком полезное done.

(%i1) y: (x: 1, for i from 1 thru 10 do (x: x*i))$
(%i2) y;
(%o2)                         done

То, что Вы действительно хотите получить, нужно включить как третий аргумент в выражение последовательного вычисления, который в действительности возвращает значение.

(%i3) y: (x: 1, for i from 1 thru 10 do (x: x*i), x)$
(%i4) y;
(%o4)                        3628800

Next: , Previous: Основные сведения о выражениях, Up: Выражения   [Contents][Index]

6.2 Комплексные выражения

Комплексное выражение задается в Maxima добавлением к вещественной части выражения %i, умноженного на мнимую часть. Таким образом, корни уравнения x^2 - 4*x + 13 = 0 равны 2 + 3*%i и 2 - 3*%i. Заметим, что упрощение произведений комплексных выражений может произойти после раскрытия произведения. Упрощение отношений, корней и других функций комплексных выражений, обычно, может быть произведено, с использованием функций realpart, imagpart, rectform, polarform, abs и carg.


Next: , Previous: Комплексные выражения, Up: Выражения   [Contents][Index]

6.3 Невычисляемые и вычисляемые формы

Maxima различает операторы, которые являются невычисляемыми (nouns) и операторы, который являются вычисляемыми (verbs). Вычисляемым является оператор, который может быть выполнен. Невычисляемым является оператор, который встречается как символ в выражении, без вычисления. По умолчанию, имена функций является вычисляемыми. Вычисляемая форма может быть переведена в невычисляемую, экранированием (quoting) имени функции или применением функции nounify. Невычисляемая форма может быть переведена в вычисляемую, применением функции verbify. Флаг вычисления nouns вызывает функцию ev для вычисления невычисляемых форм в выражении.

Вычисляемая форма отличается первым знаком доллара $ в соответствующем Lisp-символе. Невычисляемая форма, наоборот, отличается первым знаком процента % в соответствующем Lisp-символе. Некоторые невычисляемые формы, такие как 'integrate и 'derivative (возвращаемые diff), имеют специальные свойства вывода, но не всегда. По умолчанию, невычисляемые и вычисляемые формы функции идентичны при выводе. Глобальный флаг noundisp вызывает то, что Maxima выводит невычисляемые формы с предшествующей одиночной кавычкой '.

См. также noun, nouns, nounify и verbify.

Примеры:

(%i1) foo (x) := x^2;
                                     2
(%o1)                     foo(x) := x
(%i2) foo (42);
(%o2)                         1764
(%i3) 'foo (42);
(%o3)                        foo(42)
(%i4) 'foo (42), nouns;
(%o4)                         1764
(%i5) declare (bar, noun);
(%o5)                         done
(%i6) bar (x) := x/17;
                                     x
(%o6)                    ''bar(x) := --
                                     17
(%i7) bar (52);
(%o7)                        bar(52)
(%i8) bar (52), nouns;
                               52
(%o8)                          --
                               17
(%i9) integrate (1/x, x, 1, 42);
(%o9)                        log(42)
(%i10) 'integrate (1/x, x, 1, 42);
                             42
                            /
                            [   1
(%o10)                      I   - dx
                            ]   x
                            /
                             1
(%i11) ev (%, nouns);
(%o11)                       log(42)

Next: , Previous: Невычисляемые и вычисляемые формы, Up: Выражения   [Contents][Index]

6.4 Идентификаторы

Идентификаторы Maxima могут содержать буквы алфавита, плюс цифры от 0 до 9, плюс любые специальные символы, с предшествующим знаком \.

Цифра может быть первым символом идентификатора, если ей предшествует бэкслеш \. Для цифр, которые являются вторыми или последующими символами, бэкслеш не нужен.

Специальный символ может быть объявлен алфавитным, с помощью функции declare. Если это так, его не нужно экранировать бэкслешом в идентификаторе. Изначально к алфавитным символам относятся A до Z, a до z, % и _.

Maxima чувствительна к регистру символов. Идентификаторы foo, FOO и Foo различны. Для дальнейших сведений по этому вопросу смотрите Lisp и Maxima.

Maxima идентификатор является Lisp-символом, который начинается со знака доллар $. Любой другой Lisp-символ, когда он встречается в Maxima, предваряется знаком вопроса ?. См. Lisp и Maxima для более подробной информации по этому вопросу.

Примеры:

(%i1) %an_ordinary_identifier42;
(%o1)               %an_ordinary_identifier42
(%i2) embedded\ spaces\ in\ an\ identifier;
(%o2)           embedded spaces in an identifier
(%i3) symbolp (%);
(%o3)                         true
(%i4) [foo+bar, foo\+bar];
(%o4)                 [foo + bar, foo+bar]
(%i5) [1729, \1729];
(%o5)                     [1729, 1729]
(%i6) [symbolp (foo\+bar), symbolp (\1729)];
(%o6)                     [true, true]
(%i7) [is (foo\+bar = foo+bar), is (\1729 = 1729)];
(%o7)                    [false, false]
(%i8) baz\~quux;
(%o8)                       baz~quux
(%i9) declare ("~", alphabetic);
(%o9)                         done
(%i10) baz~quux;
(%o10)                      baz~quux
(%i11) [is (foo = FOO), is (FOO = Foo), is (Foo = foo)];
(%o11)                [false, false, false]
(%i12) :lisp (defvar *my-lisp-variable* '$foo)
*MY-LISP-VARIABLE*
(%i12) ?\*my\-lisp\-variable\*;
(%o12)                         foo

Next: , Previous: Идентификаторы, Up: Выражения   [Contents][Index]

6.5 Строки

Строки (последовательности символов в кавычках) заключаются в двойные кавычки " при вводе и выводятся с или без кавычек, в зависимости от значения глобальной переменной stringdisp.

Строки могут содержать любые символы, включая символы табуляции, новой строки и возврат каретки. Последовательность \" распознается как литерал двойной кавычки, а \\ как литерал бэкслеша. Когда бэкслеш появляется в конце строки, то бэкслеш и символ завершение строки (либо новая строка, либо возврат каретки) игнорируются, так что данная строка продолжается со следующей строки. Никакие другие специальные комбинации бэкслеша с другим символом не распознаются. Если бэкслеш появляется перед любым символом, отличным от ", \, или конец строки, то он игнорируется. Нет других способов для представления специальных символов (таких как табуляция, новая строка или возврат каретки) кроме как вставка этого символа в строку.

В Maxima нет типа одиночный символ. Одиночный символ представляется как одно-символьная строка.

Дополнительный пакет stringproc содержит много функций для работы со строками.

Примеры:

(%i1) s_1 : "This is a string.";
(%o1)               This is a string.
(%i2) s_2 : "Embedded \"double quotes\" and backslash \\ characters.";
(%o2) Embedded "double quotes" and backslash \ characters.
(%i3) s_3 : "Embedded line termination
in this string.";
(%o3) Embedded line termination
in this string.
(%i4) s_4 : "Ignore the \
line termination \
characters in \
this string.";
(%o4) Ignore the line termination characters in this string.
(%i5) stringdisp : false;
(%o5)                         false
(%i6) s_1;
(%o6)                   This is a string.
(%i7) stringdisp : true;
(%o7)                         true
(%i8) s_1;
(%o8)                  "This is a string."

Next: , Previous: Строки, Up: Выражения   [Contents][Index]

6.6 Неравенства

Maxima имеет операторы неравенства <, <=, >=, >, # и notequal. См. if для описания условных выражений.


Next: , Previous: Неравенства, Up: Выражения   [Contents][Index]

6.7 Синтаксис

Возможно определять новые операторы с заданным приоритетом, удалять определения существующих операторов или переопределять приоритет существующих операторов. Оператор может быть унарным префиксным или унарным постфиксным, бинарным инфиксным, n-арным (n-ary) инфиксным, матчфиксным (matchfix) или безфиксным (nofix). Матчфиксный (matchfix) обозначает пару символов, которые заключают между собой свой аргумент или аргументы, а безфиксный (nofix) означает оператор, который не принимает аргументы. Следующие примеры демонстрируют различные типы операторов.

унарный префиксный

изменение знака - a

унарный постфиксный

факториал a!

бинарный инфиксный

экспонента a^b

n-арный инфиксный

сложение a + b

матчфиксный

список [a, b]

(Встроенных безфиксных операторов нет; для примера такого оператора см. nofix.)

Механизм определения нового оператора прост. Необходимо только объявить функцию как оператор; сама функция оператора может быть определена или нет.

Вот пример определенных пользователем операторов. Заметим, что явный вызов функции "dd" (a) эквивалентен dd a, также как "<-" (a, b) эквивалентно a <- b. Заметим также, что функции "dd" и "<-" не определены в этом примере.

(%i1) prefix ("dd");
(%o1)                          dd
(%i2) dd a;
(%o2)                         dd a
(%i3) "dd" (a);
(%o3)                         dd a
(%i4) infix ("<-");
(%o4)                          <-
(%i5) a <- dd b;
(%o5)                      a <- dd b
(%i6) "<-" (a, "dd" (b));
(%o6)                      a <- dd b

Maxima функции, которые определяют новые операторы, сведены в нижеследующей таблице, с установленными по умолчанию левыми и правыми степенями связывания (lbp и rbp, соответственно). (Степень связывания определяет приоритет операторов. Однако, так как левые и правые степени связывания могут отличаться, степень связывания - это что-то более сложное чем приоритет.) Некоторые функции определения операций принимают дополнительные аргументы, см. описания этих функций для более полного описания деталей.

prefix

rbp=180

postfix

lbp=180

infix

lbp=180, rbp=180

nary

lbp=180, rbp=180

matchfix

(степень связывания не применима)

nofix

(степень связывания не применима)

Для сравнения, приведем некоторые встроенные операторы, и их левые и правые степени связывания.

Operator   lbp     rbp

  :        180     20 
  ::       180     20 
  :=       180     20 
  ::=      180     20 
  !        160
  !!       160
  ^        140     139 
  .        130     129 
  *        120
  /        120     120 
  +        100     100 
  -        100     134 
  =        80      80 
  #        80      80 
  >        80      80 
  >=       80      80 
  <        80      80 
  <=       80      80 
  not              70 
  and      65
  or       60
  ,        10
  $        -1
  ;        -1

remove и kill удаляют свойства оператора из атома. remove ("a", op) удаляет только свойства оператора a. kill ("a") удаляет все свойства a, включая свойства оператора. Заметим, что имя оператора должно быть взято в кавычки.

(%i1) infix ("@");
(%o1)                           @
(%i2) "@" (a, b) := a^b;
                                     b
(%o2)                      a @ b := a
(%i3) 5 @ 3;
(%o3)                          125
(%i4) remove ("@", op);
(%o4)                         done
(%i5) 5 @ 3;
Incorrect syntax: @ is not an infix operator
5 @
 ^
(%i5) "@" (5, 3);
(%o5)                          125
(%i6) infix ("@");
(%o6)                           @
(%i7) 5 @ 3;
(%o7)                          125
(%i8) kill ("@");
(%o8)                         done
(%i9) 5 @ 3;
Incorrect syntax: @ is not an infix operator
5 @
 ^
(%i9) "@" (5, 3);
(%o9)                        @(5, 3)

Previous: Синтаксис, Up: Выражения   [Contents][Index]

6.8 Функции и переменные для выражений

Функция: at (expr, [eqn_1, ..., eqn_n])
Функция: at (expr, eqn)

Вычисляет выражение expr, предполагая значения для переменных, заданные в списке уравнений [eqn_1, ..., eqn_n] или одном уравнении eqn.

Если подвыражение зависит от переменных, для которых заданы значения, но нет, заданного при помощи atvalue значения, или оно не может быть вычислено иным способом, то возвращается невычисляемая форма at, которая выводится в двумерном формате.

Функция at выполняет множественные подстановки последовательно, не параллельно.

См. также atvalue. Для описания других функций, которые выполняют подстановки, см. также subst и ev.

Примеры:

(%i1) atvalue (f(x,y), [x = 0, y = 1], a^2);
                                2
(%o1)                          a
(%i2) atvalue ('diff (f(x,y), x), x = 0, 1 + y);
(%o2)                        @2 + 1
(%i3) printprops (all, atvalue);
                                !
                  d             !
                 --- (f(@1, @2))!       = @2 + 1
                 d@1            !
                                !@1 = 0

                                     2
                          f(0, 1) = a

(%o3)                         done
(%i4) diff (4*f(x, y)^2 - u(x, y)^2, x);
                  d                          d
(%o4)  8 f(x, y) (-- (f(x, y))) - 2 u(x, y) (-- (u(x, y)))
                  dx                         dx
(%i5) at (%, [x = 0, y = 1]);
                                         !
              2              d           !
(%o5)     16 a  - 2 u(0, 1) (-- (u(x, y))!            )
                             dx          !
                                         !x = 0, y = 1
Функция: box (expr)
Функция: box (expr, a)

Возвращает expr, заключенное в бокс (box). Возвращаемое значение есть выражение с box в качестве оператора и expr как аргумент. Бокс изображается при выводе, когда display2d есть true.

box (expr, a) заключает expr в бокс, обозначенный символом a. Эта метка обрезается, если она длиннее чем ширина бокса.

box вычисляет свои аргументы. Однако, выражение, взятое в бокс, не вычисляется до его содержимого, так что выражения в боксе эффективно исключается из вычислений.

boxchar есть символ, используемый для отображения бокса в функциях box, в dpart и в lpart.

Примеры:

(%i1) box (a^2 + b^2);
                            """""""""
                            " 2    2"
(%o1)                       "b  + a "
                            """""""""
(%i2) a : 1234;
(%o2)                         1234
(%i3) b : c - d;
(%o3)                         c - d
(%i4) box (a^2 + b^2);
                      """"""""""""""""""""
                      "       2          "
(%o4)                 "(c - d)  + 1522756"
                      """"""""""""""""""""
(%i5) box (a^2 + b^2, term_1);
                      term_1""""""""""""""
                      "       2          "
(%o5)                 "(c - d)  + 1522756"
                      """"""""""""""""""""
(%i6) 1729 - box (1729);
                                 """"""
(%o6)                     1729 - "1729"
                                 """"""
(%i7) boxchar: "-";
(%o7)                           -
(%i8) box (sin(x) + cos(y));
                        -----------------
(%o8)                   -cos(y) + sin(x)-
                        -----------------
Управляющая переменная: boxchar

Значение по умолчанию: "

boxchar есть символ, который используется для изображения бокса в функциях box, в dpart и в lpart .

Все боксы в выражении изображаются с текущим значением boxchar. Изображаемый символ не сохраняется в выражении бокса.

Функция: carg (z)

Возвращает комплексный аргумент z. Этот комплексный аргумент есть угол theta в пределах (-%pi, %pi] такой что r exp (theta %i) = z, где r есть модуль z.

carg есть вычислительная функция, но не функция упрощения.

carg игнорирует декларацию declare (x, complex) и рассматривает x как вещественную переменную. Это ошибка.

См. также abs (комплексный модуль), polarform, rectform, realpart и imagpart.

Примеры:

(%i1) carg (1);
(%o1)                           0
(%i2) carg (1 + %i);
                               %pi
(%o2)                          ---
                                4
(%i3) carg (exp (%i));
(%o3)                           1
(%i4) carg (exp (%pi * %i));
(%o4)                          %pi
(%i5) carg (exp (3/2 * %pi * %i));
                                %pi
(%o5)                         - ---
                                 2
(%i6) carg (17 * exp (2 * %i));
(%o6)                           2
Специальный оператор: constant

declare (a, constant) объявляет a как константу. См. declare.

Функция: constantp (expr)

Возвращает true, если expr есть константное выражение, иначе возвращает false.

Выражение рассматривается как константное, если его аргументы есть числа (включая рациональные числа, которые отображаются с помощью /R/), символьные константы, такие как %pi, %e и %i, переменные, равные константами, или объявленные константами с помощью declare, или функции, чьи аргументы есть константы.

constantp вычисляет свои аргументы.

Примеры:

(%i1) constantp (7 * sin(2));
(%o1)                                true
(%i2) constantp (rat (17/29));
(%o2)                                true
(%i3) constantp (%pi * sin(%e));
(%o3)                                true
(%i4) constantp (exp (x));
(%o4)                                false
(%i5) declare (x, constant);
(%o5)                                done
(%i6) constantp (exp (x));
(%o6)                                true
(%i7) constantp (foo (x) + bar (%e) + baz (2));
(%o7)                                false
(%i8) 
Функция: declare (a_1, p_1, a_2, p_2, ...)

Присваивает атому или списку атомов a_i свойство или список свойств p_i. Когда a_i и/или p_i есть списки, каждый из атомом получает все свойства.

declare не вычисляет свои аргументы. declare всегда возвращает done.

Как отмечено в описании для каждого флага декларации, для некоторых флагов featurep(object, feature) возвращает true, если object был объявлен, как имеющий feature. Однако, featurep не распознает некоторые флаги. Это ошибка.

См. также features.

declare распознает следующие свойства:

evfun

Делает a_i известным для ev так, что эта функция названная как a_i, применяется когда a_i появляется как флаговый аргумент ev. См. evfun.

evflag

Делает a_i известным для функции ev так, что a_i связывается с true во время выполнение ev, когда a_i появляется как флаговый аргумент ev. См. evflag.

bindtest

Указывает Maxima то, что следует вызвать ошибку, когда при вычислении значение a_i не определено.

noun

Указывает Maxima считать a_i невычисляемой формой. Эффект состоит в замене a_i на 'a_i или nounify(a_i), в зависимости от контекста.

constant

Указывает Maxima рассматривать a_i как символьную константу.

scalar

Указывает Maxima рассматривать a_i как скалярную переменную.

nonscalar

Указывает Maxima рассматривать a_i как нескалярную переменную. Обычное применение состоит в том, чтобы объявлять переменная как символьный вектор или матрицу.

mainvar

Указывает Maxima рассматривать a_i как "главную переменную" (mainvar). ordergreatp определяет упорядочивание атомов таким образом:

(главные переменные) > (другие переменные) > (скалярный переменные) > (константы) > (числа)

alphabetic

Указывает Maxima рассматривать a_i как алфавитный символ.

feature

Указывает Maxima рассматривать a_i как имя свойства. Тогда другие атомы могут иметь свойство a_i.

rassociative, lassociative

Указывает Maxima рассматривать a_i как право-ассоциативную или лево-ассоциативную функцию.

nary

Указывает Maxima рассматривать a_i как n-арную функцию.

Декларация nary это не тоже, что вызов функции nary. Единственный эффект declare(foo, nary) состоит в том, чтобы обучить упрощатель Maxima упрощать вложенные выражения, например, чтобы foo(x, foo(y, z)) упрощалось до foo(x, y, z).

symmetric, antisymmetric, commutative

Указывает Maxima рассматривать a_i как симметричную или антисимметричную функцию. commutative это тоже самое, что symmetric.

oddfun, evenfun

Указывает Maxima рассматривать a_i как нечетную или четную функцию.

outative

Указывает Maxima упрощать выражения с a_i путем выноса константных множителей за пределы первого аргумента.

Когда a_i имеет один аргумент, множитель рассматривается константным, если он есть литерал или объявлен константой.

Когда a_i имеет два или более аргументов, множитель рассматривается константой, если второй аргумент есть символ и этот множитель свободен от этого второго аргумента.

multiplicative

Указывает Maxima упрощать выражения a_i путем подстановки a_i(x * y * z * ...) --> a_i(x) * a_i(y) * a_i(z) * .... Эта подстановка выполняется только для первого аргумента.

additive

Указывает Maxima упрощать a_i выражения путем подстановки a_i(x + y + z + ...) --> a_i(x) + a_i(y) + a_i(z) + .... Эта подстановка выполняется только для первого аргумента.

linear

Эквивалентно объявлению a_i совместно outative и additive.

integer, noninteger

Указывает Maxima рассматривать a_i как целую или нецелую переменную.

even, odd

Указывает Maxima рассматривать a_i как четную или нечетную целую переменную.

rational, irrational

Указывает Maxima рассматривать a_i как рациональную или иррациональную вещественную переменную.

real, imaginary, complex

Указывает Maxima рассматривать a_i как вещественную, чисто мнимую или комплексную переменную.

increasing, decreasing

Указывает Maxima рассматривать a_i как растущую или убывающую функцию.

posfun

Указывает Maxima рассматривать a_i как положительную функцию.

integervalued

Указывает Maxima рассматривать a_i как целочисленную функцию.

Примеры:

Декларации evfun и evflag.

(%i1) declare (expand, evfun);
(%o1)                         done
(%i2) (a + b)^3;
                                   3
(%o2)                       (b + a)
(%i3) (a + b)^3, expand;
                     3        2      2      3
(%o3)               b  + 3 a b  + 3 a  b + a
(%i4) declare (demoivre, evflag);
(%o4)                         done
(%i5) exp (a + b*%i);
                             %i b + a
(%o5)                      %e
(%i6) exp (a + b*%i), demoivre;
                      a
(%o6)               %e  (%i sin(b) + cos(b))

Декларация bindtest.

(%i1) aa + bb;
(%o1)                        bb + aa
(%i2) declare (aa, bindtest);
(%o2)                         done
(%i3) aa + bb;
aa unbound variable
 -- an error.  Quitting.  To debug this try debugmode(true);
(%i4) aa : 1234;
(%o4)                         1234
(%i5) aa + bb;
(%o5)                       bb + 1234

Декларация noun.

(%i1) factor (12345678);
                             2
(%o1)                     2 3  47 14593
(%i2) declare (factor, noun);
(%o2)                         done
(%i3) factor (12345678);
(%o3)                   factor(12345678)
(%i4) ''%, nouns;
                             2
(%o4)                     2 3  47 14593

Декларации constant, scalar, nonscalar и mainvar.

Декларация alphabetic.

(%i1) xx\~yy : 1729;
(%o1)                         1729
(%i2) declare ("~", alphabetic);
(%o2)                         done
(%i3) xx~yy + yy~xx + ~xx~~yy~;
(%o3)                ~xx~~yy~ + yy~xx + 1729

Декларация feature.

(%i1) declare (FOO, feature);
(%o1)                         done
(%i2) declare (x, FOO);
(%o2)                         done
(%i3) featurep (x, FOO);
(%o3)                         true

Декларации rassociative и lassociative.

Декларация nary.

(%i1) H (H (a, b), H (c, H (d, e)));
(%o1)               H(H(a, b), H(c, H(d, e)))
(%i2) declare (H, nary);
(%o2)                         done
(%i3) H (H (a, b), H (c, H (d, e)));
(%o3)                   H(a, b, c, d, e)

Декларации symmetric и antisymmetric.

(%i1) S (b, a);
(%o1)                        S(b, a)
(%i2) declare (S, symmetric);
(%o2)                         done
(%i3) S (b, a);
(%o3)                        S(a, b)
(%i4) S (a, c, e, d, b);
(%o4)                   S(a, b, c, d, e)
(%i5) T (b, a);
(%o5)                        T(b, a)
(%i6) declare (T, antisymmetric);
(%o6)                         done
(%i7) T (b, a);
(%o7)                       - T(a, b)
(%i8) T (a, c, e, d, b);
(%o8)                   T(a, b, c, d, e)

Декларации oddfun и evenfun.

(%i1) o (- u) + o (u);
(%o1)                     o(u) + o(- u)
(%i2) declare (o, oddfun);
(%o2)                         done
(%i3) o (- u) + o (u);
(%o3)                           0
(%i4) e (- u) - e (u);
(%o4)                     e(- u) - e(u)
(%i5) declare (e, evenfun);
(%o5)                         done
(%i6) e (- u) - e (u);
(%o6)                           0

Декларация outative.

(%i1) F1 (100 * x);
(%o1)                       F1(100 x)
(%i2) declare (F1, outative);
(%o2)                         done
(%i3) F1 (100 * x);
(%o3)                       100 F1(x)
(%i4) declare (zz, constant);
(%o4)                         done
(%i5) F1 (zz * y);
(%o5)                       zz F1(y)

Декларация multiplicative.

(%i1) F2 (a * b * c);
(%o1)                       F2(a b c)
(%i2) declare (F2, multiplicative);
(%o2)                         done
(%i3) F2 (a * b * c);
(%o3)                   F2(a) F2(b) F2(c)

Декларация additive.

(%i1) F3 (a + b + c);
(%o1)                     F3(c + b + a)
(%i2) declare (F3, additive);
(%o2)                         done
(%i3) F3 (a + b + c);
(%o3)                 F3(c) + F3(b) + F3(a)

Декларация linear.

(%i1) 'sum (F(k) + G(k), k, 1, inf);
                       inf
                       ====
                       \
(%o1)                   >    (G(k) + F(k))
                       /
                       ====
                       k = 1
(%i2) declare (nounify (sum), linear);
(%o2)                         done
(%i3) 'sum (F(k) + G(k), k, 1, inf);
                     inf          inf
                     ====         ====
                     \            \
(%o3)                 >    G(k) +  >    F(k)
                     /            /
                     ====         ====
                     k = 1        k = 1
Функция: disolate (expr, x_1, ..., x_n)

аналогична isolate (expr, x), за исключением того, что она дает возможность пользователю изолировать более чем одну переменную одновременно. Это может быть полезно, например, если пользователь пытается заменить переменные в многократном интегрировании и эта замена переменных включает две или более переменных интегрирования. Данная функция автоматически загружается из simplification/disol.mac. Демонстрация доступна по demo("disol")$.

Функция: dispform (expr)

Возвращает внешнее представление expr по отношению к его главному оператору. Это может быть полезно в сочетании с part, которая также имеет дело с внешним представлением. Предположим expr есть -A. Тогда внутреннее представление expr есть "*"(-1,A), в то время как внешнее представление есть "-"(A). dispform (expr, all) конвертирует все выражение (не только верхний уровень) в внешний формат. Например, если expr: sin (sqrt (x)), то freeof (sqrt, expr) и freeof (sqrt, dispform (expr)) дают true, в то время как freeof (sqrt, dispform (expr, all)) дает false.

Функция: distrib (expr)

Распространяет суммы над произведениями. Она отличается от expand тем, что она работает только на самом верхнем уровне выражения, то есть она не рекурсивная и работает быстрее чем expand. Она отличается от multthru тем, что раскрывает все суммы на этом уровне.

Примеры:

(%i1) distrib ((a+b) * (c+d));
(%o1)                 b d + a d + b c + a c
(%i2) multthru ((a+b) * (c+d));
(%o2)                 (b + a) d + (b + a) c
(%i3) distrib (1/((a+b) * (c+d)));
                                1
(%o3)                    ---------------
                         (b + a) (d + c)
(%i4) expand (1/((a+b) * (c+d)), 1, 0);
                                1
(%o4)                 ---------------------
                      b d + a d + b c + a c
Функция: dpart (expr, n_1, ..., n_k)

Выбирает тоже подвыражение что и part, но вместо только возвращения этого подвыражения как значения, она возвращает все выражение с выбранным подвыражением, изображенным внутри бокса. Данный бокс в действительности является частью выражения.

(%i1) dpart (x+y/z^2, 1, 2, 1);
                             y
(%o1)                       ---- + x
                               2
                            """
                            "z"
                            """
Функция: exp (x)

Представляет собой экспоненциальную функцию. Все экземпляры exp (x) при вводе упрощаются до %e^x. exp не присутствует в упрощенных выражениях.

Если demoivre равно true, то %e^(a + b %i) упрощается до %e^(a (cos(b) + %i sin(b))), если b свободна от %i. См. demoivre.

Если %emode, равно true, то %e^(%pi %i x) упрощается. См. %emode.

Если %enumer, равно true, то %e заменяется на 2.718..., когда numer есть true. См. %enumer.

Управляющая переменная: %emode

Значение по умолчанию: true

Когда %emode есть true, то %e^(%pi %i x) упрощается следующим образом.

%e^(%pi %i x) упрощается до cos (%pi x) + %i sin (%pi x), если x есть число с плавающей точкой, целое или произведение 1/2, 1/3, 1/4 или 1/6 и тогда в дальнейшем упрощается.

Для других численных x, %e^(%pi %i x) упрощается до %e^(%pi %i y), где y есть x - 2 k для некоторых целых k, таких что abs(y) < 1.

Когда %emode есть false, специальное упрощение %e^(%pi %i x) не выполняется.

Управляющая переменная: %enumer

Значение по умолчанию: false

Когда %enumer есть true, то %e заменяется своим численным значением 2.718..., когда numer есть true.

Когда %enumer есть false, эта подстановка выполняется только если экспонента в %e^x вычисляется до численного значения.

См. также ev и numer.

Управляющая переменная: exptisolate

Значение по умолчанию: false

Если exptisolate равно true, то isolate (expr, var) исследует показатели атомов (таких как %e), которые содержат var.

Управляющая переменная: exptsubst

Значение по умолчанию: false

Если exptsubst равно true, то позволяется выполнять подстановки, такие как y для %e^x в %e^(a x).

Функция: freeof (x_1, ..., x_n, expr)

freeof (x_1, expr) Возвращает true, если никакое подвыражение expr не равно x_1 или если x_1 возникает только как немая переменная в expr, иначе возвращает false.

freeof (x_1, ..., x_n, expr) эквивалентно freeof (x_1, expr) and ... and freeof (x_n, expr).

Аргументы x_1, ..., x_n могут быть именами функций или переменных, именами с индексами, операторами (заключенными в двойные кавычки) или выражениями общего вида. freeof вычисляет свои аргументы.

freeof действует только на expr в том виде, в как оно есть, (после упрощения и вычисления) и не пытается определить, может ли некоторое эквивалентное выражение дать другой результат. В частности, упрощение может давать эквивалентное, но другое выражение, которое содержит некоторые различные элементы чем исходная форма expr.

Переменная является немой переменной в некотором выражении, если она не имеет значения за пределами выражения. Немые переменные, распознаваемые freeof, есть индекс суммы или произведения, переменная предела в limit, переменная интегрирования в определенном интеграле integrate, исходная переменная в laplace, формальные переменные в выражениях at и аргументы в lambda выражениях. Локальные переменные в block не распознаются freeof как немые переменные. Это ошибка.

Неопределенное интегрирование integrate не свободно от переменной интегрирования.

Функция: genfact (x, y, z)

Возвращает обобщенный факториал, заданный как x (x-z) (x - 2 z) ... (x - (y - 1) z). Таким образом, для целого x, genfact (x, x, 1) = x! и genfact (x, x/2, 2) = x!!.

Функция: imagpart (expr)

Возвращает мнимую часть выражения expr.

imagpart есть вычислительная функция, а не функция упрощения.

См. также abs, carg, polarform, rectform и realpart.

Функция: infix (op)
Функция: infix (op, lbp, rbp)
Функция: infix (op, lbp, rbp, lpos, rpos, pos)

Объявляет op инфиксным оператором. Инфиксный оператор есть функция двух аргументов, с именем функции, записанным между этими аргументами. Например, оператор вычитания - есть инфиксный оператор.

infix (op) объявляет op инфиксным оператором со степенями связывания по умолчанию (левая и правая, обе равны 180) и частями речи по умолчанию (левая и правая, обе равны any).

infix (op, lbp, rbp) объявляет op инфиксным оператором с указанными левой и правой степени связывания и частями речи по умолчанию (левая и правая, обе равны any).

infix (op, lbp, rbp, lpos, rpos, pos) объявляет op инфиксным оператором с указанными левой и правой степенями связывания и частями речи lpos, rpos и pos для левого операнда, правого операнда и результата соответственно.

Термин "часть речи" по отношению к объявлению операторов, означает тип выражения. Различается три типа: expr, clause и any, которые означают алгебраическое выражение, логическое выражение и выражение произвольного типа соответственно. Maxima может обнаружить некоторые синтаксические ошибки, сравнивая объявленные для оператора части речи с актуальными выражениями.

Приоритет op по отношению к другим операторам выводится из левой и правой степеней связывания рассматриваемых операторов. Если левые и правые степени связывания op обе больше левых и правых степеней связывания другого оператора, то op имеет более высокий приоритет чем этот оператор. Если степени связывания обе не больше или меньше, то имеют место некоторые более сложные соотношения.

Ассоциативность op зависит от его степени связывания. Большая левая степень связывания (lbp) означает, что op вычисляется до других операторов, стоящих слева от него в выражении, в то время как большая правая степень связывания (rbp) означает, что op вычисляется до других операторов, стоящих справа от него в выражении. Таким образом, большее lbp делает op право-ассоциативным, в то время как большее rbp делает op лево-ассоциативным. Если lbp равно rbp, то op является лево-ассоциативный.

См. также Syntax.

Примеры:

(%i1) "@"(a, b) := sconcat("(", a, ",", b, ")")$
(%i2) :lisp (get '$+ 'lbp)
100
(%i2) :lisp (get '$+ 'rbp)
100
(%i2) infix ("@", 101, 101)$
(%i3) 1 + a@b + 2;
(%o3)                       (a,b) + 3
(%i4) infix ("@", 99, 99)$
(%i5) 1 + a@b + 2;
(%o5)                       (a+1,b+2)
(%i1) "@"(a, b) := sconcat("(", a, ",", b, ")")$
(%i2) infix ("@", 100, 99)$
(%i3) foo @ bar @ baz;
(%o3)                    (foo,(bar,baz))
(%i4) infix ("@", 100, 101)$
(%i5) foo @ bar @ baz;
(%o5)                    ((foo,bar),baz)

Maxima может обнаружить некоторые синтаксические ошибки, сравнивая объявленные для оператора части речи с актуальными выражениями.

(%i1) infix ("##", 100, 99, expr, expr, expr);
(%o1)                          ##
(%i2) if x ## y then 1 else 0;
Incorrect syntax: Found algebraic expression where logical expression expected
if x ## y then 
             ^
(%i2) infix ("##", 100, 99, expr, expr, clause);
(%o2)                          ##
(%i3) if x ## y then 1 else 0;
(%o3)                if x ## y then 1 else 0
Управляющая переменная: inflag

Значение по умолчанию: false

Когда inflag есть true, функции для извлечения частей выражения работает с внутренней формой expr.

Заметим, что упрощатель переупорядочивает выражения. Таким образом, first (x + y) возвращает x если inflag есть true, и y, если inflag есть false (first (y + x) дает те же результаты.)

Также, установка inflag равным true и вызов part или substpart есть тоже самое, что вызов inpart или substinpart.

Функции, на которые влияет значение inflag: part, substpart, first, rest, last, length, конструкция for ... in, map, fullmap, maplist, reveal и pickapart.

Функция: inpart (expr, n_1, ..., n_k)

аналогична part, но работает с внутренним представлением выражения, а не с выводимой формой, и, таким образом, может быть быстрее, так как форматирование не выполняется. Нужно быть осторожным по отношению к порядку подвыражений в суммах и произведениях (так как этот порядок переменных в внутренней форме часто отличается от порядка в выводимой форме) и в работе с унарным минусом, вычитанием и делением (так как эти операторы удаляются из выражения). part (x+y, 0) или inpart (x+y, 0) дает +, хотя для ссылки на оператор он должен быть заключен в двойные кавычки. Например ... if inpart (%o9,0) = "+" then ....

Примеры:

(%i1) x + y + w*z;
(%o1)                      w z + y + x
(%i2) inpart (%, 3, 2);
(%o2)                           z
(%i3) part (%th (2), 1, 2);
(%o3)                           z
(%i4) 'limit (f(x)^g(x+1), x, 0, minus);
                                  g(x + 1)
(%o4)                 limit   f(x)
                      x -> 0-
(%i5) inpart (%, 1, 2);
(%o5)                       g(x + 1)
Функция: isolate (expr, x)

Возвращает expr с подвыражениями, которые есть суммы, и которые не содержат переменную var, замененные метками промежуточных выражений (атомарными символами, такими как %t1, %t2, ...). Это часто бывает полезно, чтобы избежать ненужного раскрытия подвыражений, которые не содержат интересующих переменных. Так как данные метки промежуточных выражений имеют подвыражения в качестве своих значений, то они могут быть подставлены обратно вычислением этого выражения.

Если exptisolate (значение по умолчанию: false) равно true, то isolate исследует показатели атомов (таких как %e), которые содержат переменную var.

Если isolate_wrt_times равно true, то isolate изолирует также по отношению к произведениям. См. isolate_wrt_times.

Выполните example (isolate) для других примеров.

Управляющая переменная: isolate_wrt_times

Значение по умолчанию: false

Когда isolate_wrt_times равно true, то isolate также изолирует по отношению к произведениям. Например, сравнивает обе установки

(%i1) isolate_wrt_times: true$
(%i2) isolate (expand ((a+b+c)^2), c);

(%t2)                          2 a


(%t3)                          2 b


                          2            2
(%t4)                    b  + 2 a b + a

                     2
(%o4)               c  + %t3 c + %t2 c + %t4
(%i4) isolate_wrt_times: false$
(%i5) isolate (expand ((a+b+c)^2), c);
                     2
(%o5)               c  + 2 b c + 2 a c + %t4
Управляющая переменная: listconstvars

Значение по умолчанию: false

Когда listconstvars есть true, то в список, возвращаемый listofvars, включаются %e, %pi, %i и другие переменные, объявленные константами. По умолчанию они опускаются.

Управляющая переменная: listdummyvars

Значение по умолчанию: true

Когда listdummyvars есть false, "немые переменные" в выражении не будут включаться в список, возвращаемый listofvars. (Смысл "немых переменных" тот же, что и в freeof. "Немые переменные" – это математические объекты, такие как индекс суммы или произведения, переменная предела и переменная интегрирования в определенном интеграле).

Пример:

(%i1) listdummyvars: true$
(%i2) listofvars ('sum(f(i), i, 0, n));
(%o2)                        [i, n]
(%i3) listdummyvars: false$
(%i4) listofvars ('sum(f(i), i, 0, n));
(%o4)                          [n]
Функция: listofvars (expr)

Возвращает список переменных в expr.

Когда listconstvars есть true, то в список, возвращаемый listofvars, включаются %e, %pi, %i и другие переменные, объявленные константами. По умолчанию они опускаются.

(%i1) listofvars (f (x[1]+y) / g^(2+a));
(%o1)                     [g, a, x , y]
                                  1
Функция: lfreeof (list, expr)

Для каждого члена m списка list, вызывает freeof (m, expr). Возвращает false, если какой либо из вызовов freeof дает false, иначе возвращает true.

Функция: lopow (expr, x)

Возвращает наименьший показатель степени x, который явно присутствует в expr. Таким образом,

(%i1) lopow ((x+y)^2 + (x+y)^a, x+y);
(%o1)                       min(a, 2)
Функция: lpart (label, expr, n_1, ..., n_k)

Аналогично dpart, но использует помеченный бокс. Помеченный бокс аналогичен боксу сделанному с помощью dpart, но имеет имя в верхней строке.

Функция: multthru (expr)
Функция: multthru (expr_1, expr_2)

Умножает множитель expr (который должен быть суммой) на другие множители expr. То есть, expr есть f_1 f_2 ... f_n, где по крайней мере один множитель, скажем f_i, есть сумма членов. Каждый член в той сумме умножается на остальные множители в этом произведении. (А именно на все множители, за исключением f_i). multthru не раскрывает суммы, возведенные в степень. Эта функция есть самый быстрый способ распространять произведения (коммутативные или некоммутативные) на суммы. Так как дроби представляются как произведения, то multthru может также использоваться для деления сумм на произведения.

multthru (expr_1, expr_2) умножает каждый член в expr_2 (который должен быть суммой или уравнением) на expr_1. Если expr_1 сам по себе не является суммой, то эта форма эквивалентна multthru (expr_1*expr_2).

(%i1) x/(x-y)^2 - 1/(x-y) - f(x)/(x-y)^3;
                      1        x         f(x)
(%o1)             - ----- + -------- - --------
                    x - y          2          3
                            (x - y)    (x - y)
(%i2) multthru ((x-y)^3, %);
                           2
(%o2)             - (x - y)  + x (x - y) - f(x)
(%i3) ratexpand (%);
                           2
(%o3)                   - y  + x y - f(x)
(%i4) ((a+b)^10*s^2 + 2*a*b*s + (a*b)^2)/(a*b*s^2);
                        10  2              2  2
                 (b + a)   s  + 2 a b s + a  b
(%o4)            ------------------------------
                                  2
                             a b s
(%i5) multthru (%);  /* note that this does not expand (b+a)^10 */
                                        10
                       2   a b   (b + a)
(%o5)                  - + --- + ---------
                       s    2       a b
                           s
(%i6) multthru (a.(b+c.(d+e)+f));
(%o6)            a . f + a . c . (e + d) + a . b
(%i7) expand (a.(b+c.(d+e)+f));
(%o7)         a . f + a . c . e + a . c . d + a . b
Функция: nounify (f)

Возвращает невычисляемую форму функции с именем f. Это необходимо, если требуется представить имя вычисляемой функции так, если бы она была невычисляемой. Заметим, что некоторые вычисляемые функции возвращают их невычисляемые формы, если они не могут быть вычислены для определенных значений аргументов. Невычисляемая форма возвращается также в случае, если перед функцией стоит кавычка.

Функция: nterms (expr)

Возвращает число членов, которое выражение expr имело бы, если оно было бы полностью раскрыто и не возникло бы сокращений или комбинаций членов. Заметим, что выражения такие как sin (expr), sqrt (expr), exp (expr) и др. считаются только как один член, вне независимости от того, как много членов expr имеет (если оно сумма).

Функция: op (expr)

Возвращает главный оператор выражения expr. op (expr) эквивалентно part (expr, 0).

op возвращает строку, если главный оператор встроенный или определенный пользователем префиксный, бинарный или n-арный инфиксный, постфиксный, матчфиксный или безфиксный оператор. Иначе op возвращает символ.

op следит за значением глобального флага inflag.

op вычисляет свой аргумент.

См. также args.

Примеры:

(%i1) stringdisp: true$
(%i2) op (a * b * c);
(%o2)                          "*"
(%i3) op (a * b + c);
(%o3)                          "+"
(%i4) op ('sin (a + b));
(%o4)                          sin
(%i5) op (a!);
(%o5)                          "!"
(%i6) op (-a);
(%o6)                          "-"
(%i7) op ([a, b, c]);
(%o7)                          "["
(%i8) op ('(if a > b then c else d));
(%o8)                         "if"
(%i9) op ('foo (a));
(%o9)                          foo
(%i10) prefix (foo);
(%o10)                        "foo"
(%i11) op (foo a);
(%o11)                        "foo"
Функция: operatorp (expr, op)
Функция: operatorp (expr, [op_1, ..., op_n])

operatorp (expr, op) возвращает true, если op равен оператору expr.

operatorp (expr, [op_1, ..., op_n]) возвращает true, если какой-нибудь элемент op_1, ..., op_n равен оператору expr.

Функция: optimize (expr)

Возвращает выражение, которое выдает тоже самое значение и побочные эффекты, как и expr, но выполняется более эффективно за счет устранения лишних повторных вычислений общих подвыражений. optimize также имеет побочный эффект "сворачивания" своего аргумента так что все общие подвыражения используются совместно. Выполните example (optimize) для примеров.

Управляющая переменная: optimprefix

Значение по умолчанию: %

optimprefix это префикс, используемый для генерации символов командой optimize.

Функция: ordergreat (v_1, ..., v_n)

Устанавливает синонимы для переменных v_1, ..., v_n, такие, что v_1 > v_2 > ... > v_n, и v_n > любой другой переменной, не включенной в аргументы.

См. также orderless.

Функция: ordergreatp (expr_1, expr_2)

Возвращает true, если expr_2 предшествует expr_1 в упорядочивании, установленном с помощью функции ordergreat.

Функция: orderless (v_1, ..., v_n)

Устанавливает синонимы для переменных v_1, ..., v_n, такие, что v_1 < v_2 < ... < v_n, и v_n < любой другой переменная, не включенной в аргументы.

Таким образом, полная шкала упорядочивания такова: численные константы < объявленные константы < объявленные скаляры < первый аргумент orderless < ... < последний аргумент orderless < переменные, которые начинаются с A < ... < переменные, которые начинаются с Z < последний аргумент ordergreat < ... < первый аргумент ordergreat < объявленные главные переменные mainvar.

См. также ordergreat и mainvar.

Функция: orderlessp (expr_1, expr_2)

Возвращает true, если expr_1 предшествует expr_2 в упорядочивании, установленном командой orderless.

Функция: part (expr, n_1, ..., n_k)

Возвращает части внешней формы expr. Функция получает часть expr, которая определена индексами n_1, ..., n_k. Когда первая часть n_1 expr взята, берется часть n_2 от нее и т.д. Результат есть часть n_k от ... части n_2, от части n_1 выражения expr.

part может быть использована для того, чтобы получить элемент списка, строку матрицы и т.п.

Если последний аргумент функции part есть список индексов, то выбираются несколько подвыражений, каждое из которых соответствует индексу в списке. Таким образом, part (x + y + z, [1, 3]) есть z+x.

piece запоминает последнее выражение, выбранное при использовании функции part. Оно доступно во время выполнения этой функция и, таким образом, может быть использовано в самой функции, как показано ниже.

Если partswitch установлен равным true, то end возвращается когда выбранная часть выражения не существует, иначе выдается сообщение об ошибке.

Пример: part (z+2*y, 2, 1) дает 2.

example (part) показывает дополнительные примеры.

Функция: partition (expr, x)

Возвращает список из двух выражений. Они есть (1) множители expr (если оно произведение), члены expr (если оно является суммой), или список (если оно является списком), которые не содержит x и, (2) те множители, члены или список, которые содержат.

(%i1) partition (2*a*x*f(x), x);
(%o1)                     [2 a, x f(x)]
(%i2) partition (a+b, x);
(%o2)                      [b + a, 0]
(%i3) partition ([a, b, f(a), c], a); 
(%o3)                  [[b, c], [a, f(a)]]
Управляющая переменная: partswitch

Значение по умолчанию: false

Когда partswitch есть true, то end возвращается, если выбранная часть выражения не существует, иначе выдается сообщение об ошибке.

Функция: pickapart (expr, n)

Присваивает меткам промежуточных выражений все подвыражения expr глубины n (целое число). Подвыражения большей или меньшей глубин меткам не присваиваются. pickapart возвращает выражение в терминах промежуточных выражений эквивалентное исходному expr.

См. также part, dpart, lpart, inpart и reveal.

Примеры:

(%i1) expr: (a+b)/2 + sin (x^2)/3 - log (1 + sqrt(x+1));
                                          2
                                     sin(x )   b + a
(%o1)       - log(sqrt(x + 1) + 1) + ------- + -----
                                        3        2
(%i2) pickapart (expr, 0);

                                          2
                                     sin(x )   b + a
(%t2)       - log(sqrt(x + 1) + 1) + ------- + -----
                                        3        2

(%o2)                          %t2
(%i3) pickapart (expr, 1);

(%t3)                - log(sqrt(x + 1) + 1)


                                  2
                             sin(x )
(%t4)                        -------
                                3


                              b + a
(%t5)                         -----
                                2

(%o5)                    %t5 + %t4 + %t3
(%i5) pickapart (expr, 2);

(%t6)                 log(sqrt(x + 1) + 1)


                                  2
(%t7)                        sin(x )


(%t8)                         b + a

                         %t8   %t7
(%o8)                    --- + --- - %t6
                          2     3
(%i8) pickapart (expr, 3);

(%t9)                    sqrt(x + 1) + 1


                                2
(%t10)                         x

                  b + a              sin(%t10)
(%o10)            ----- - log(%t9) + ---------
                    2                    3
(%i10) pickapart (expr, 4);

(%t11)                     sqrt(x + 1)

                      2
                 sin(x )   b + a
(%o11)           ------- + ----- - log(%t11 + 1)
                    3        2
(%i11) pickapart (expr, 5);

(%t12)                        x + 1

                   2
              sin(x )   b + a
(%o12)        ------- + ----- - log(sqrt(%t12) + 1)
                 3        2
(%i12) pickapart (expr, 6);
                  2
             sin(x )   b + a
(%o12)       ------- + ----- - log(sqrt(x + 1) + 1)
                3        2
Системная переменная: piece

Содержит последнее выражение, выбранное при использовании функции part. Оно доступно во время выполнения функции и, таким образом, может быть в ней использовано.

Функция: polarform (expr)

Возвращает выражение r %e^(%i theta) эквивалентное expr, такое, что r и theta чисто вещественные.

Функция: powers (expr, x)

Выдает степени x, встречающиеся в expr.

load ("powers") загружает эту функцию.

Функция: product (expr, i, i_0, i_1)

Представляет произведение значений expr с индексом i, меняющимся от i_0 до i_1. Невычисляемая форма 'product изображается как заглавная буква пи.

product вычисляет expr и нижний и верхний пределы i_0 и i_1, product не вычисляет индекс i.

Если верхний и нижний пределы различаются на целое число, expr вычисляется для каждого значения индекса i, и результат есть точное произведение.

Иначе, диапазон индекса является неопределенным. Для упрощения произведения применяются некоторые правила. Когда глобальная переменная simpproduct есть true, применяются дополнительные правила. В некоторых случаях, упрощение дает результат, который не является произведением, иначе, результат есть невычисляемая форма 'product.

См. также nouns и evflag.

Примеры:

(%i1) product (x + i*(i+1)/2, i, 1, 4);
(%o1)           (x + 1) (x + 3) (x + 6) (x + 10)
(%i2) product (i^2, i, 1, 7);
(%o2)                       25401600
(%i3) product (a[i], i, 1, 7);
(%o3)                 a  a  a  a  a  a  a
                       1  2  3  4  5  6  7
(%i4) product (a(i), i, 1, 7);
(%o4)          a(1) a(2) a(3) a(4) a(5) a(6) a(7)
(%i5) product (a(i), i, 1, n);
                             n
                           /===\
                            ! !
(%o5)                       ! !  a(i)
                            ! !
                           i = 1
(%i6) product (k, k, 1, n);
                               n
                             /===\
                              ! !
(%o6)                         ! !  k
                              ! !
                             k = 1
(%i7) product (k, k, 1, n), simpproduct;
(%o7)                          n!
(%i8) product (integrate (x^k, x, 0, 1), k, 1, n);
                             n
                           /===\
                            ! !    1
(%o8)                       ! !  -----
                            ! !  k + 1
                           k = 1
(%i9) product (if k <= 5 then a^k else b^k, k, 1, 10);
                              15  40
(%o9)                        a   b
Функция: realpart (expr)

Возвращает вещественную часть expr. realpart и imagpart будут работать для выражений, включающих тригонометрические и гипергеометрические функции, также как и квадратный корень, логарифм и возведение в степень.

Функция: rectform (expr)

Возвращает выражение a + b %i, эквивалентное expr, такое, что a и b чисто вещественные.

Функция: rembox (expr, unlabelled)
Функция: rembox (expr, label)
Функция: rembox (expr)

Удаляет боксы из expr.

rembox (expr, unlabelled) удаляет все непомеченные боксы из expr.

rembox (expr, label) удаляет только боксы, содержащие label.

rembox (expr) удаляет все боксы, помеченные и непомеченные.

Боксы рисуются функциями box, dpart и lpart.

Примеры:

(%i1) expr: (a*d - b*c)/h^2 + sin(%pi*x);
                                  a d - b c
(%o1)                sin(%pi x) + ---------
                                      2
                                     h
(%i2) dpart (dpart (expr, 1, 1), 2, 2);
                        """""""    a d - b c
(%o2)               sin("%pi x") + ---------
                        """""""      """"
                                     " 2"
                                     "h "
                                     """"
(%i3) expr2: lpart (BAR, lpart (FOO, %, 1), 2);
                  FOO"""""""""""   BAR""""""""
                  "    """"""" "   "a d - b c"
(%o3)             "sin("%pi x")" + "---------"
                  "    """"""" "   "  """"   "
                  """"""""""""""   "  " 2"   "
                                   "  "h "   "
                                   "  """"   "
                                   """""""""""
(%i4) rembox (expr2, unlabelled);
                                  BAR""""""""
                   FOO"""""""""   "a d - b c"
(%o4)              "sin(%pi x)" + "---------"
                   """"""""""""   "    2    "
                                  "   h     "
                                  """""""""""
(%i5) rembox (expr2, FOO);
                                  BAR""""""""
                       """""""    "a d - b c"
(%o5)              sin("%pi x") + "---------"
                       """""""    "  """"   "
                                  "  " 2"   "
                                  "  "h "   "
                                  "  """"   "
                                  """""""""""
(%i6) rembox (expr2, BAR);
                   FOO"""""""""""
                   "    """"""" "   a d - b c
(%o6)              "sin("%pi x")" + ---------
                   "    """"""" "     """"
                   """"""""""""""     " 2"
                                      "h "
                                      """"
(%i7) rembox (expr2);
                                  a d - b c
(%o7)                sin(%pi x) + ---------
                                      2
                                     h
Функция: sum (expr, i, i_0, i_1)

Представляет собой суммирование значений expr для индекса i, изменяющегося от i_0 до i_1. Невычисляемая форма 'sum изображается как заглавная буква сигма.

sum вычисляет свое слагаемое expr и нижний и верхний пределы i_0 и i_1, sum не вычисляет индекс i.

Если верхний и нижний пределы отличаются на целое число, слагаемое expr вычисляется для каждого значения индекса суммирования i, и результат есть точная сумма.

Иначе, диапазон индекса является неопределенным. Для упрощения суммирования применяются некоторые правила. Когда глобальная переменная simpsum есть true, дополнительные правила применяются. В некоторых случаях, упрощение дает результат, который не есть суммирование, иначе, результат есть невычисляемая форма 'sum.

Когда evflag (флаг вычисления) cauchysum есть true, произведение суммирования выражается как произведение Коши, в котром индекс внутреннего суммирования есть функция индекса внешнего суммирования, а не меняющейся независимо индекс.

Глобальная переменная genindex есть буквенный префикс, используемый для генерации следующего индекса суммирования, если требуется автоматически сгенерированный индекс.

gensumnum есть численный суффикс, используемый для генерирования следующего используемый для генерации следующего индекса суммирования, если требуется автоматически сгенерированный индекс. Когда gensumnum есть false, автоматически сгенерированный индекс есть только genindex без численного суффикса.

См. также sumcontract, intosum, bashindices, niceindices, nouns, evflag и zeilberger.

Примеры:

(%i1) sum (i^2, i, 1, 7);
(%o1)                          140
(%i2) sum (a[i], i, 1, 7);
(%o2)           a  + a  + a  + a  + a  + a  + a
                 7    6    5    4    3    2    1
(%i3) sum (a(i), i, 1, 7);
(%o3)    a(7) + a(6) + a(5) + a(4) + a(3) + a(2) + a(1)
(%i4) sum (a(i), i, 1, n);
                            n
                           ====
                           \
(%o4)                       >    a(i)
                           /
                           ====
                           i = 1
(%i5) sum (2^i + i^2, i, 0, n);
                          n
                         ====
                         \       i    2
(%o5)                     >    (2  + i )
                         /
                         ====
                         i = 0
(%i6) sum (2^i + i^2, i, 0, n), simpsum;
                              3      2
                   n + 1   2 n  + 3 n  + n
(%o6)             2      + --------------- - 1
                                  6
(%i7) sum (1/3^i, i, 1, inf);
                            inf
                            ====
                            \     1
(%o7)                        >    --
                            /      i
                            ====  3
                            i = 1
(%i8) sum (1/3^i, i, 1, inf), simpsum;
                                1
(%o8)                           -
                                2
(%i9) sum (i^2, i, 1, 4) * sum (1/i^2, i, 1, inf);
                              inf
                              ====
                              \     1
(%o9)                      30  >    --
                              /      2
                              ====  i
                              i = 1
(%i10) sum (i^2, i, 1, 4) * sum (1/i^2, i, 1, inf), simpsum;
                                  2
(%o10)                       5 %pi
(%i11) sum (integrate (x^k, x, 0, 1), k, 1, n);
                            n
                           ====
                           \       1
(%o11)                      >    -----
                           /     k + 1
                           ====
                           k = 1
(%i12) sum (if k <= 5 then a^k else b^k, k, 1, 10);
          10    9    8    7    6    5    4    3    2
(%o12)   b   + b  + b  + b  + b  + a  + a  + a  + a  + a
Функция: lsum (expr, x, L)

Представляет собой сумму expr для каждого элемента x в L.

Невычисляемая форма 'lsum возвращается, если аргумент L не вычисляется до списка.

Примеры:

(%i1) lsum (x^i, i, [1, 2, 7]);
                            7    2
(%o1)                      x  + x  + x
(%i2) lsum (i^2, i, rootsof (x^3 - 1, x));
                     ====
                     \      2
(%o2)                 >    i
                     /
                     ====
                                   3
                     i in rootsof(x  - 1, x)
Функция: verbify (f)

Возвращает вычисляемую форму функции с именем f.

См. также verb, noun и nounify.

Примеры:

(%i1) verbify ('foo);
(%o1)                          foo
(%i2) :lisp $%
$FOO
(%i2) nounify (foo);
(%o2)                          foo
(%i3) :lisp $%
%FOO

Next: , Previous: Выражения, Up: Top   [Contents][Index]

7 Simplification


Next: , Up: Simplification   [Contents][Index]

7.1 Introduction to Simplification

Maxima interacts with the user through a cycle of actions called the read-eval-print loop (REPL). This consists of three steps: reading and parsing, evaluating and simplifying, and outputting. Parsing converts a syntactically valid sequence of typed characters into a internal data structure. Evaluation replaces variable and function names with their values and simplification rewrites expressions to be easier for the user or other programs to understand. Output displays results in a variety of different formats and notations.

Evaluation and simplification sometimes appear to have similar functionality, and Maxima uses simplification in many cases where other systems use evaluation. For example, arithmetic both on numbers and on symbolic expressions is simplification, not evaluation: 2+2 simplifies to 4, 2+x+x simplifies to 2+2*x, and sqrt(7)^4 simplifies to 49. Evaluation and simplification are interleaved. For example, factor(integrate(x+1,x)) first calls the built-in function integrate, giving x+x*x*2^-1; that simplifies to x+(1/2)*x^2; this in turn is passed to the factor function, which returns (x*(x+2))/2.

Evaluation is what makes Maxima a programming language: it implements functions, subroutines, variables, values, loops, assignments and so on. Evaluation replaces built-in or user-defined function names by their definitions and variables by their values. This is largely the same as activities of a conventional programming language, but extended to work with symbolic mathematical data. The system has various optional "flags" which the user can set to control the details of evaluation. See Functions and Variables for Evaluation.

Simplification maintains the value of an expression while re-formulating its form to be smaller, simpler to understand, or to conform to a particular specification (like expanded). For example, sin(%pi/2) to 1, and x+x to 2*x. There are many flags which control simplification. For example, with triginverses:true, atan(tan(x)) does not simplify to x, but with triginverses:all, it does.

Simplification can be provided in three ways:

The internal simplifier belongs to the heart of Maxima. It is a large and complicated collection of programs, and it has been refined over many years and by thousands of users. Nevertheless, especially if you are trying out novel ideas or unconventional notation, you may find it helpful to make small (or large) changes to the program yourself. For details see for example the paper at the end of https://people.eecs.berkeley.edu/~fateman/papers/intro5.txt.

Maxima internally represents expressions as "trees" with operators or "roots" like +, * , = and operands ("leaves") which are variables like x, y, z, functions or sub-trees, like x*y. Each operator has a simplification program associated with it. + (which also covers binary - since a-b = a+(-1)*b) and * (which also covers / since a/b = a*b^(-1)) have rather elaborate simplification programs. These simplification programs (simplus, simptimes, simpexpt, etc.) are called whenever the simplifier encounters the respective arithmetic operators in an expression tree to be analyzed.

The structure of the simplifier dates back to 1965, and many hands have worked on it through the years. It is data-directed, or object-oriented in the sense that it dispatches to the appropriate routine depending on the root of some sub-tree of the expression, recursively. This general approach means that modifications to simplification are generally localized. In many cases it is straightforward to add an operator and its simplification routine without disturbing existing code.

Maxima also provides a variety of transformation routines that can change the form of an expression, including factor (polynomial factorization), horner (reorganize a polynomial using Horner’s rule), partfrac (rewrite a rational function as partial fractions), trigexpand (apply the sum formulas for trigonometric functions), and so on.

Users can also write routines that change the form of an expression.

Besides this general simplifier operating on algebraic expression trees, there are several other representations of expressions in Maxima which have separate methods. For example, the rat function converts polynomials to vectors of coefficients to assist in rapid manipulation of such forms. Other representations include Taylor series and the (rarely used) Poisson series.

All operators introduced by the user initially have no simplification programs associated with them. Maxima does not know anything about function "f" and so typing f(a,b) will result in simplifying a,b, but not f. Even some built-in operators have no simplifications. For example, = does not "simplify" – it is a place-holder with no simplification semantics other than to simplify its two arguments, in this case referred to as the left and right sides. Other parts of Maxima such as the solve program take special note of equations, that is, trees with = as the root. (Note – in Maxima, the assignment operation is : . That is, q: 4 sets the value of the symbol q to 4. Function definition is done with :=. )

The general simplifier returns results with an internal flag indicating the expression and each sub-expression has been simplified. This does not guarantee that it is unique over all possible equivalent expressions. That’s too hard (theoretically, not possible given the generality of what can be expressed in Maxima). However, some aspects of the expression, such as the ordering of terms in a sum or product, are made uniform. This is important for the other programs to work properly.

A number of option variables control simplification. Indeed, simplification can be turned off entirely using simp:false. However, many internal routines will not operate correctly with simp:false. (About the only time it seems plausible to turn off the simplifier is in the rare case that you want to over-ride a built-in simplification. In that case you might temporarily disable the simplifier, put in the new transformation via tellsimp, and then re-enable the simplifier by simp:true.)

It is more plausible for you to associate user-defined symbolic function names or operators with properties (additive, lassociative, oddfun, antisymmetric, linear, outative, commutative, multiplicative, rassociative, evenfun, `nary' and symmetric). These options steer the simplifier processing in systematic directions.

For example, declare(f,oddfun) specifies that f is an odd function. Maxima will simplify f(-x) to -f(x). In the case of an even function, that is declare(g,evenfun), Maxima will simplify g(-x) to g(x). You can also associate a programming function with a name such as h(x):=x^2+1. In that case the evaluator will immediately replace h(3) by 10, and h(a+1) by (a+1)^2+1, so any properties of h will be ignored.

In addition to these directly related properties set up by the user, facts and properties from the actual context may have an impact on the simplifier’s behavior, too. See Introduction to Maxima's Database.

Example: sin(n*%pi) is simplified to zero, if n is an integer.

(%i1) sin(n*%pi);
(%o1)                      sin(%pi n)
(%i2) declare(n, integer);
(%o2)                         done
(%i3) sin(n*%pi);
(%o3)                           0

If automated simplification is not sufficient, you can consider a variety of built-in, but explicitly called simplfication functions (ratsimp, expand, factor, radcan and others). There are also flags that will push simplification into one or another direction. Given demoivre:true the simplifier rewrites complex exponentials as trigonometric forms. Given exponentialize:true the simplifier tries to do the reverse: rewrite trigonometric forms as complex exponentials.

As everywhere in Maxima, by writing your own functions (be it in the Maxima user language or in the implementation language Lisp) and explicitly calling them at selected places in the program, you can respond to your individual simplification needs. Lisp gives you a handle on all the internal mechanisms, but you rarely need this full generality. "Tellsimp" is designed to generate much of the Lisp internal interface into the simplifier automatically. See See Rules and Patterns.

Over the years (Maxima/Macsyma’s origins date back to about 1966!) users have contributed numerous application packages and tools to extend or alter its functional behavior. Various non-standard and "share" packages exist to modify or extend simplification as well. You are invited to look into this more experimental material where work is still in progress See simplification-pkg.

The following appended material is optional on a first reading, and reading it is not necessary for productive use of Maxima. It is for the curious user who wants to understand what is going on, or the ambitious programmer who might wish to change the (open-source) code. Experimentation with redefining Maxima Lisp code is easily possible: to change the definition of a Lisp program (say the one that simplifies cos(), named simp%cos), you simply load into Maxima a text file that will overwrite the simp%cos function from the maxima package.


Previous: Introduction to Simplification, Up: Simplification   [Contents][Index]

7.2 Functions and Variables for Simplification

Property: additive

If declare(f,additive) has been executed, then:

(1) If f is univariate, whenever the simplifier encounters f applied to a sum, f will be distributed over that sum. I.e. f(y+x) will simplify to f(y)+f(x).

(2) If f is a function of 2 or more arguments, additivity is defined as additivity in the first argument to f, as in the case of sum or integrate, i.e. f(h(x)+g(x),x) will simplify to f(h(x),x)+f(g(x),x). This simplification does not occur when f is applied to expressions of the form sum(x[i],i,lower-limit,upper-limit).

Example:

(%i1) F3 (a + b + c);
(%o1)                     F3(c + b + a)
(%i2) declare (F3, additive);
(%o2)                         done
(%i3) F3 (a + b + c);
(%o3)                 F3(c) + F3(b) + F3(a)
Property: antisymmetric

If declare(h,antisymmetric) is done, this tells the simplifier that h is antisymmetric. E.g. h(x,z,y) will simplify to - h(x, y, z). That is, it will give (-1)^n times the result given by symmetric or commutative, where n is the number of interchanges of two arguments necessary to convert it to that form.

Examples:

(%i1) S (b, a);
(%o1)                        S(b, a)
(%i2) declare (S, symmetric);
(%o2)                         done
(%i3) S (b, a);
(%o3)                        S(a, b)
(%i4) S (a, c, e, d, b);
(%o4)                   S(a, b, c, d, e)
(%i5) T (b, a);
(%o5)                        T(b, a)
(%i6) declare (T, antisymmetric);
(%o6)                         done
(%i7) T (b, a);
(%o7)                       - T(a, b)
(%i8) T (a, c, e, d, b);
(%o8)                   T(a, b, c, d, e)
Function: combine (expr)

Simplifies the sum expr by combining terms with the same denominator into a single term.

See also: rncombine.

Example:

(%i1) 1*f/2*b + 2*c/3*a + 3*f/4*b +c/5*b*a;
                      5 b f   a b c   2 a c
(%o1)                 ----- + ----- + -----
                        4       5       3
(%i2) combine (%);
                  75 b f + 4 (3 a b c + 10 a c)
(%o2)             -----------------------------
                               60
Property: commutative

If declare(h, commutative) is done, this tells the simplifier that h is a commutative function. E.g. h(x, z, y) will simplify to h(x, y, z). This is the same as symmetric.

Example:

(%i1) S (b, a);
(%o1)                        S(b, a)
(%i2) S (a, b) + S (b, a);
(%o2)                   S(b, a) + S(a, b)
(%i3) declare (S, commutative);
(%o3)                         done
(%i4) S (b, a);
(%o4)                        S(a, b)
(%i5) S (a, b) + S (b, a);
(%o5)                       2 S(a, b)
(%i6) S (a, c, e, d, b);
(%o6)                   S(a, b, c, d, e)
Function: demoivre (expr)
Option variable: demoivre

The function demoivre (expr) converts one expression without setting the global variable demoivre.

When the variable demoivre is true, complex exponentials are converted into equivalent expressions in terms of circular functions: exp (a + b*%i) simplifies to %e^a * (cos(b) + %i*sin(b)) if b is free of %i. a and b are not expanded.

The default value of demoivre is false.

exponentialize converts circular and hyperbolic functions to exponential form. demoivre and exponentialize cannot both be true at the same time.

Function: distrib (expr)

Distributes sums over products. It differs from expand in that it works at only the top level of an expression, i.e., it doesn’t recurse and it is faster than expand. It differs from multthru in that it expands all sums at that level.

Examples:

(%i1) distrib ((a+b) * (c+d));
(%o1)                 b d + a d + b c + a c
(%i2) multthru ((a+b) * (c+d));
(%o2)                 (b + a) d + (b + a) c
(%i3) distrib (1/((a+b) * (c+d)));
                                1
(%o3)                    ---------------
                         (b + a) (d + c)
(%i4) expand (1/((a+b) * (c+d)), 1, 0);
                                1
(%o4)                 ---------------------
                      b d + a d + b c + a c
Option variable: distribute_over

Default value: true

distribute_over controls the mapping of functions over bags like lists, matrices, and equations. At this time not all Maxima functions have this property. It is possible to look up this property with the command `properties'..

The mapping of functions is switched off, when setting distribute_over to the value false.

Examples:

The sin function maps over a list:

(%i1) sin([x,1,1.0]);
(%o1)         [sin(x), sin(1), 0.8414709848078965]

mod is a function with two arguments which maps over lists. Mapping over nested lists is possible too:

(%i1) mod([x,11,2*a],10);
(%o1)             [mod(x, 10), 1, 2 mod(a, 5)]
(%i2) mod([[x,y,z],11,2*a],10);
(%o2) [[mod(x, 10), mod(y, 10), mod(z, 10)], 1, 2 mod(a, 5)]

Mapping of the floor function over a matrix and an equation:

(%i1) floor(matrix([a,b],[c,d]));
                     [ floor(a)  floor(b) ]
(%o1)                [                    ]
                     [ floor(c)  floor(d) ]
(%i2) floor(a=b);
(%o2)                  floor(a) = floor(b)

Functions with more than one argument map over any of the arguments or all arguments:

(%i1) expintegral_e([1,2],[x,y]);
(%o1) [[expintegral_e(1, x), expintegral_e(1, y)], 
                      [expintegral_e(2, x), expintegral_e(2, y)]]

Check if a function has the property distribute_over:

(%i1) properties(abs);
(%o1) [integral, rule, distributes over bags, noun, gradef, 
                                                 system function]

The mapping of functions is switched off, when setting distribute_over to the value false.

(%i1) distribute_over;
(%o1)                         true
(%i2) sin([x,1,1.0]);
(%o2)         [sin(x), sin(1), 0.8414709848078965]
(%i3) distribute_over : not distribute_over;
(%o3)                         false
(%i4) sin([x,1,1.0]);
(%o4)                   sin([x, 1, 1.0])
Option variable: domain

Default value: real

When domain is set to complex, sqrt (x^2) will remain sqrt (x^2) instead of returning abs(x).

Property: evenfun
Property: oddfun

declare(f, evenfun) or declare(f, oddfun) tells Maxima to recognize the function f as an even or odd function.

Examples:

(%i1) o (- x) + o (x);
(%o1)                     o(x) + o(- x)
(%i2) declare (o, oddfun);
(%o2)                         done
(%i3) o (- x) + o (x);
(%o3)                           0
(%i4) e (- x) - e (x);
(%o4)                     e(- x) - e(x)
(%i5) declare (e, evenfun);
(%o5)                         done
(%i6) e (- x) - e (x);
(%o6)                           0
Function: expand
    expand (expr)
    expand (expr, p, n)

Expand expression expr. Products of sums and exponentiated sums are multiplied out, numerators of rational expressions which are sums are split into their respective terms, and multiplication (commutative and non-commutative) are distributed over addition at all levels of expr.

For polynomials one should usually use ratexpand which uses a more efficient algorithm.

maxnegex and maxposex control the maximum negative and positive exponents, respectively, which will expand.

expand (expr, p, n) expands expr, using p for maxposex and n for maxnegex. This is useful in order to expand part but not all of an expression.

expon - the exponent of the largest negative power which is automatically expanded (independent of calls to expand). For example if expon is 4 then (x+1)^(-5) will not be automatically expanded.

expop - the highest positive exponent which is automatically expanded. Thus (x+1)^3, when typed, will be automatically expanded only if expop is greater than or equal to 3. If it is desired to have (x+1)^n expanded where n is greater than expop then executing expand ((x+1)^n) will work only if maxposex is not less than n.

expand(expr, 0, 0) causes a resimplification of expr. expr is not reevaluated. In distinction from ev(expr, noeval) a special representation (e. g. a CRE form) is removed. See also ev.

The expand flag used with ev causes expansion.

The file share/simplification/facexp.mac contains several related functions (in particular facsum, factorfacsum and collectterms, which are autoloaded) and variables (nextlayerfactor and facsum_combine) that provide the user with the ability to structure expressions by controlled expansion. Brief function descriptions are available in simplification/facexp.usg. A demo is available by doing demo("facexp").

Examples:

(%i1) expr:(x+1)^2*(y+1)^3;
                               2        3
(%o1)                   (x + 1)  (y + 1)
(%i2) expand(expr);
       2  3        3    3      2  2        2      2      2
(%o2) x  y  + 2 x y  + y  + 3 x  y  + 6 x y  + 3 y  + 3 x  y
                                                      2
                                     + 6 x y + 3 y + x  + 2 x + 1
(%i3) expand(expr,2);
               2        3              3          3
(%o3)         x  (y + 1)  + 2 x (y + 1)  + (y + 1)
(%i4) expr:(x+1)^-2*(y+1)^3;
                                   3
                            (y + 1)
(%o4)                       --------
                                   2
                            (x + 1)
(%i5) expand(expr);
            3               2
           y             3 y            3 y             1
(%o5) ------------ + ------------ + ------------ + ------------
       2              2              2              2
      x  + 2 x + 1   x  + 2 x + 1   x  + 2 x + 1   x  + 2 x + 1
(%i6) expand(expr,2,2);
                                   3
                            (y + 1)
(%o6)                     ------------
                           2
                          x  + 2 x + 1

Resimplify an expression without expansion:

(%i1) expr:(1+x)^2*sin(x);
                                2
(%o1)                    (x + 1)  sin(x)
(%i2) exponentialize:true;
(%o2)                         true
(%i3) expand(expr,0,0);
                            2    %i x     - %i x
                  %i (x + 1)  (%e     - %e      )
(%o3)           - -------------------------------
                                 2
Function: expandwrt (expr, x_1, …, x_n)

Expands expression expr with respect to the variables x_1, …, x_n. All products involving the variables appear explicitly. The form returned will be free of products of sums of expressions that are not free of the variables. x_1, …, x_n may be variables, operators, or expressions.

By default, denominators are not expanded, but this can be controlled by means of the switch expandwrt_denom.

This function is autoloaded from simplification/stopex.mac.

Option variable: expandwrt_denom

Default value: false

expandwrt_denom controls the treatment of rational expressions by expandwrt. If true, then both the numerator and denominator of the expression will be expanded according to the arguments of expandwrt, but if expandwrt_denom is false, then only the numerator will be expanded in that way.

Function: expandwrt_factored (expr, x_1, …, x_n)

is similar to expandwrt, but treats expressions that are products somewhat differently. expandwrt_factored expands only on those factors of expr that contain the variables x_1, …, x_n.

This function is autoloaded from simplification/stopex.mac.

Option variable: expon

Default value: 0

expon is the exponent of the largest negative power which is automatically expanded (independent of calls to expand). For example, if expon is 4 then (x+1)^(-5) will not be automatically expanded.

Function: exponentialize (expr)
Option variable: exponentialize

The function exponentialize (expr) converts circular and hyperbolic functions in expr to exponentials, without setting the global variable exponentialize.

When the variable exponentialize is true, all circular and hyperbolic functions are converted to exponential form. The default value is false.

demoivre converts complex exponentials into circular functions. exponentialize and demoivre cannot both be true at the same time.

Option variable: expop

Default value: 0

expop is the highest positive exponent which is automatically expanded. Thus (x + 1)^3, when typed, will be automatically expanded only if expop is greater than or equal to 3. If it is desired to have (x + 1)^n expanded where n is greater than expop then executing expand ((x + 1)^n) will work only if maxposex is not less than n.

Property: lassociative

declare (g, lassociative) tells the Maxima simplifier that g is left-associative. E.g., g (g (a, b), g (c, d)) will simplify to g (g (g (a, b), c), d).

See also rassociative.

Property: linear

One of Maxima’s operator properties. For univariate f so declared, "expansion" f(x + y) yields f(x) + f(y), f(a*x) yields a*f(x) takes place where a is a "constant". For functions of two or more arguments, "linearity" is defined to be as in the case of sum or integrate, i.e., f (a*x + b, x) yields a*f(x,x) + b*f(1,x) for a and b free of x.

Example:

(%i1) declare (f, linear);
(%o1)                         done
(%i2) f(x+y);
(%o2)                      f(y) + f(x)
(%i3) declare (a, constant);
(%o3)                         done
(%i4) f(a*x);
(%o4)                        a f(x)

linear is equivalent to additive and outative. See also opproperties.

Example:

(%i1) 'sum (F(k) + G(k), k, 1, inf);
                       inf
                       ====
                       \
(%o1)                   >    (G(k) + F(k))
                       /
                       ====
                       k = 1
(%i2) declare (nounify (sum), linear);
(%o2)                         done
(%i3) 'sum (F(k) + G(k), k, 1, inf);
                     inf          inf
                     ====         ====
                     \            \
(%o3)                 >    G(k) +  >    F(k)
                     /            /
                     ====         ====
                     k = 1        k = 1
Option variable: maxnegex

Default value: 1000

maxnegex is the largest negative exponent which will be expanded by the expand command, see also maxposex.

Option variable: maxposex

Default value: 1000

maxposex is the largest exponent which will be expanded with the expand command, see also maxnegex.

Property: multiplicative

declare(f, multiplicative) tells the Maxima simplifier that f is multiplicative.

  1. If f is univariate, whenever the simplifier encounters f applied to a product, f distributes over that product. E.g., f(x*y) simplifies to f(x)*f(y). This simplification is not applied to expressions of the form f('product(...)).
  2. If f is a function of 2 or more arguments, multiplicativity is defined as multiplicativity in the first argument to f, e.g., f (g(x) * h(x), x) simplifies to f (g(x) ,x) * f (h(x), x).

declare(nounify(product), multiplicative) tells Maxima to simplify symbolic products.

Example:

(%i1) F2 (a * b * c);
(%o1)                       F2(a b c)
(%i2) declare (F2, multiplicative);
(%o2)                         done
(%i3) F2 (a * b * c);
(%o3)                   F2(a) F2(b) F2(c)

declare(nounify(product), multiplicative) tells Maxima to simplify symbolic products.

(%i1) product (a[i] * b[i], i, 1, n);
                             n
                           /===\
                            ! !
(%o1)                       ! !  a  b
                            ! !   i  i
                           i = 1
(%i2) declare (nounify (product), multiplicative);
(%o2)                         done
(%i3) product (a[i] * b[i], i, 1, n);
                          n         n
                        /===\     /===\
                         ! !       ! !
(%o3)                  ( ! !  a )  ! !  b
                         ! !   i   ! !   i
                        i = 1     i = 1
Function: multthru
    multthru (expr)
    multthru (expr_1, expr_2)

Multiplies a factor (which should be a sum) of expr by the other factors of expr. That is, expr is f_1 f_2 ... f_n where at least one factor, say f_i, is a sum of terms. Each term in that sum is multiplied by the other factors in the product. (Namely all the factors except f_i). multthru does not expand exponentiated sums. This function is the fastest way to distribute products (commutative or noncommutative) over sums. Since quotients are represented as products multthru can be used to divide sums by products as well.

multthru (expr_1, expr_2) multiplies each term in expr_2 (which should be a sum or an equation) by expr_1. If expr_1 is not itself a sum then this form is equivalent to multthru (expr_1*expr_2).

(%i1) x/(x-y)^2 - 1/(x-y) - f(x)/(x-y)^3;
                      1        x         f(x)
(%o1)             - ----- + -------- - --------
                    x - y          2          3
                            (x - y)    (x - y)
(%i2) multthru ((x-y)^3, %);
                           2
(%o2)             - (x - y)  + x (x - y) - f(x)
(%i3) ratexpand (%);
                           2
(%o3)                   - y  + x y - f(x)
(%i4) ((a+b)^10*s^2 + 2*a*b*s + (a*b)^2)/(a*b*s^2);
                        10  2              2  2
                 (b + a)   s  + 2 a b s + a  b
(%o4)            ------------------------------
                                  2
                             a b s
(%i5) multthru (%);  /* note that this does not expand (b+a)^10 */
                                        10
                       2   a b   (b + a)
(%o5)                  - + --- + ---------
                       s    2       a b
                           s
(%i6) multthru (a.(b+c.(d+e)+f));
(%o6)            a . f + a . c . (e + d) + a . b
(%i7) expand (a.(b+c.(d+e)+f));
(%o7)         a . f + a . c . e + a . c . d + a . b
Property: nary

declare(f, nary) tells Maxima to recognize the function f as an n-ary function.

The nary declaration is not the same as calling the `nary' function. The sole effect of declare(f, nary) is to instruct the Maxima simplifier to flatten nested expressions, for example, to simplify foo(x, foo(y, z)) to foo(x, y, z). See also declare.

Example:

(%i1) H (H (a, b), H (c, H (d, e)));
(%o1)               H(H(a, b), H(c, H(d, e)))
(%i2) declare (H, nary);
(%o2)                         done
(%i3) H (H (a, b), H (c, H (d, e)));
(%o3)                   H(a, b, c, d, e)
Option variable: negdistrib

Default value: true

When negdistrib is true, -1 distributes over an expression. E.g., -(x + y) becomes - y - x. Setting it to false will allow - (x + y) to be displayed like that. This is sometimes useful but be very careful: like the simp flag, this is one flag you do not want to set to false as a matter of course or necessarily for other than local use in your Maxima.

Example:

(%i1) negdistrib;
(%o1)                         true
(%i2) -(x+y);
(%o2)                       (- y) - x
(%i3) negdistrib : not negdistrib ;
(%o3)                         false
(%i4) -(x+y);
(%o4)                       - (y + x)
System variable: opproperties

opproperties is the list of the special operator properties recognized by the Maxima simplifier.

Items are added to the opproperties list by the function define_opproperty.

Example:

(%i1) opproperties;
(%o1) [linear, additive, multiplicative, outative, evenfun, 
oddfun, commutative, symmetric, antisymmetric, nary, 
lassociative, rassociative]
Function: define_opproperty (property_name, simplifier_fn)

Declares the symbol property_name to be an operator property, which is simplified by simplifier_fn, which may be the name of a Maxima or Lisp function or a lambda expression. After define_opproperty is called, functions and operators may be declared to have the property_name property, and simplifier_fn is called to simplify them.

simplifier_fn must be a function of one argument, which is an expression in which the main operator is declared to have the property_name property.

simplifier_fn is called with the global flag simp disabled. Therefore simplifier_fn must be able to carry out its simplification without making use of the general simplifier.

define_opproperty appends property_name to the global list opproperties.

define_opproperty returns done.

Example:

Declare a new property, identity, which is simplified by simplify_identity. Declare that f and g have the new property.

(%i1) define_opproperty (identity, simplify_identity);
(%o1)                         done
(%i2) simplify_identity(e) := first(e);
(%o2)           simplify_identity(e) := first(e)
(%i3) declare ([f, g], identity);
(%o3)                         done
(%i4) f(10 + t);
(%o4)                        t + 10
(%i5) g(3*u) - f(2*u);
(%o5)                           u
Property: outative

declare(f, outative) tells the Maxima simplifier that constant factors in the argument of f can be pulled out.

  1. If f is univariate, whenever the simplifier encounters f applied to a product, that product will be partitioned into factors that are constant and factors that are not and the constant factors will be pulled out. E.g., f(a*x) will simplify to a*f(x) where a is a constant. Non-atomic constant factors will not be pulled out.
  2. If f is a function of 2 or more arguments, outativity is defined as in the case of sum or integrate, i.e., f (a*g(x), x) will simplify to a * f(g(x), x) for a free of x.

sum, integrate, and limit are all outative.

Example:

(%i1) F1 (100 * x);
(%o1)                       F1(100 x)
(%i2) declare (F1, outative);
(%o2)                         done
(%i3) F1 (100 * x);
(%o3)                       100 F1(x)
(%i4) declare (zz, constant);
(%o4)                         done
(%i5) F1 (zz * y);
(%o5)                       zz F1(y)
Function: radcan (expr)

Simplifies expr, which can contain logs, exponentials, and radicals, by converting it into a form which is canonical over a large class of expressions and a given ordering of variables; that is, all functionally equivalent forms are mapped into a unique form. For a somewhat larger class of expressions, radcan produces a regular form. Two equivalent expressions in this class do not necessarily have the same appearance, but their difference can be simplified by radcan to zero.

For some expressions radcan is quite time consuming. This is the cost of exploring certain relationships among the components of the expression for simplifications based on factoring and partial-fraction expansions of exponents.

Examples:

(%i1) radcan((log(x+x^2)-log(x))^a/log(1+x)^(a/2));
                                    a/2
(%o1)                     log(x + 1)
(%i2) radcan((log(1+2*a^x+a^(2*x))/log(1+a^x)));
(%o2)                           2
(%i3) radcan((%e^x-1)/(1+%e^(x/2)));
                              x/2
(%o3)                       %e    - 1
Option variable: radexpand

Default value: true

radexpand controls some simplifications of radicals.

When radexpand is all, causes nth roots of factors of a product which are powers of n to be pulled outside of the radical. E.g. if radexpand is all, sqrt (16*x^2) simplifies to 4*x.

More particularly, consider sqrt (x^2).

Note that domain only matters when radexpand is true.

Property: rassociative

declare (g, rassociative) tells the Maxima simplifier that g is right-associative. E.g., g(g(a, b), g(c, d)) simplifies to g(a, g(b, g(c, d))).

See also lassociative.

Function: scsimp (expr, rule_1, …, rule_n)

Sequential Comparative Simplification (method due to Stoute). scsimp attempts to simplify expr according to the rules rule_1, …, rule_n. If a smaller expression is obtained, the process repeats. Otherwise after all simplifications are tried, it returns the original answer.

example (scsimp) displays some examples.

Option variable: simp

Default value: true

simp enables simplification. This is the default. simp is also an evflag, which is recognized by the function ev. See ev.

When simp is used as an evflag with a value false, the simplification is suppressed only during the evaluation phase of an expression. The flag does not suppress the simplification which follows the evaluation phase.

Many Maxima functions and operations require simplification to be enabled to work normally. When simplification is disabled, many results will be incomplete, and in addition there may be incorrect results or program errors.

Examples:

The simplification is switched off globally. The expression sin(1.0) is not simplified to its numerical value. The simp-flag switches the simplification on.

(%i1) simp:false;
(%o1)                         false
(%i2) sin(1.0);
(%o2)                       sin(1.0)
(%i3) sin(1.0),simp;
(%o3)                  0.8414709848078965

The simplification is switched on again. The simp-flag cannot suppress the simplification completely. The output shows a simplified expression, but the variable x has an unsimplified expression as a value, because the assignment has occurred during the evaluation phase of the expression.

(%i1) simp:true;
(%o1)                         true
(%i2) x:sin(1.0),simp:false;
(%o2)                  0.8414709848078965
(%i3) :lisp $x
((%SIN) 1.0)
Property: symmetric

declare (h, symmetric) tells the Maxima simplifier that h is a symmetric function. E.g., h (x, z, y) simplifies to h (x, y, z).

commutative is synonymous with symmetric.

Function: xthru (expr)

Combines all terms of expr (which should be a sum) over a common denominator without expanding products and exponentiated sums as ratsimp does. xthru cancels common factors in the numerator and denominator of rational expressions but only if the factors are explicit.

Sometimes it is better to use xthru before ratsimping an expression in order to cause explicit factors of the gcd of the numerator and denominator to be canceled thus simplifying the expression to be ratsimped.

Examples:

(%i1) ((x+2)^20 - 2*y)/(x+y)^20 + (x+y)^(-19) - x/(x+y)^20;
                                20
                 1       (x + 2)   - 2 y       x
(%o1)        --------- + --------------- - ---------
                    19             20             20
             (y + x)        (y + x)        (y + x)
(%i2) xthru (%);
                                 20
                          (x + 2)   - y
(%o2)                     -------------
                                   20
                            (y + x)

Next: , Previous: Simplification, Up: Top   [Contents][Index]

8 Plotting


Next: , Previous: Plotting, Up: Plotting   [Contents][Index]

8.1 Introduction to Plotting

To make the plots, Maxima can use an external plotting package or its own graphical interface Xmaxima (see the section on Plotting Formats). The plotting functions calculate a set of points and pass them to the plotting package together with a set of commands specific to that graphic program. In some cases those commands and data are saved in a file and the graphic program is executed giving it the name of that file to be parsed.

When a file is created, it will begiven the name maxout_xxx.format, where xxx is a number that is unique to every concurrently-running instance of Maxima and format is the name of the plotting format being used (gnuplot, xmaxima, mgnuplot or geomview).

There are commands to save the plot in a graphic format file, rather than showing it in the screen. The default name for that graphic file is maxplot.extension, where extension is the extension normally used for the kind of graphic file selected, but that name can also be specified by the user.

The maxout_xxx.format and maxplot.extension files are created in the directory specified by the system variable maxima_tempdir. That location can be changed by assigning to that variable (or to the environment variable MAXIMA_TEMPDIR) a string that represents a valid directory where Maxima can create new files. The output of the Maxima plotting command will be a list with the names of the file(s) created, including their complete path, or empty if no files are created. Those files should be deleted after the maxima session ends.

If the format used is either gnuplot or xmaxima, and the maxout_xxx.gnuplot or maxout_xxx.xmaxima was saved, gnuplot or xmaxima can be run, giving it the name of that file as argument, in order to view again a plot previously created in Maxima. Thus, when a Maxima plotting command fails, the format can be set to gnuplot or xmaxima and the plain-text file maxout_xxx.gnuplot (or maxout_xxx.xmaxima) can be inspected to look for the source of the problem.

The additional package draw provides functions similar to the ones described in this section with some extra features, but it only works with gnuplot. Note that some plotting options have the same name in both plotting packages, but their syntax and behavior is different. To view the documentation for a graphic option opt, type ?? opt in order to choose the information for either of those two packages.


Next: , Previous: Introduction to Plotting, Up: Plotting   [Contents][Index]

8.2 Plotting Formats

Maxima can use either Gnuplot, Xmaxima or Geomview as graphics program. Gnuplot and Geomview are external programs which must be installed separately, while Xmaxima is distributed with Maxima. To see which plotting format you are currently using, use the command get_plot_option(plot_format); and to change to another format, you can use set_plot_option([plot_format, <format>]), where <format> is the name of one of the formats described below. Those two commands show and change the global plot format, while each individual plotting command can use its own format, if it includes an option [plot_format, <format>] (see get_plot_option and set_plot_option).

The plotting formats are the following:


Next: , Previous: Plotting Formats, Up: Plotting   [Contents][Index]

8.3 Functions and Variables for Plotting

System variable: geomview_command

This variable stores the name of the command used to run the geomview program when the plot format is geomview. Its default value is "geomview". If the geomview program is not found unless you give its complete path or if you want to try a different version of it, you may change the value of this variable. For instance,

(%i1) geomview_command: "/usr/local/bin/my_geomview"$
Function: get_plot_option (keyword, index)

Returns the current default value of the option named keyword, which is a list. The optional argument index must be a positive integer which can be used to extract only one element from the list (element 1 is the name of the option).

See also set_plot_option, remove_plot_option and the section on Plotting Options.

System variable: gnuplot_command

This variable stores the name of the command used to run the gnuplot program when the plot format is gnuplot or gnuplot_pipes. Its default value is "gnuplot". If the gnuplot program is not found unless you give its complete path or if you want to try a different version of it, you may change the value of this variable. For instance,

(%i1) gnuplot_command: "/usr/local/bin/my_gnuplot"$
System variable: gnuplot_file_args

When a graphic file is going to be created using gnuplot, this variable is used to specify the format used to print the file name given to gnuplot. Its default value is "~a" in SBCL and Openmcl, and "~s" in other lisp versions, which means that the name of the file will be passed without quotes if SBCL or Openmcl are used and within quotes if other Lisp versions are used. The contents of this variable can be changed in order to add options for the gnuplot program, adding those options before the format directive "~s".

System variable: gnuplot_view_args

This variable is the format used to parse the argument that will be passed to the gnuplot program when the plot format is gnuplot. Its default value is "-persist ~a" when SBCL or Openmcl are used, and "-persist ~s" with other Lisp variants, where "~a" or "~s" will be replaced with the name of the file where the gnuplot commands have been written (usually "maxout_xxx.gnuplot"). The option -persist tells gnuplot to exit after the commands in the file have been executed, without closing the window that displays the plot.

Those familiar with gnuplot, might want to change the value of this variable. For example, by changing it to:

(%i1) gnuplot_view_args: "~s -"$

gnuplot will not be closed after the commands in the file have been executed; thus, the window with the plot will remain, as well as the gnuplot interactive shell where other commands can be issued in order to modify the plot.

In Windows versions of Gnuplot older than 4.6.3 the behavior of "~s -" and "-persist ~s" were the opposite; namely, "-persist ~s" made the plot window and the gnuplot interactive shell remain, while "~s -" closed the gnuplot shell keeping the plot window. Therefore, when older gnuplot versions are used in Windows, it might be necessary to adjust the value of gnuplot_view_args.

Function: julia (x, y, ...options...)

Creates a graphic representation of the Julia set for the complex number (x + i y). The two mandatory parameters x and y must be real. This program is part of the additional package dynamics, but that package does not have to be loaded; the first time julia is used, it will be loaded automatically.

Each pixel in the grid is given a color corresponding to the number of iterations it takes the sequence that starts at that point to move out of the convergence circle of radius 2 centered at the origin. The number of pixels in the grid is controlled by the grid plot option (default 30 by 30). The maximum number of iterations is set with the option iterations. The program sets its own default palette: magenta, violet, blue, cyan, green, yellow, orange, red, brown and black, but it can be changed by adding an explicit palette option in the command.

The default domain used goes from -2 to 2 in both axes and can be changed with the x and y options. By default, the two axes are shown with the same scale, unless the option yx_ratio is used or the option same_xy is disabled. Other general plot options are also accepted.

The following example shows a region of the Julia set for the number -0.55 + i0.6. The option color_bar_tics is used to prevent Gnuplot from adjusting the color box up to 40, in which case the points corresponding the maximum 36 iterations would not be black.

(%i1) julia (-0.55, 0.6, [iterations, 36], [x, -0.3, 0.2],
      [y, 0.3, 0.9], [grid, 400, 400], [color_bar_tics, 0, 6, 36])$
figures/plotting4
Function: make_transform ([var1, var2, var3], fx, fy, fz)

Returns a function suitable to be used in the option transform_xy of plot3d. The three variables var1, var2, var3 are three dummy variable names, which represent the 3 variables given by the plot3d command (first the two independent variables and then the function that depends on those two variables). The three functions fx, fy, fz must depend only on those 3 variables, and will give the corresponding x, y and z coordinates that should be plotted. There are two transformations defined by default: polar_to_xy and spherical_to_xyz. See the documentation for those two transformations.

Function: mandelbrot (options)

Creates a graphic representation of the Mandelbrot set. This program is part of the additional package dynamics, but that package does not have to be loaded; the first time mandelbrot is used, the package will be loaded automatically.

This program can be called without any arguments, in which case it will use a default value of 9 iterations per point, a grid with dimensions set by the grid plot option (default 30 by 30) and a region that extends from -2 to 2 in both axes. The options are all the same that plot2d accepts, plus an option iterations to change the number of iterations.

Each pixel in the grid is given a color corresponding to the number of iterations it takes the sequence starting at zero to move out of the convergence circle of radius 2, centered at the origin. The maximum number of iterations is set by the option iterations. The program uses its own default palette: magenta,violet, blue, cyan, green, yellow, orange, red, brown and black, but it can be changed by adding an explicit palette option in the command. By default, the two axes are shown with the same scale, unless the option yx_ratio is used or the option same_xy is disabled.

Example:

[grid,400,400])$

(%i1) mandelbrot ([iterations, 30], [x, -2, 1], [y, -1.2, 1.2],
            [grid,400,400])$
figures/plotting5
System function: polar_to_xy

It can be given as value for the transform_xy option of plot3d. Its effect will be to interpret the two independent variables in plot3d as the distance from the z axis and the azimuthal angle (polar coordinates), and transform them into x and y coordinates.

Function: plot2d
    plot2d (expr, range_x, options)
    plot2d (expr_1=expr_2, range_x, range_y, options)
    plot2d ([parametric, expr_x, expr_y, range], options)
    plot2d ([discrete, points], options)
    plot2d ([contour, expr], range_x, range_y, options)
    plot2d ([type_1, …, type_n], options)

There are 5 types of plots that can be plotted by plot2d:

  1. Explicit functions. plot2d (expr, range_x, options), where expr is an expression that depends on only one variable, or the name of a function with one input parameter and numerical results. range_x is a list with three elements, the first one being the name of the variable that will be shown on the horizontal axis of the plot, and the other two elements should be two numbers, the first one smaller than the second, that define the minimum and maximum values to be shown on the horizontal axis. The name of the variable used in range_x must be the same variable on which expr depends. The result will show in the vertical axis the corresponding values of the expression or function for each value of the variable in the horizontal axis.
  2. Implicit functions. plot2d (expr_1=expr_2, range_x, range_y, options), where expr_1 and expr_2 are two expressions that can depend on one or two variables. range_x and range_y must be two lists of three elements that define the ranges for the variables in the two axes of the plot; the first element of each list is the name of the corresponding variable, and the other two elements are the minimum and maximum values for that variable. The two variables on which expr_1 and expr_2 can depend are those specified by range_x and range_y. The result will be a curve or a set of curves where the equation expr_1=expr_2 is true.
  3. Parametric functions. plot2d ([parametric, expr_x, expr_y, range], options), where expr_x and expr_y are two expressions that depend on a single parameter. range must be a three-element list; the first element must be the name of the parameter on which expr_x and expr_y depend, and the other two elements must be the minimum and maximum values for that parameter. The result will be a curve in which the horizontal and vertical coordinates of each point are the values of expr_x and expr_y for a value of the parameter within the range given.
  4. Set of points. plot2d ([discrete, points], options), displays a list of points, joined by segments by default. The horizontal and vertical coordinates of each of those points can be specified in three different ways: With two lists of the same length, in which the elements of the first list are the horizontal coordinates of the points and the second list are the vertical coordinates, or with a list of two-element lists, each one corresponding to the two coordinates of one of the points, or with a single list that defines the vertical coordinates of the points; in this last case, the horizontal coordinates of the n points will be assumed to be the first n natural numbers.
  5. Contour lines. plot2d ([contour, expr], range_x, range_y, options), where expr is an expression that depends on two variables. range_x and range_y will be lists whose first elements are the names of those two variables, followed by two numbers that set the minimum and maximum values for them. The first variable will be represented along the horizontal axis and the second along the vertical axis. The result will be a set of curves along which the given expression has certain values. If those values are not specified with the option levels, plotd2d will try to choose, at the most, 8 values of the form d*10^n, where d is either 1, 2 or 5, all of them within the minimum and maximum values of expr within the given ranges.

At the end of a plot2d command several of the options described in Plotting Options can be used. Many instances of the 5 types described above can be combined into a single plot, by putting them inside a list: plot2d ([type_1, …, type_n], options). If one of the types included in the list require range_x or range_y, those ranges should come immediately after the list.

If there are several plots to be plotted, a legend will be written to identity each of the expressions. The labels that should be used in that legend can be given with the option legend. If that option is not used, Maxima will create labels from the expressions or function names.

Examples:

  1. Explicit function.
    (%i1) plot2d (sin(x), [x, -%pi, %pi])$
    
    figures/plotting6
  2. Implicit function.
    (%i1) plot2d (x^2-y^3+3*y=2, [x,-2.5,2.5], [y,-2.5,2.5])$
    
    figures/plotting3
  3. Parametric function.
    (%i1) r: (exp(cos(t))-2*cos(4*t)-sin(t/12)^5)$
    (%i2) plot2d([parametric, r*sin(t), r*cos(t), [t,-8*%pi,8*%pi]])$
    
    figures/plotting11
  4. Set of points.
    (%i1) plot2d ([discrete, makelist(i*%pi, i, 1, 5),
                                [0.6, 0.9, 0.2, 1.3, 1]])$
    
    figures/plotting14
  5. Contour lines.
    (%i1) plot2d ([contour, u^3 + v^2], [u, -4, 4], [v, -4, 4])$
    
    figures/plotting2

Examples using options.

If an explicit function grows too fast, the y option can be used to limit the values in the vertical axis:

(%i1) plot2d (sec(x), [x, -2, 2], [y, -20, 20])$
figures/plotting7

When the plot box is disabled, no labels are created for the axes. In that case, instead of using xlabel and ylabel to set the names of the axes, it is better to use option label, which allows more flexibility. Option yx_ratio is used to change the default rectangular shape of the plot; in this example the plot will fill a square.

(%i1) plot2d ( x^2 - 1, [x, -3, 3], nobox, grid2d,
      [yx_ratio, 1], [axes, solid], [xtics, -2, 4, 2],
      [ytics, 2, 2, 6], [label, ["x", 2.9, -0.3],
      ["x^2-1", 0.1, 8]], [title, "A parabola"])$
figures/plotting8

A plot with a logarithmic scale in the vertical axis:

(%i1) plot2d (exp(3*s), [s, -2, 2], logy)$
figures/plotting9

Plotting functions by name:

(%i1) F(x) := x^2 $
(%i2) :lisp (defun |$g| (x) (m* x x x))
$g
(%i2) H(x) := if x < 0 then x^4 - 1 else 1 - x^5 $
(%i3) plot2d ([F, G, H], [u, -1, 1], [y, -1.5, 1.5])$
figures/plotting10

Plot of a circle, using its parametric representation, together with the function -|x|. The circle will only look like a circle if the scale in the two axes is the same, which is done with the option same_xy.

(%i1) plot2d([[parametric, cos(t), sin(t), [t,0,2*%pi]], -abs(x)],
         [x, -sqrt(2), sqrt(2)], same_xy)$
figures/plotting12

A plot of 200 random numbers between 0 and 9:

(%i1) plot2d ([discrete, makelist ( random(10), 200)])$
figures/plotting13

In the next example a table with three columns is saved in a file “data.txt” which is then read and the second and third column are plotted on the two axes:

(%i1) display2d:false$
(%i2) with_stdout ("data.txt", for x:0 thru 10 do
                             print (x, x^2, x^3))$
(%i3) data: read_matrix ("data.txt")$
(%i4) plot2d ([discrete, transpose(data)[2], transpose(data)[3]],
  [style,points], [point_type,diamond], [color,red])$
figures/plotting15

A plot of discrete data points together with a continuous function:

(%i1) xy: [[10, .6], [20, .9], [30, 1.1], [40, 1.3], [50, 1.4]]$
(%i2) plot2d([[discrete, xy], 2*%pi*sqrt(l/980)], [l,0,50],
        [style, points, lines], [color, red, blue],
        [point_type, asterisk],
        [legend, "experiment", "theory"],
        [xlabel, "pendulum's length (cm)"],
        [ylabel, "period (s)"])$
figures/plotting16

See also the section about Plotting Options.

Function: plot3d
    plot3d (expr, x_range, y_range, …, options, …)
    plot3d ([expr_1, …, expr_n], x_range, y_range, …, options, …)

Displays a plot of one or more surfaces defined as functions of two variables or in parametric form.

The functions to be plotted may be specified as expressions or function names. The mouse can be used to rotate the plot looking at the surface from different sides.

Examples.

Plot of a function of two variables:

(%i1) plot3d (u^2 - v^2, [u, -2, 2], [v, -3, 3], [grid, 100, 100],
        nomesh_lines)$
figures/plotting17

Use of the z option to limit a function that goes to infinity (in this case the function is minus infinity on the x and y axes); this also shows how to plot with only lines and no shading:

(%i1) plot3d ( log ( x^2*y^2 ), [x, -2, 2], [y, -2, 2], [z, -8, 4],
         nopalette, [color, magenta])$
figures/plotting18

The infinite values of z can also be avoided by choosing a grid that does not fall on any points where the function is undefined, as in the next example, which also shows how to change the palette and how to include a color bar that relates colors to values of the z variable:

(%i1) plot3d (log (x^2*y^2), [x, -2, 2], [y, -2, 2],[grid, 29, 29],
       [palette, [gradient, red, orange, yellow, green]],
       color_bar, [xtics, 1], [ytics, 1], [ztics, 4],
       [color_bar_tics, 4])$
figures/plotting19

Two surfaces in the same plot. Ranges specific to one of the surfaces can be given by placing each expression and its ranges in a separate list; global ranges for the complete plot are also given after the function definitions.

(%i1) plot3d ([[-3*x - y, [x, -2, 2], [y, -2, 2]],
   4*sin(3*(x^2 + y^2))/(x^2 + y^2), [x, -3, 3], [y, -3, 3]],
   [x, -4, 4], [y, -4, 4])$
figures/plotting20

Plot of a Klein bottle, defined parametrically:

(%i1) expr_1: 5*cos(x)*(cos(x/2)*cos(y)+sin(x/2)*sin(2*y)+3)-10$
(%i2) expr_2: -5*sin(x)*(cos(x/2)*cos(y)+sin(x/2)*sin(2*y)+3)$
(%i3) expr_3: 5*(-sin(x/2)*cos(y)+cos(x/2)*sin(2*y))$
(%i4) plot3d ([expr_1, expr_2, expr_3], [x, -%pi, %pi],
        [y, -%pi, %pi], [grid, 50, 50])$
figures/plotting21

Plot of a “spherical harmonic” function, using the predefined transformation, spherical_to_xyz to transform from spherical coordinates to rectangular coordinates. See the documentation for spherical_to_xyz.

(%i1) plot3d (sin(2*theta)*cos(phi), [theta,0,%pi], [phi,0,2*%pi],
      [transform_xy, spherical_to_xyz], [grid, 30, 60], nolegend)$
figures/plotting22

Use of the pre-defined function polar_to_xy to transform from cylindrical to rectangular coordinates. See the documentation for polar_to_xy.

(%i1) plot3d (r^.33*cos(th/3), [r,0,1], [th,0,6*%pi], nobox,
    nolegend, [grid, 12, 80], [transform_xy, polar_to_xy])$
figures/plotting23

Plot of a sphere using the transformation from spherical to rectangular coordinates. Option same_xyz is used to get the three axes scaled in the same proportion. When transformations are used, it is not convenient to eliminate the mesh lines, because Gnuplot will not show the surface correctly.

(%i1) plot3d ( 5, [theta,0,%pi], [phi,0,2*%pi], same_xyz, nolegend,
  [transform_xy, spherical_to_xyz], [mesh_lines_color,blue],
  [palette,[gradient,"#1b1b4e", "#8c8cf8"]])$
figures/plotting24

Definition of a function of two-variables using a matrix. Notice the single quote in the definition of the function, to prevent plot3d from failing when it realizes that the matrix will require integer indices.

(%i1) M: matrix([1,2,3,4], [1,2,3,2], [1,2,3,4], [1,2,3,3])$
(%i2) f(x, y) := float('M [round(x), round(y)])$
(%i3) plot3d (f(x,y), [x,1,4], [y,1,4], [grid,3,3], nolegend)$
figures/plotting25

By setting the elevation equal to zero, a surface can be seen as a map in which each color represents a different level.

(%i1) plot3d (cos (-x^2 + y^3/4), [x,-4,4], [y,-4,4], [zlabel,""],
       [mesh_lines_color,false], [elevation,0], [azimuth,0],
       color_bar, [grid,80,80], noztics, [color_bar_tics,1])$
figures/plotting26

See also Plotting Options.

System variable: plot_options

This option is being kept for compatibility with older versions, but its use is deprecated. To set global plotting options, see their current values or remove options, use set_plot_option, get_plot_option and remove_plot_option.

Function: remove_plot_option (name)

Removes the default value of an option. The name of the option must be given.

See also set_plot_option, get_plot_option and Plotting Options.

Function: set_plot_option (option)

Accepts any of the options listed in the section Plotting Options, and saves them for use in plotting commands. The values of the options set in each plotting command will have precedence, but if those options are not given, the default values set with this function will be used.

set_plot_option evaluates its argument and returns the complete list of options (after modifying the option given). If called without any arguments, it will simply show the list of current default options.

See also remove_plot_option, get_plot_option and the section on Plotting Options.

Example:

Modification of the grid values.

(%i1) set_plot_option ([grid, 30, 40]);
(%o1) [[plot_format, gnuplot_pipes], [grid, 30, 40], 
[run_viewer, true], [axes, true], [nticks, 29], [adapt_depth, 5], 
[color, blue, red, green, magenta, black, cyan], 
[point_type, bullet, box, triangle, plus, times, asterisk], 
[palette, [gradient, green, cyan, blue, violet], 
[gradient, magenta, violet, blue, cyan, green, yellow, orange, 
red, brown, black]], [gnuplot_preamble, ], [gnuplot_term, default]]
System function: spherical_to_xyz

It can be given as value for the transform_xy option of plot3d. Its effect will be to interpret the two independent variables and the function in plot3d as the spherical coordinates of a point (first, the angle with the z axis, then the angle of the xy projection with the x axis and finally the distance from the origin) and transform them into x, y and z coordinates.


Next: , Previous: Functions and Variables for Plotting, Up: Plotting   [Contents][Index]

8.4 Plotting Options

All options consist of a list starting with one of the keywords in this section, followed by one or more values. If the option appears inside one of the plotting commands, its value will be local for that command. It the option is given as argument to set_plot_option, its value will be global and used in all plots, unless it is overridden by a local value.

Some of the options may have different effects in different plotting commands as it will be pointed out in the following list. The options that accept among their possible values true or false, can also be set to true by simply writing their names, and false by writing their names with the prefix no. For instance, typing logx as an option is equivalent to writing [logx, true] and nobox is equivalent to [box, false]. When just the name of the option is used for an option which cannot have a value true, it means that any value previously assigned to that option will be removed, leaving it to the graphic program to decide what to do.

Plot option: adapt_depth [adapt_depth, integer]

Default value: 5

The maximum number of splittings used by the adaptive plotting routine of plot2d; integer must be a non-negative integer. A value of zero means that adaptive plotting will not be used and the resulting plot will have 1+4*nticks points (see option nticks). To have more control on the number of points and their positions, a list of points can be created and then plotted using the discrete method of plot2d.

Plot option: axes [axes, symbol], axes, noaxes

Default value: true

Where symbol can be either true, false, x, y or solid. If false, no axes are shown; if equal to x or y only the x or y axis will be shown; if it is equal to true, both axes will be shown and solid will show the two axes with a solid line, rather than the default broken line. This option does not have any effect in the 3 dimensional plots. The single keywords axes and noaxes can be used as synonyms for [axes, true] and [axes, false].

Plot option: azimuth [azimuth, number]

Default value: 30

A plot3d plot can be thought of as starting with the x and y axis in the horizontal and vertical axis, as in plot2d, and the z axis coming out of the screen. The z axis is then rotated around the x axis through an angle equal to elevation and then the new xy plane is rotated around the new z axis through an angle azimuth. This option sets the value for the azimuth, in degrees.

See also elevation.

Plot option: box [box, symbol], box, nobox

Default value: true

If set to true, a bounding box will be drawn for the plot; if set to false, no box will be drawn. The single keywords box and nobox can be used as synonyms for [box, true] and [box, false].

Plot option: color [color, color_1, …, color_n]

In 2d plots it defines the color (or colors) for the various curves. In plot3d, it defines the colors used for the mesh lines of the surfaces, when no palette is being used.

If there are more curves or surfaces than colors, the colors will be repeated in sequence. The valid colors are red, green, blue, magenta, cyan, yellow, orange, violet, brown, gray, black, white, or a string starting with the character # and followed by six hexadecimal digits: two for the red component, two for green component and two for the blue component. If the name of a given color is unknown color, black will be used instead.

Plot option: color_bar [color_bar, symbol], color_bar, nocolor_bar

Default value: false in plot3d, true in mandelbrot and julia

Where symbol can be either true or false. If true, whenever plot3d, mandelbrot or julia use a palette to represent different values, a box will be shown on the right, showing the corresponding between colors and values. The single keywords color_bar and nocolor_bar can be used as synonyms for [color_bar, true] and [color_bar, false].

Plot option: color_bar_tics [color_bar_tics, x1, x2, x3], color_bar_tics, nocolor_bar_tics

Defines the values at which a mark and a number will be placed in the color bar. The first number is the initial value, the second the increments and the third is the last value where a mark is placed. The second and third numbers can be omitted. When only one number is given, it will be used as the increment from an initial value that will be chosen automatically. The single keyword color_bar_tics removes a value given previously, making the graphic program use its default for the values of the tics and nocolor_bar_tics will not show any tics on the color bar.

Plot option: elevation [elevation, number]

Default value: 60

A plot3d plot can be thought of as starting with the x and y axis in the horizontal and vertical axis, as in plot2d, and the z axis coming out of the screen. The z axis is then rotated around the x axis through an angle equal to elevation and then the new xy plane is rotated around the new z axis through an angle azimuth. This option sets the value for the elevation, in degrees.

See also azimuth.

Plot option: grid [grid, integer, integer]

Default value: 30, 30

Sets the number of grid points to use in the x- and y-directions for three-dimensional plotting or for the julia and mandelbrot programs.

For a way to actually draw a grid See grid2d.

Plot option: grid2d [grid2d, value], grid2d, nogrid2d

Default value: false

Shows a grid of lines on the xy plane. The points where the grid lines are placed are the same points where tics are marked in the x and y axes, which can be controlled with the xtics and ytics options. The single keywords grid2d and nogrid2d can be used as synonyms for [grid2d, true] and [grid2d, false].

See also grid.

Plot option: iterations [iterations, value]

Default value: 9

Number of iterations made by the programs mandelbrot and julia.

Plot option: label [label, [string, x, y], …]

Writes one or several labels in the points with x, y coordinates indicated after each label.

Plot option: legend [legend, string_1, …, string_n], legend, nolegend

It specifies the labels for the plots when various plots are shown. If there are more plots than the number of labels given, they will be repeated. If given the value false, no legends will be shown. By default, the names of the expressions or functions will be used, or the words discrete1, discrete2, …, for discrete sets of points. The single keyword legend removes any previously defined legends, leaving it to the plotting program to set up a legend. The keyword nolegend is a synonym for [legend, false].

Plot option: levels [levels, number, …]

This option is used by plot2d to do contour plots. If only one number is given after the keyword levels, it must be a natural number; plot2d will try to plot that number of contours with values between the minimum and maximum value of the expression given, with the form d*10^n, where d is either 1, 2 or 5. Since not always it will be possible to find that number of levels in that interval, the number of contour lines show will be smaller than the number specified by this option.

If more than one number are given after the keyword levels, plot2d. will show the contour lines corresponding to those values of the expression plotted, if they exist within the domain used.

Plot option: logx [logx, value], logx, nologx

Default value: false

Makes the horizontal axes to be scaled logarithmically. It can be either true or false. The single keywords logx and nologx can be used as synonyms for [logx, true] and [logx, false].

Plot option: logy [logy, value], logy, nology

Default value: false

Makes the vertical axes to be scaled logarithmically. It can be either true or false. The single keywords logy and nology can be used as synonyms for [logy, true] and [logy, false].

Plot option: mesh_lines_color [mesh_lines_color, color], mesh_lines_color, no_mesh_lines

Default value: black

It sets the color used by plot3d to draw the mesh lines, when a palette is being used. It accepts the same colors as for the option color (see the list of allowed colors in color). It can also be given a value false to eliminate completely the mesh lines. The single keyword mesh_lines_color removes any previously defined colors, leaving it to the graphic program to decide what color to use. The keyword no_mesh_lines is a synonym for [mesh_lines_color, false]

Plot option: nticks [nticks, integer]

Default value: 29

When plotting functions with plot2d, it is gives the initial number of points used by the adaptive plotting routine for plotting functions. When plotting parametric functions with plot3d, it sets the number of points that will be shown for the plot.

Plot option: palette [palette, [palette_1], …, [palette_n]], palette, nopalette

It can consist of one palette or a list of several palettes. Each palette is a list with a keyword followed by values. If the keyword is gradient, it should be followed by a list of valid colors.

If the keyword is hue, saturation or value, it must be followed by 4 numbers. The first three numbers, which must be between 0 and 1, define the hue, saturation and value of a basic color to be assigned to the minimum value of z. The keyword specifies which of the three attributes (hue, saturation or value) will be increased according to the values of z. The last number indicates the increase corresponding to the maximum value of z. That last number can be bigger than 1 or negative; the corresponding values of the modified attribute will be rounded modulo 1.

Gnuplot only uses the first palette in the list; xmaxima will use the palettes in the list sequentially, when several surfaces are plotted together; if the number of palettes is exhausted, they will be repeated sequentially.

The color of the mesh lines will be given by the option mesh_lines_color. If palette is given the value false, the surfaces will not be shaded but represented with a mesh of curves only. In that case, the colors of the lines will be determined by the option color.

The single keyword palette removes any palette previously defined, leaving it to the graphic program to decide the palette to use and nopalette is a synonym for [palette, false].

Plot option: plotepsilon [plotepsilon, value]

Default value: 1e-6

This value is used by plot2d when plotting implicit functions or contour lines. When plotting an explicit function expr_1=expr_2, it is converted into expr_1-expr_2 and the points where that equals zero are searched. When a contour line for expr equal to some value is going to be plotted, the points where expr minus that value are equal to zero are searched. The search is done by computing those expressions at a grid of points (see sample). If at one of the points in that grid the absolute value of the expression is less than the value of plotepsilon, it will be assumed to be zero, and therefore, as being part of the curve to be plotted.

Plot option: plot_format [plot_format, format]

Default value: gnuplot, in Windows systems, or gnuplot_pipes in other systems.

Where format is one of the following: gnuplot, xmaxima, mgnuplot, gnuplot_pipes or geomview.

It sets the format to be used for plotting as explained in Plotting Formats.

Plot option: plot_realpart [plot_realpart, symbol], plot_realpart, noplot_realpart

Default value: false

If set to true, the functions to be plotted will be considered as complex functions whose real value should be plotted; this is equivalent to plotting realpart(function). If set to false, nothing will be plotted when the function does not give a real value. For instance, when x is negative, log(x) gives a complex value, with real value equal to log(abs(x)); if plot_realpart were true, log(-5) would be plotted as log(5), while nothing would be plotted if plot_realpart were false. The single keyword plot_realpart can be used as a synonym for [plot_realpart, true] and noplot_realpart is a synonym for [plot_realpart, false].

Plot option: point_type [point_type, type_1, …, type_n]

In gnuplot, each set of points to be plotted with the style “points” or “linespoints” will be represented with objects taken from this list, in sequential order. If there are more sets of points than objects in this list, they will be repeated sequentially. The possible objects that can be used are: bullet, circle, plus, times, asterisk, box, square, triangle, delta, wedge, nabla, diamond, lozenge.

Plot option: pdf_file [pdf_file, file_name]

Saves the plot into a PDF file with name equal to file_name, rather than showing it in the screen. By default, the file will be created in the directory defined by the variable maxima_tempdir, unless file_name contains the character “/”, in which case it will be assumed to contain the complete path where the file should be created. The value of maxima_tempdir can be changed to save the file in a different directory. When the option gnuplot_pdf_term_command is also given, it will be used to set up Gnuplot’s PDF terminal; otherwise, Gnuplot’s pdfcairo terminal will be used with solid colored lines of width 3, plot size of 17.2 cm by 12.9 cm and font of 18 points.

Plot option: png_file [png_file, file_name]

Saves the plot into a PNG graphics file with name equal to file_name, rather than showing it in the screen. By default, the file will be created in the directory defined by the variable maxima_tempdir, unless file_name contains the character “/”, in which case it will be assumed to contain the complete path where the file should be created. The value of maxima_tempdir can be changed to save the file in a different directory. When the option gnuplot_png_term_command is also given, it will be used to set up Gnuplot’s PNG terminal; otherwise, Gnuplot’s pngcairo terminal will be used, with a font of size 12.

Plot option: ps_file [ps_file, file_name]

Saves the plot into a Postscript file with name equal to file_name, rather than showing it in the screen. By default, the file will be created in the directory defined by the variable maxima_tempdir, unless file_name contains the character “/”, in which case it will be assumed to contain the complete path where the file should be created. The value of maxima_tempdir can be changed to save the file in a different directory. When the option gnuplot_ps_term_command is also given, it will be used to set up Gnuplot’s Postscript terminal; otherwise, Gnuplot’s postscript terminal will be used with the EPS option, solid colored lines of width 2, plot size of 16.4 cm by 12.3 cm and font of 24 points.

Plot option: run_viewer [run_viewer, symbol], run_viewer, norun_viewer

Default value: true

This option is only used when the plot format is gnuplot and the terminal is default or when the Gnuplot terminal is set to dumb (see gnuplot_term) and can have a true or false value.

If the terminal is default, a file maxout_xxx.gnuplot (or other name specified with gnuplot_out_file) is created with the gnuplot commands necessary to generate the plot. Option run_viewer controls whether or not Gnuplot will be launched to execute those commands and show the plot.

If the terminal is default, gnuplot is run to execute the commands in maxout_xxx.gnuplot, producing another file maxplot.txt (or other name specified with gnuplot_out_file). Option run_viewer controls whether or not that file, with an ASCII representation of the plot, will be shown in the Maxima or Xmaxima console.

Its default value, true, makes the plots appear in either the console or a separate graphics window. run_viewer and norun_viewer are synonyms for [run_viewer, true] and [run_viewer, false].

Plot option: same_xy [same_xy , value], same_xy, nosame_xy

It can be either true or false. If true, the scales used in the x and y axes will be the same, in either 2d or 3d plots. See also yx_ratio. same_xy and nosame_xy are synonyms for [same_xy, true] and [same_xy, false].

Plot option: same_xyz [same_xyz , value], same_xyz, nosame_xyz

It can be either true or false. If true, the scales used in the 3 axes of a 3d plot will be the same. same_xyz and nosame_xyz are synonyms for [same_xyz, true] and [same_xyz, false].

Plot option: sample [sample, nx, ny]

Default value: [sample, 50, 50]

nx and ny must be two natural numbers that will be used by plot2d to look for the points that make part of the plot of an implicit function or a contour line. The domain is divided into nx intervals in the horizontal axis and ny intervals in the vertical axis and the numerical value of the expression is computed at the borders of those intervals. Higher values of nx and ny will give smoother curves, but will increase the time needed to trace the plot. When there are critical points in the plot where the curve changes direction, to get better results it is more important to try to make those points to be at the border of the intervals, rather than increasing nx and ny.

Plot option: style [style, type_1, …, type_n], [style, [style_1], …, [style_n]]

The styles that will be used for the various functions or sets of data in a 2d plot. The word style must be followed by one or more styles. If there are more functions and data sets than the styles given, the styles will be repeated. Each style can be either lines for line segments, points for isolated points, linespoints for segments and points, or dots for small isolated dots. Gnuplot accepts also an impulses style.

Each of the styles can be enclosed inside a list with some additional parameters. lines accepts one or two numbers: the width of the line and an integer that identifies a color. The default color codes are: 1: blue, 2: red, 3: magenta, 4: orange, 5: brown, 6: lime and 7: aqua. If you use Gnuplot with a terminal different than X11, those colors might be different; for example, if you use the option [gnuplot_term, ps], color index 4 will correspond to black, instead of orange.

points accepts one two or three parameters; the first parameter is the radius of the points, the second parameter is an integer that selects the color, using the same code used for lines and the third parameter is currently used only by Gnuplot and it corresponds to several objects instead of points. The default types of objects are: 1: filled circles, 2: open circles, 3: plus signs, 4: x, 5: *, 6: filled squares, 7: open squares, 8: filled triangles, 9: open triangles, 10: filled inverted triangles, 11: open inverted triangles, 12: filled lozenges and 13: open lozenges.

linespoints accepts up to four parameters: line width, points radius, color and type of object to replace the points.

See also color and point_type.

Plot option: svg_file [svg_file, file_name]

Saves the plot into an SVG file with name equal to file_name, rather than showing it in the screen. By default, the file will be created in the directory defined by the variable maxima_tempdir, unless file_name contains the character “/”, in which case it will be assumed to contain the complete path where the file should be created. The value of maxima_tempdir can be changed to save the file in a different directory. When the option gnuplot_svg_term_command is also given, it will be used to set up Gnuplot’s SVG terminal; otherwise, Gnuplot’s svg terminal will be used with font of 14 points.

Plot option: t [t, min, max]

Default range for parametric plots.

Plot option: title [title, text]

Defines a title that will be written at the top of the plot.

Plot option: transform_xy [transform_xy, symbol], notransform_xy

Where symbol is either false or the result obtained by using the function transform_xy. If different from false, it will be used to transform the 3 coordinates in plot3d. notransform_xy removes any transformation function previously defined.

See make_transform, polar_to_xy and spherical_to_xyz.

Plot option: window [window, n]

Opens the plot in window number n, instead of the default window 0. If window number n is already opened, the plot in that window will be replaced by the current plot.

Plot option: x [x, min, max]

When used as the first option in a plot2d command (or any of the first two in plot3d), it indicates that the first independent variable is x and it sets its range. It can also be used again after the first option (or after the second option in plot3d) to define the effective horizontal domain that will be shown in the plot.

Plot option: xlabel [xlabel, string]

Specifies the string that will label the first axis; if this option is not used, that label will be the name of the independent variable, when plotting functions with plot2d the name of the first variable, when plotting surfaces with plot3d, or the first expression in the case of a parametric plot.

Plot option: xtics [xtics, x1, x2, x3], [xtics, false], xtics, noxtics

Defines the values at which a mark and a number will be placed in the x axis. The first number is the initial value, the second the increments and the third is the last value where a mark is placed. The second and third numbers can be omitted, in which case the first number is the increment from an initial value that will be chosen by the graphic program. If [xtics, false] is used, no marks or numbers will be shown along the x axis.

The single keyword xtics removes any values previously defined, leaving it to the graphic program to decide the values to use and noxtics is a synonym for [xtics, false]

Plot option: xy_scale [xy_scale, sx, sy]

In a 2d plot, it defines the ratio of the total size of the Window to the size that will be used for the plot. The two numbers given as arguments are the scale factors for the x and y axes.

This option does not change the size of the graphic window or the placement of the graph in the window. If you want to change the aspect ratio of the plot, it is better to use option yx_ratio. For instance, [yx_ratio, 10] instead of [xy_scale, 0.1, 1].

Plot option: y [y, min, max]

When used as one of the first two options in plot3d, it indicates that one of the independent variables is y and it sets its range. Otherwise, it defines the effective domain of the second variable that will be shown in the plot.

Plot option: ylabel [ylabel, string]

Specifies the string that will label the second axis; if this option is not used, that label will be “y”, when plotting explicit functions with plot2d, or the name of the second variable, when plotting surfaces with plot3d, or the second expression in the case of a parametric plot.

Plot option: ytics [ytics, y1, y2, y3], [ytics, false], ytics, noytics

Defines the values at which a mark and a number will be placed in the y axis. The first number is the initial value, the second the increments and the third is the last value where a mark is placed. The second and third numbers can be omitted, in which case the first number is the increment from an initial value that will be chosen by the graphic program. If [ytics, false] is used, no marks or numbers will be shown along the y axis.

The single keyword ytics removes any values previously defined, leaving it to the graphic program to decide the values to use and noytics is a synonym for [ytics, false]

Plot option: yx_ratio [yx_ratio, r]

In a 2d plot, the ratio between the vertical and the horizontal sides of the rectangle used to make the plot. See also same_xy.

Plot option: z [z, min, max]

Used in plot3d to set the effective range of values of z that will be shown in the plot.

Plot option: zlabel [zlabel, string]

Specifies the string that will label the third axis, when using plot3d. If this option is not used, that label will be “z”, when plotting surfaces, or the third expression in the case of a parametric plot. It can not be used with set_plot_option and it will be ignored by plot2d.

Plot option: zmin [zmin, z], zmin

In 3d plots, the value of z that will be at the bottom of the plot box.

The single keyword zmin removes any value previously defined, leaving it to the graphic program to decide the value to use.

Plot option: ztics [ztics, z1, z2, z3], [ztics, false], ztics, noztics

Defines the values at which a mark and a number will be placed in the z axis. The first number is the initial value, the second the increments and the third is the last value where a mark is placed. The second and third numbers can be omitted, in which case the first number is the increment from an initial value that will be chosen by the graphic program. If [ztics, false] is used, no marks or numbers will be shown along the z axis.

The single keyword ztics removes any values previously defined, leaving it to the graphic program to decide the values to use and noztics is a synonym for [ztics, false]


Next: , Previous: Plotting Options, Up: Plotting   [Contents][Index]

8.5 Gnuplot Options

There are several plot options specific to gnuplot. All of them consist of a keyword (the name of the option), followed by a string that should be a valid gnuplot command, to be passed directly to gnuplot. In most cases, there exist a corresponding plotting option that will produce a similar result and whose use is more recommended than the gnuplot specific option.

Plot option: gnuplot_term [gnuplot_term, terminal_name]

Sets the output terminal type for gnuplot. The argument terminal_name can be a string or one of the following 3 special symbols

Plot option: gnuplot_out_file [gnuplot_out_file, file_name]

It can be used to replace the default name for the file that contains the commands that will interpreted by gnuplot, when the terminal is set to default, or to replace the default name of the graphic file that gnuplot creates, when the terminal is different from default. If it contains one or more slashes, “/”, the name of the file will be left as it is; otherwise, it will be appended to the path of the temporary directory. The complete name of the files created by the plotting commands is always sent as output of those commands so they can be seen if the command is ended by semi-colon.

When used in conjunction with the gnuplot_term option, it can be used to save the plot in a file, in one of the graphic formats supported by Gnuplot. To create PNG, PDF, Postscript or SVG, it is easier to use options png_file, pdf_file, ps_file, or svg_file.

Plot option: gnuplot_script_file [gnuplot_script_file, file_name_or_function]

Creates a plot with plot2d, plot3d, mandelbrot or julia using the gnuplot plot_format and saving the script sent to Gnuplot in the file specified by file_name_or_function. The value file_name_or_function can be a string or a Maxima function of one variable that returns a string. If that string corresponds to a complete file path (directory and file name), the script will be created in that file and will not be deleted after Maxima is closed; otherwise, the string will give the name of a file to be created in the temporary directory and deleted when Maxima is closed.

In this example, the script file name is set to “sin.gnuplot”, in the current directory.

(%i1) plot2d( sin(x), [x,0,2*%pi], [gnuplot_script_file, "./sin.gnuplot"]);

(%o1) ["./sin.gnuplot"]

In this example, gnuplot_maxout_prt(file) is a function that takes the default file name, file. It constructs a full file name for the data file by interpolating a random 8-digit integer with a pad of zeros into the default file name (“maxout” followed by the id number of the Maxima process, followed by “.gnuplot”). The temporary directory is determined by maxima_tempdir (it is “/tmp” in this example).

(%i1) gnuplot_maxout_prt(file) := block([beg,end],
        [beg,end] : split(file,"."),
        printf(false,"~a_~8,'0d.~a",beg,random(10^8-1),end)) $

(%i2) plot2d( sin(x), [x,0,2*%pi], [gnuplot_script_file, gnuplot_maxout_prt]);

(%o2) ["/tmp/maxout68715_09606909.gnuplot"]

By default, the script would have been saved in a file named maxoutXXXXX.gnuplot (XXXXX=68715 in this example) in the temporary directory. If the print statement in function gnuplot_maxout_prt above included a directory path, the file would have been saved in that directory rather than in the temporary directory.

Plot option: gnuplot_pm3d [gnuplot_pm3d, value]

With a value of false, it can be used to disable the use of PM3D mode, which is enabled by default.

Plot option: gnuplot_preamble [gnuplot_preamble, string]

This option inserts gnuplot commands before any other commands sent to Gnuplot. Any valid gnuplot commands may be used. Multiple commands should be separated with a semi-colon. See also gnuplot_postamble.

Plot option: gnuplot_postamble [gnuplot_postamble, string]

This option inserts gnuplot commands after other commands sent to Gnuplot and right before the plot command is sent. Any valid gnuplot commands may be used. Multiple commands should be separated with a semi-colon. See also gnuplot_preamble.

Plot option: gnuplot_default_term_command

[gnuplot_default_term_command, command]

The gnuplot command to set the terminal type for the default terminal. It this option is not set, the command used will be: "set term wxt size 640,480 font \",12\"; set term pop".

Plot option: gnuplot_dumb_term_command

[gnuplot_dumb_term_command, command]

The gnuplot command to set the terminal type for the dumb terminal. It this option is not set, the command used will be: "set term dumb 79 22", which makes the text output 79 characters by 22 characters.

Plot option: gnuplot_pdf_term_command [gnuplot_pdf_term_command, command]

The gnuplot command to set the terminal type for the PDF terminal. If this option is not set, the command used will be: "set term pdfcairo color solid lw 3 size 17.2 cm, 12.9 cm font \",18\"". See the gnuplot documentation for more information.

Plot option: gnuplot_png_term_command [gnuplot_png_term_command, command]

The gnuplot command to set the terminal type for the PNG terminal. If this option is not set, the command used will be: "set term pngcairo font \",12\"". See the gnuplot documentation for more information.

Plot option: gnuplot_ps_term_command [gnuplot_ps_term_command, command]

The gnuplot command to set the terminal type for the PostScript terminal. If this option is not set, the command used will be: "set term postscript eps color solid lw 2 size 16.4 cm, 12.3 cm font \",24\"". See the gnuplot documentation for set term postscript for more information.

Plot option: gnuplot_strings [gnuplot_strings, value]

With a value of true, all strings used in labels and titles will be interpreted by gnuplot as “enhanced” text, if the terminal being used supports it. In enhanced mode, some characters such as ^ and _ are not printed, but interpreted as formatting characters. For a list of the formatting characters and their meaning, see the documentation for enhanced in Gnuplot. The default value for this option is false, which will not treat any characters as formatting characters.

Plot option: gnuplot_svg_background

[gnuplot_svg_background, color]
nognuplot_svg_background

Specify the background color for SVG image output. color must be a string which specifies a color name recognized by Gnuplot, or an RGB triple of the form "#xxxxxx" where x is a hexadecimal digit. The default value is "white".

When the value of gnuplot_svg_background is false, the background is the default determined by Gnuplot. At present (April 2023), the Gnuplot default is to specify the background in SVG output as "none".

nognuplot_svg_background, specified by itself without a value, is equivalent to [gnuplot_svg_background, false].

Plot option: gnuplot_svg_term_command [gnuplot_svg_term_command, command]

The gnuplot command to set the terminal type for the SVG terminal. If this option is not set, the command used will be: "set term svg font \",14\"". See the gnuplot documentation for more information.

Plot option: gnuplot_curve_titles

This is an obsolete option that has been replaced by legend described above.

Plot option: gnuplot_curve_styles

This is an obsolete option that has been replaced by style.


Previous: Gnuplot Options, Up: Plotting   [Contents][Index]

8.6 Gnuplot_pipes Format Functions

Function: gnuplot_start ()

Opens the pipe to gnuplot used for plotting with the gnuplot_pipes format. Is not necessary to manually open the pipe before plotting.

Function: gnuplot_close ()

Closes the pipe to gnuplot which is used with the gnuplot_pipes format.

Function: gnuplot_send (s)

Sends the command s to the gnuplot pipe. If that pipe is not currently opened, it will be opened before sending the command. s must be a string.

Function: gnuplot_restart ()

Closes the pipe to gnuplot which is used with the gnuplot_pipes format and opens a new pipe.

Function: gnuplot_replot
    gnuplot_replot ()
    gnuplot_replot (s)

Updates the gnuplot window. If gnuplot_replot is called with a gnuplot command in a string s, then s is sent to gnuplot before reploting the window.

Function: gnuplot_reset ()

Resets the state of gnuplot used with the gnuplot_pipes format. To update the gnuplot window call gnuplot_replot after gnuplot_reset.


Next: , Previous: Plotting, Up: Top   [Contents][Index]

9 Ввод и вывод


Next: , Previous: Ввод и вывод, Up: Ввод и вывод   [Contents][Index]

9.1 Комментарии

В Maxima любой текст, расположенный между /* и */, является комментарием.

Анализатор Maxima обрабатывает комментарии как пробелы, чтобы проще было различать лексемы во входном потоке, комментарий всегда завершает лексему. Следующий ввод a/* foo */b содержит две лексемы a и b, а не одну ab. Во всех остальных случаях комментарии игнорируются, что бы в них ни находилось.

Комментарии могут иметь сколько угодно уровней вложенности. Разделители /* и */ образуют соответствующие пары. Количество открывающих разделителей /* должно быть равно количеству закрывающих */.

Примеры:

(%i1) /* aa is a variable of interest */  aa : 1234;
(%o1)                         1234
(%i2) /* Value of bb depends on aa */  bb : aa^2;
(%o2)                        1522756
(%i3) /* User-defined infix operator */  infix ("b");
(%o3)                           b
(%i4) /* Parses same as a b c, not abc */  a/* foo */b/* bar */c;
(%o4)                         a b c
(%i5) /* Comments /* can be nested /* to any depth */ */ */  1 + xyz;
(%o5)                        xyz + 1

Next: , Previous: Комментарии, Up: Ввод и вывод   [Contents][Index]

9.2 Файлы

Файл – это область на определенном запоминающем устройстве, содержащая данные или текст. Файлы на дисках как-бы группируются в "директории", которые являются просто списками файлов. Для работы с файлами существуют следующие команды: save, load,

loadfile, stringout, batch, demo, writefile, closefile и appendfile.


Previous: Файлы, Up: Ввод и вывод   [Contents][Index]

9.3 Функции и переменные для ввода и вывода

Системная переменная: __

__ - введенное выражение, обрабатываемое в данный момент. То есть, пока вычисляется expr, __ равно expr.

Введенное выражение присваивается переменной __ до упрощения или вычисления. Однако, значение __ упрощается (но не вычисляется) во время вывода.

__ распознается функциями batch и load. В файле, обрабатываемом с помощью batch, __ означает то же самое, что и в режиме диалога. Когда файл обрабатывается функцией load, __ имеет значения последнего, введенного в режиме диалога или пакетном файле, выражения. __ не принимает значения выражений, которые вводятся в обрабатываемом файле. В частности, если load (filename) вызывается в режиме диалога, то во время выполнения файла __ имеет значение load(filename).

См. также _ и %.

Примеры:

(%i1) print ("I was called as", __);
I was called as print(I was called as, __) 
(%o1)              print(I was called as, __)
(%i2) foo (__);
(%o2)                     foo(foo(__))
(%i3) g (x) := (print ("Current input expression =", __), 0);
(%o3) g(x) := (print("Current input expression =", __), 0)
(%i4) [aa : 1, bb : 2, cc : 3];
(%o4)                       [1, 2, 3]
(%i5) (aa + bb + cc)/(dd + ee + g(x));
                            cc + bb + aa
Current input expression = -------------- 
                           g(x) + ee + dd
                                6
(%o5)                        -------
                             ee + dd
Системная переменная: _

_ - самое последнее из введенных выражений (таких как %i1, %i2, %i3, ...).

Введенное выражение присваивается переменной _ до упрощения или вычисления. Однако, это значение упрощается (но не вычисляется) во время вывода.

_ обрабатывается функциями batch и load. Во время обработки файла функцией batch переменная _ означает то же, что и в режиме диалога. Когда файл обрабатывается функцией load, значение переменной _ принимает последнее вычисленное выражение, которое было введено в диалоговом режиме или пакетном файле. Выражения, вводимые в обрабатываемом файле, не присваиваются переменной _.

См. также __ и %.

Примеры:

(%i1) 13 + 29;
(%o1)                          42
(%i2) :lisp $_
((MPLUS) 13 29)
(%i2) _;
(%o2)                          42
(%i3) sin (%pi/2);
(%o3)                           1
(%i4) :lisp $_
((%SIN) ((MQUOTIENT) $%PI 2))
(%i4) _;
(%o4)                           1
(%i5) a: 13$
(%i6) b: 29$
(%i7) a + b;
(%o7)                          42
(%i8) :lisp $_
((MPLUS) $A $B)
(%i8) _;
(%o8)                         b + a
(%i9) a + b;
(%o9)                          42
(%i10) ev (_);
(%o10)                         42
Системная переменная: %

% - вывод (%o1, %o2, o3, ...) последнего обработанного выражения, даже если он не выводится.

% обрабатывается командами batch и load. В файле, обрабатываемом командой batch, % имеет то же значение, что и в режиме диалога. В файле, обрабатываемого командой load, Значение % принимает вывод последнего обработанного в диалоговом режиме выражения. Переменной % не присваивается вывод выражений обрабатываемого файла.

См. также _, %% и %th.

Системная переменная: %%

В составных выражениях таких как block, lambda, или (s_1, ..., s_n), %% - значение предыдущего утверждения. К примеру выражения,

block (integrate (x^5, x), ev (%%, x=2) - ev (%%, x=1));
block ([prev], prev: integrate (x^5, x),
               ev (prev, x=2) - ev (prev, x=1));

дадут один и тот же результат, то есть 21/2.

Составное выражение может быть частью другого составного выражения. И в случае простого утверждения, и в случае, когда утверждение является составным выражением, %% принимает значение предыдущего утверждения. К примеру,

block (block (a^n, %%*42), %%/6)

выдаст 7*a^n.

Внутри составного утверждения, значение %% можно проверить в диалоге команды break. К примеру, следующее выражение

block (a: 42, break ())$

открывает диалог, в котором результатом ввода %%; будет 42.

В первом утверждении составного выражения или вне составного выражения переменная %% не определена.

Переменная %% распознается функциями batch и load, и имеет то же значение, что и в режиме диалога.

См. также %.

Управляющая переменная: %edispflag

Значение по умолчанию: false

Когда %edispflag установлена равной true, Maxima отображает %e отрицательной степени. К примеру, %e^-x отображается как 1/%e^x.

Функция: %th (i)

Значение i-го предыдущего вывода. То есть, если следующим вычисленным выражением будет вывод с номером n, то %th (m) примет значение вывода с номером (n - m).

%th полезна в пакетных batch-файлах или в ссылках на группу выведенных выражений. К примеру,

block (s: 0, for i:1 thru 10 do s: s + %th (i))$

присвоит переменной s сумму последних десяти выведенных выражений.

%th обрабатывается функциями batch и load. В файле, обрабатываемом функцией batch, %th означает то же, что и в режиме диалога. В файле, обрабатываемом командой load, %th ссылается на выведенные выражения, которые были вычислены последними в режиме диалога или пакетном файле. %th не ссылается на выражения, выводимые в процессе работы load.

См. также %.

Специальный символ: ?

Стоящий перед именем функции или переменной символ ? означает что это имя функции или переменной из Lisp, а не из Maxima. К примеру, ?round означает Lisp-функцию ROUND. См. дополнительно Lisp и Maxima.

Запись ? word (вопросительный знак и следующее за ним слово разделены пробелом) эквивалентна записи describe("word"). Вопросительный знак должен находиться в начале строки ввода, иначе он не определится как запрос на документацию.

Специальный символ: ??

Запись ?? word (?? и следующее за ним слово разделяются символом пробела) эквивалентна записи descrive("word", inexact).

Управляющая переменная: absboxchar

Значение по умолчанию: !

Символ absboxchar используется для изображения знака модуля вокруг, выражений, занимающих по высоте больше одной строчки.

Управляющая переменная: file_output_append

Значение по умолчанию: false

file_output_append управляет тем, будет ли вывод в функции добавляться в конец или замещать содержимое выводимого файла. Когда file_output_append равна true, такие функции добавляют вывод к файлу, иначе выводимый файл переписывается заново.

Функции save, strungout и with_stdout учитывают file_output_append. Остальные функции, которые записываю выход во внешние файлы, не учитывают file_output_append. В частности, графические и транслирующие функции всегда замещает содержимое выводимого файла, а tex и strungout всегда дописываю в конец.

Функция: appendfile (filename)

Добавляет копию консольного вывода в filename. appendfile работает так же как и writefile, но отличие в том, что если файл существует, он всегда дописывается.

closefile закрывает трансляцию в файл открытый функциями appendfile или writefile.

Функция: batch (filename)

Считывает выражения Maxima из filename, и обрабатывает их. batch ищет filename в директориях списка file_search_maxima. См. file_search.

filename содержит последовательность выражений Maxima, завершающихся символами ; или $. Специальные переменная % и функция %th ссылаются на предыдущие результаты внутри файла. Файл может включать конструкции :lisp. Символы пробела, табуляции и новой строки в файле игнорируются. Подходящий входной файл может быть создан при помощи текстового редактора или функцией stringout.

batch считывает каждое входящее выражение из filename, отображает его ввод в консоли, вычисляет соответствующее выходящее выражение и выводит его. Входящим выражениям присваиваются входные метки, а выходящим – выходные. batch вычисляет все входящие выражения файла до тех пор пока в них не встретится ошибка. Если запрашивается пользовательский ввод (к примеру, командами asksign или askinteger), выполнение batch останавливается для сбора требуемого ввода и затем продолжается.

Возможна остановка batch нажатием control-C в консоли. Эффект нажатия control-C зависит от реализации лежащего в основе Lisp.

batch может использоваться в различных целях. Для хранения рабочих командных строк, дающих возможность проводить демонстрации без ошибок, или может помочь организовать работу над решением сложных задач.

batch вычисляет свой аргумент. batch не возвращает значений.

См. также load, batchload и demo.

Функция: batchload (filename)

Считывает выражения Maxima из filename и вычисляет их, не отображая входные и выходные выражения и не присваивая ссылок выходным выражениям. Однако, печатаемый вывод (такой, какой производят команды print или describe) отображается.

Специальная переменная % и функция %th ссылается на предыдущие результаты из режима диалога, но не на результаты внутри файла. Файл не может включать конструкции :lisp.

batchload возвращает путь к filename в виде строки. batchload вычисляет свой аргумент.

См. также batch и load.

Функция: closefile ()

Закрывает запись в файл, открытую командой writefile или appendfile.

Функция: collapse (expr)

Сворачивает выражение expr делая все его общие (т.е. равные) ссылающимися на одни ячейки памяти, тем самым сохраняя память. Функция (collapse используется командой optimize. Таким образом, вызов collapse может быть полезным до выгрузки в save файл. Можно свернуть несколько выражений вместе используя команду collapse ([expr_1, ..., expr_n]). Аналогично, можно свернуть элементы массива A при помощи команды collapse (listarray ('A)).

Функция: concat (arg_1, arg_2, ...)

Сцепляет свои аргументы. Аргументы должны быть атомами. Возвращаемое значение является символом, если первый аргумент – символ, и строкой в противном случае.

concat вычисляет свои аргументы. Одиночная кавычка ' предотвращает вычисление.

(%i1) y: 7$
(%i2) z: 88$
(%i3) concat (y, z/2);
(%o3)                          744
(%i4) concat ('y, z/2);
(%o4)                          y44

Символу, полученному с помощью concat, можно присваивать значения и использовать его в выражениях. :: (двойное двоеточие) – оператор присваивания, который вычисляет свой левый операнд.

(%i5) a: concat ('y, z/2);
(%o5)                          y44
(%i6) a:: 123;
(%o6)                          123
(%i7) y44;
(%o7)                          123
(%i8) b^a;
                               y44
(%o8)                         b
(%i9) %, numer;
                               123
(%o9)                         b

Заметьте, что несмотря на то, что concat (1, 2) выглядит как число, результат является строкой.

(%i10) concat (1, 2) + 3;
(%o10)                       12 + 3
Функция: sconcat (arg_1, arg_2, ...)

Сцепляет аргументы в строки. В отличии от concat, аргументы не обязаны быть атомами.

(%i1) sconcat ("xx[", 3, "]:", expand ((x+y)^3));
(%o1)               xx[3]:y^3+3*x*y^2+3*x^2*y+x^3
Функция: disp (expr_1, expr_2, ...)

то же что и display, но отличается тем что значение аргументов отображаются без выражений. Это полезно для сложных аргументов, у которых нет имени или в случае, когда интерес представляет только значение без имени.

Функция: dispcon (tensor_1, tensor_2, ...)
Функция: dispcon (all)

Отображает ограничения аргументов, наложенные на них командой defcon. dispcon (all) отображает все ограничения, которые были заданы.

Функция: display (expr_1, expr_2, ...)

Отображает равенства, выравненные по центру. Левыми частями равенств являются не вычисленные выражения expr_i, a правыми – их значения. Эта функция полезна в блоках и конструкциях for для вывода промежуточных результатов. Аргументы display обычно являются атомами, переменными с индексом, или вызовами функций. См. также disp.

(%i1) display(B[1,2]);
                                      2
                         B     = X - X
                          1, 2
(%o1)                            done
Управляющая переменная: display2d

Значение по умолчанию: true

Когда display2d равна false, консольный вывод производится в строковой (одномерной) форме, а не в наглядной (двумерной).

Управляющая переменная: display_format_internal

Значение по умолчанию: false

Когда display_format_internal равна true, выражения отображаются без преобразования, которое "прячет" внутреннее математическое представление. Тогда вывод соответствует результату функции inpart, а не part.

Примеры:

User     part       inpart
a-b;      a - b     a + (- 1) b

           a            - 1
a/b;       -         a b
           b
                       1/2
sqrt(x);   sqrt(x)    x

          4 X        4
X*4/3;    ---        - X
           3         3
Функция: dispterms (expr)

Выводит друг под другом части expr. Первым отображается оператор выражения expr, затем каждое слагаемое суммы, множители произведения или части более общего выражения отображаются отдельно. Это полезно, когда expr слишком большое для иных способов отображения. К примеру, если P1, P2, ... – очень большие выражения, то программе может не хватить памяти при попытке отобразить P1 + P2 + ... как единое целое. Однако, dispterms (P1 + P2 + ...) отображает P1, затем ниже P2 и т. д. Если не использовать dispterms, когда показательное выражение слишком широко, для отображения в виде A^B, то оно выводится в виде expt (A, B) (или ncexpt (A, B) в случае A^^B).

Управляющая переменная: error_size

Значение по умолчанию: 10

error_size изменяет сообщения об ошибках, в зависимости от размера выражения, которое появляется в нем. Если размер выражения (определенный с помощью Lisp-функции ERROR-SIZE) больше чем error_size, выражение замещается символом, а символу присваивается выражение. Символы берутся из списка error_syms.

В противном случае, когда выражение меньше чем error_size, оно и выводится в сообщении.

См. также error и error_syms.

Пример:

ERROR-SIZE задает размер U равным 24.

(%i1) U: (C^D^E + B + A)/(cos(X-1) + 1)$

(%i2) error_size: 20$

(%i3) error ("Example expression is", U);

Example expression is errexp1
 -- an error.  Quitting.  To debug this try debugmode(true);
(%i4) errexp1;
                            E
                           D
                          C   + B + A
(%o4)                    --------------
                         cos(X - 1) + 1
(%i5) error_size: 30$

(%i6) error ("Example expression is", U);

                         E
                        D
                       C   + B + A
Example expression is --------------
                      cos(X - 1) + 1
 -- an error.  Quitting.  To debug this try debugmode(true);
Управляющая переменная: error_syms

Значение по умолчанию: [errexp1, errexp2, errexp3]

В сообщениях об ошибках, выражения большие чем error_size заменяются символами и присваиваются этим символам. Символы берутся из списка error_syms. Первое слишком большое выражения заменяется символом error_syms[1], второе символом error_syms[2] и так далее.

Если слишком больших выражений больше чем элементов в error_syms, то символы генерируются автоматически, n-ный символ равен concat ('errexp, n).

См. также error и error_size.

Функция: expt (a, b)

Если показательное выражение слишком широко для отображения в виде a^b), оно выводится в виде expt (a, b) (или ncexpt (a, b) в случае a^^b).

expt и ncexpt не распознаются при вводе.

Управляющая переменная: exptdispflag

Значение по умолчанию: true

Когда exptdispflag равна true, Maxima отображает выражения с отрицательными степенями в виде дробей, например X^(-1) в виде 1/X.

Функция: filename_merge (path, filename)

Составляет путь из path и filename. Если последняя часть пути path имеет форму ###.something, эта часть заменяется на filename.something. В противном случае последняя часть заменяется на filename.

Результатом является объект пути Lisp.

Функция: file_search (filename)
Функция: file_search (filename, pathlist)

file_search ищет файл filename и возвращает путь к этому файлу (в виде строки), если может его найти, иначе возвращает false. file_search (filename) ищет в определенных по умолчанию каталогах для поиска, которые указаны в переменных file_search_maxima, file_search_lisp и file_search_demo.

Перед попыткой сопоставить имя с шаблонами поиска файлов. file_search первым делом проверяет существование искомого файла. См. file_search_maxima о шаблонах поиска файла.

Аргумент filename может быть как путем с именем, так и просто именем файла. Если каталог включен в пути поиска вместе с поисковым шаблоном файла, то filename может быть именем без расширения. В примере

file_search ("/home/wfs/special/zeta.mac");
file_search ("zeta.mac");
file_search ("zeta");

будет найден один и тот же файл, если он существует и /home/wfs/special/###.mac включен в file_search_maxima.

file_search (filename, pathlist) осуществляет поиск в каталогах, заданных переменной pathlist, которая представляет из себя список строк. Аргумент pathlist замещает каталоги поиска, определенные по умолчанию, так если дан список путей, file_search ищет только в заданных там и не ищет в путях по умолчанию. Даже если pathlist содержит только один каталог, pathlist должен быть задан, как список из одного элемента.

Пользователь может изменять пути, определенные по умолчанию. См. file_search_maxima.

file_search используется функцией load, шаблоны поиска файлов берутся из file_search_maxima и file_search_lisp.

Управляющая переменная: file_search_maxima
Управляющая переменная: file_search_lisp
Управляющая переменная: file_search_demo

Эти переменные задают списки каталогов, в которых производят поиск функции load, demo и некоторые другие функции Maxima. По умолчанию в них заданы различные каталоги из путей установки Maxima.

Пользователь может изменить эти переменные, удалить значения по умолчанию или добавить дополнительные каталоги. Например,

file_search_maxima: ["/usr/local/foo/###.mac",
    "/usr/local/bar/###.mac"]$

удаляет начальные директории списка file_search_maxima, в то время как

file_search_maxima: append (file_search_maxima,
    ["/usr/local/foo/###.mac", "/usr/local/bar/###.mac"])$

добавляет две дополнительные директории. Иногда удобно разместить такие выражения в файле maxima-init.mac, чтобы путь поиска файла назначался автоматически при запуске Maxima.

При помощи шаблонов поиска файлов можно определить несколько расширений файлов и несколько путей. Строка ### заменяется запрашиваемым именем, в то время как список разделенных запятыми имен, заключенный в фигурные скобки, {foo,bar,baz} раскрывается в множество строк. В качестве примера предположим, что искомое имя – neumann, тогда

"/home/{wfs,gcj}/###.{lisp,mac}"

раскроется в /home/wfs/neumann.lisp, /home/gcj/neumann.lisp, /home/wfs/neumann.mac и /home/gcj/neumann.mac.

Функция: file_type (filename)

Возвращает предположение о содержимом filename, на основе его расширения. filename не должен ссылаться на существующий файл, не происходит попыток открыть файл и проверить содержимое.

Возвращаемое значение является одним из символов: object, lisp или maxima. Если расширение начинается на m или d, file_type возвращается maxima. Если расширение начинается на l, file_type возвращается lisp. Если ни один из перечисленных вариантов, то file_type возвращается object.

Функция: grind (expr)
Управляющая переменная: grind

Функция grind выводит expr в консоль в форме подходящем для ввода в Maxima. grind всегда возвращает done.

Когда expr является именем функции или макрокоманды, grind печатает определение функции или макрокоманды вместо просто имени.

См. также string, которая возвращает строку, а не печатает вывод. grind пытается печатать выражение способом, который делает его проще для чтения, чем вывод команды string.

Когда переменная grind равна true, вывод string и stringout имеет тот же вид, что и вывод grind. В противном случае специального форматирования вывода этих функций не производится. По умолчанию значение переменной grind равно false.

grind может так же быть задана как аргумент playback. Когда grind задана, playback печатает входное выражение в таком же виде как функция grind. В противном случае специального форматирования вывода не производится.

grind вычисляет свой аргумент.

Примеры:

(%i1) aa + 1729;
(%o1)                       aa + 1729
(%i2) grind (%);
aa+1729$
(%o2)                         done
(%i3) [aa, 1729, aa + 1729];
(%o3)                 [aa, 1729, aa + 1729]
(%i4) grind (%);
[aa,1729,aa+1729]$
(%o4)                         done
(%i5) matrix ([aa, 17], [29, bb]);
                           [ aa  17 ]
(%o5)                      [        ]
                           [ 29  bb ]
(%i6) grind (%);
matrix([aa,17],[29,bb])$
(%o6)                         done
(%i7) set (aa, 17, 29, bb);
(%o7)                   {17, 29, aa, bb}
(%i8) grind (%);
{17,29,aa,bb}$
(%o8)                         done
(%i9) exp (aa / (bb + 17)^29);
                                aa
                            -----------
                                     29
                            (bb + 17)
(%o9)                     %e
(%i10) grind (%);
%e^(aa/(bb+17)^29)$
(%o10)                        done
(%i11) expr: expand ((aa + bb)^10);
         10           9        2   8         3   7         4   6
(%o11) bb   + 10 aa bb  + 45 aa  bb  + 120 aa  bb  + 210 aa  bb
         5   5         6   4         7   3        8   2
 + 252 aa  bb  + 210 aa  bb  + 120 aa  bb  + 45 aa  bb
        9        10
 + 10 aa  bb + aa
(%i12) grind (expr);
bb^10+10*aa*bb^9+45*aa^2*bb^8+120*aa^3*bb^7+210*aa^4*bb^6
     +252*aa^5*bb^5+210*aa^6*bb^4+120*aa^7*bb^3+45*aa^8*bb^2
     +10*aa^9*bb+aa^10$
(%o12)                        done
(%i13) string (expr);
(%o13) bb^10+10*aa*bb^9+45*aa^2*bb^8+120*aa^3*bb^7+210*aa^4*bb^6\
+252*aa^5*bb^5+210*aa^6*bb^4+120*aa^7*bb^3+45*aa^8*bb^2+10*aa^9*\
bb+aa^10
(%i14) cholesky (A):= block ([n : length (A), L : copymatrix (A),
  p : makelist (0, i, 1, length (A))], for i thru n do
  for j : i thru n do
  (x : L[i, j], x : x - sum (L[j, k] * L[i, k], k, 1, i - 1),
  if i = j then p[i] : 1 / sqrt(x) else L[j, i] : x * p[i]),
  for i thru n do L[i, i] : 1 / p[i],
  for i thru n do for j : i + 1 thru n do L[i, j] : 0, L)$
(%i15) grind (cholesky);
cholesky(A):=block(
         [n:length(A),L:copymatrix(A),
          p:makelist(0,i,1,length(A))],
         for i thru n do
             (for j from i thru n do
                  (x:L[i,j],x:x-sum(L[j,k]*L[i,k],k,1,i-1),
                   if i = j then p[i]:1/sqrt(x)
                       else L[j,i]:x*p[i])),
         for i thru n do L[i,i]:1/p[i],
         for i thru n do (for j from i+1 thru n do L[i,j]:0),L)$
(%o15)                        done
(%i16) string (fundef (cholesky));
(%o16) cholesky(A):=block([n:length(A),L:copymatrix(A),p:makelis\
t(0,i,1,length(A))],for i thru n do (for j from i thru n do (x:L\
[i,j],x:x-sum(L[j,k]*L[i,k],k,1,i-1),if i = j then p[i]:1/sqrt(x\
) else L[j,i]:x*p[i])),for i thru n do L[i,i]:1/p[i],for i thru \
n do (for j from i+1 thru n do L[i,j]:0),L)
Управляющая переменная: ibase

Значение по умолчанию: 10

Целые вводимые в Maxima распознаются с учетом основания системы счисления ibase.

Переменной ibase может быть присвоено значение между 2 и 35 (в десятичной), включительно. Когда ibase больше чем 10, в состав цифр входят десятичные цифры от 0 до 9 и заглавные буквы алфавита A, B, C, ..., по мере необходимости.

Цифры для основания 35, наибольшего возможного, включают цифры от 0 до 9 и буквы от A до Z.

См. также obase.

Управляющая переменная: inchar

Значение по умолчанию: %i

inchar – префикс перед метками выражений, вводимых пользователем. Maxima автоматически генерирует ссылку для каждого входного выражения, соединяя inchar и linenum. Переменной inchar может быть присвоена любая строка или обозначение, не обязательно состоящее из одной буквы.

(%i1) inchar: "input";
(%o1)                                input
(input1) expand ((a+b)^3);
                            3        2      2      3
(%o1)                      b  + 3 a b  + 3 a  b + a
(input2)

См. также labels.

Функция: ldisp (expr_1, ..., expr_n)

Отображает выражения expr_1, ..., expr_n в консоли как в печатном выводе. ldisp присваивает метки промежуточных выражений для каждого аргумента и возвращает список меток.

См. также disp.

(%i1) e: (a+b)^3;
                                   3
(%o1)                       (b + a)
(%i2) f: expand (e);
                     3        2      2      3
(%o2)               b  + 3 a b  + 3 a  b + a
(%i3) ldisp (e, f);
                                   3
(%t3)                       (b + a)

                     3        2      2      3
(%t4)               b  + 3 a b  + 3 a  b + a

(%o4)                      [%t3, %t4]
(%i4) %t3;
                                   3
(%o4)                       (b + a)
(%i5) %t4;
                     3        2      2      3
(%o5)               b  + 3 a b  + 3 a  b + a
Функция: ldisplay (expr_1, ..., expr_n)

Отображает выражения expr_1, ..., expr_n в консоли как при выводе. Каждое выражение печатается в виде равенства lhs = rhs, в котором lhs – один из аргументов функции ldisplay, а rhs – его значение. Обычно каждый аргумент – переменная. ldisp присваивает метки промежуточных выражений каждому равенству и возвращает список меток.

См. также display.

(%i1) e: (a+b)^3;
                                   3
(%o1)                       (b + a)
(%i2) f: expand (e);
                     3        2      2      3
(%o2)               b  + 3 a b  + 3 a  b + a
(%i3) ldisplay (e, f);
                                     3
(%t3)                     e = (b + a)

                       3        2      2      3
(%t4)             f = b  + 3 a b  + 3 a  b + a

(%o4)                      [%t3, %t4]
(%i4) %t3;
                                     3
(%o4)                     e = (b + a)
(%i5) %t4;
                       3        2      2      3
(%o5)             f = b  + 3 a b  + 3 a  b + a
Управляющая переменная: linechar

Значение по умолчанию: %t

linechar – префикс меток промежуточных выражений, генерируемых Maxima. Maxima генерирует метки для каждого промежуточного выражения (если оно отображается), соединяя linechar и linenum. Переменной linechar может быть присвоена любая строка или символ, не обязательно одиночная буква.

Промежуточный выражения могут отображаться, а могут и не отображаться. См. programmode и labels.

Управляющая переменная: linel

Значение по умолчанию: 79

linel – ширина консоли (в символах) для вывода выражений. Пользователь может задать любое значение linel, хотя очень маленькие или очень большие значения могут оказаться неудобными. Текст выводимый встроенными функциями Maxima, такой как сообщения об ошибках и вывод describe, не зависит от linel.

Управляющая переменная: lispdisp

Значение по умолчанию: false

Когда lispdisp равна true, Lisp символы отображаются с вопросительным знаком ? перед ними. В противном случае Lisp символы отображаются без знака.

Примеры:

(%i1) lispdisp: false$
(%i2) ?foo + ?bar;
(%o2)                       foo + bar
(%i3) lispdisp: true$
(%i4) ?foo + ?bar;
(%o4)                      ?foo + ?bar
Функция: load (filename)

Вычисляет выражения в filename, тем самым загружая переменные, функции и другие объекты в Maxima. Значения любых существовавших объектов заменяются связями, полученными из filename. Для поиска файла load вызывает file_search, пути поиска берутся из file_search_maxima и file_search_lisp. Если load выполнена успешно, то возвращается имя файла, иначе печатается сообщение об ошибке.

load работает с равным успехом как для Lisp, так и для Maxima программ. Файлы, созданные командами save, translate_file и compile_file, которые создают код Lisp, и stringout, которая создает код Maxima, могут быть обработаны функцией load. load вызывает loadfile для загрузки Lisp файлов и batchload для загрузки Maxima файлов.

load не распознает конструкции :lisp в файлах Maxima, и во время обработки filename, глобальные переменные _, __, % и %th имеют те связи, которые были у них в момент вызова load.

См. также loadfile, batch, batchload и demo. batch, batchload и demo выполняют Maxima файлы.

См. file_search для более подробного ознакомления с механизмом поиска файлов.

load вычисляет свой аргумент.

Функция: loadfile (filename)

Вычисляет выражения Lisp в filename. loadfile не вызывает file_search, поэтому filename должен включать расширение и информацию о пути, достаточную для поиска файла.

loadfile может обрабатывать файлы, созданные командами save, translate_file и compile_file. Возможно, удобнее использовать load вместо loadfile.

Управляющая переменная: loadprint

Значение по умолчанию: true

loadprint управляет печатью сообщение после загрузки файла.

Управляющая переменная: obase

Значение по умолчанию: 10

obase – основание системы счисления в которой Maxima отображает целые числа.

Переменной obase можно присвоить любое целое число между 2 и 35 (десятичное), включительно. Когда obase больше десяти, цифрами являются десятичные цифры от 0 до 9 и заглавные буквы латинского алфавита A, B, C, ..., по мере необходимости. Цифры системы с основанием 35, самым большим из допустимых, включают цифры от 0 до 9 и буквы от A до Y.

См. также ibase.

Управляющая переменная: outchar

Значение по умолчанию: %o

outchar – это префикс меток для выражений, вычисленных системой Maxima. Maxima автоматически генерирует метки для каждого вычисленного выражения, соединяя outchar с linenum. Переменной outchar можно присвоить любую строку или символ, не обязательно одиночную букву.

(%i1) outchar: "output";
(output1)                           output
(%i2) expand ((a+b)^3);
                            3        2      2      3
(output2)                  b  + 3 a b  + 3 a  b + a
(%i3)

См. также labels.

Управляющая переменная: packagefile

Значение по умолчанию: false

Разработчики, которые используют save или translate, создавая пакеты (файлы) для использования другими, возможно захотят установить packagefile: true, чтобы при загрузке файла предотвратить занесение информации, кроме необходимой, в списки Maxima (такие как values, functions). В этом случае содержимое пакета будет загружено не в виде пользовательских данных. Заметим, что это не решает проблему возможного конфликта имен. Также заметим, что переменная просто указывает на то, что выводится в пакетный файл. Установка управляющей переменной в true также полезна для создания инициализационных файлов Maxima.

Управляющая переменная: pfeformat

Значение по умолчанию: false

Когда pfeformat равна true, рациональная дробь отображается при помощи косой черты (прямого слэша). Целочисленный знаменатель n отображается как множитель 1/n.

(%i1) pfeformat: false$
(%i2) 2^16/7^3;
                              65536
(%o2)                         -----
                               343
(%i3) (a+b)/8;
                              b + a
(%o3)                         -----
                                8
(%i4) pfeformat: true$ 
(%i5) 2^16/7^3;
(%o5)                       65536/343
(%i6) (a+b)/8;
(%o6)                      1/8 (b + a)
Функция: print (expr_1, ..., expr_n)

Вычисляет и отображает expr_1, ..., expr_n одно за другим, слева направо, начиная с левого края экрана консоли.

Функция print возвращает значение своего последнего аргумента. print не создает меток промежуточных выражений.

См. также display, disp, ldisplay и ldisp. Эти функции отображают по одному выражению на строку, в то время как print старается отобразить по два или больше выражений в каждой строке.

Чтобы отобразить содержимое файла, см. printfile.

(%i1) r: print ("(a+b)^3 is", expand ((a+b)^3), "log (a^10/b) is",
      radcan (log (a^10/b)))$
            3        2      2      3
(a+b)^3 is b  + 3 a b  + 3 a  b + a  log (a^10/b) is 

                                              10 log(a) - log(b) 
(%i2) r;
(%o2)                  10 log(a) - log(b)
(%i3) disp ("(a+b)^3 is", expand ((a+b)^3), "log (a^10/b) is",
      radcan (log (a^10/b)))$
                           (a+b)^3 is

                     3        2      2      3
                    b  + 3 a b  + 3 a  b + a

                         log (a^10/b) is

                       10 log(a) - log(b)
Функция: printfile (path)

Выводит файл с именем path на консоль. Значение path может быть строкой или символом. Если символ, то он преобразуется в строку.

Если файл с именем path доступен в текущей директории, то он печатается на консоли. В противном случае printfile пытается найти файл добавляя path ко всем элементам file_search_usage при помощи filename_merge.

printfile возвращает path, если файл существует, и результат успешного поиска файла.

Функция: tcl_output (list, i0, skip)
Функция: tcl_output (list, i0)
Функция: tcl_output ([list_1, ..., list_n], i)

Выводит элементы списков заключенными в фигурные скобки { }, в виде пригодном для использования в языке Tcl/Tk.

tcl_output (list, i0, skip) выводит элементы списка list с номерами i0, i0 + skip, i0 + 2 skip и так далее.

tcl_output (list, i0) равнозначна tcl_output (list, i0, 2).

tcl_output ([list_1, ..., list_n], i) выводит i-ые элементы списков list_1, ..., list_n.

Примеры:

(%i1) tcl_output ([1, 2, 3, 4, 5, 6], 1, 3)$

 {1.000000000     4.000000000     
 }
(%i2) tcl_output ([1, 2, 3, 4, 5, 6], 2, 3)$

 {2.000000000     5.000000000     
 }
(%i3) tcl_output ([3/7, 5/9, 11/13, 13/17], 1)$

 {((RAT SIMP) 3 7) ((RAT SIMP) 11 13) 
 }
(%i4) tcl_output ([x1, y1, x2, y2, x3, y3], 2)$

 {$Y1 $Y2 $Y3 
 }
(%i5) tcl_output ([[1, 2, 3], [11, 22, 33]], 1)$

 {SIMP 1.000000000     11.00000000     
 }
Функция: read (expr_1, ..., expr_n)

Выводит expr_1, ..., expr_n, затем считывает одно выражение с консоли и возвращает вычисленное выражение.

См. также readonly.

(%i1) foo: 42$ 
(%i2) foo: read ("foo is", foo, " -- enter new value.")$
foo is 42  -- enter new value. 
(a+b)^3;
(%i3) foo;
                                     3
(%o3)                         (b + a)
Функция: readonly (expr_1, ..., expr_n)

Выводит expr_1, ..., expr_n, затем считывает одно выражение с консоли и Возвращает его без вычисления.

(%i1) aa: 7$
(%i2) foo: readonly ("Enter an expression:");
Enter an expression: 
2^aa;
                                  aa
(%o2)                            2
(%i3) foo: read ("Enter an expression:");
Enter an expression: 
2^aa;
(%o3)                            128

См. также read.

Функция: reveal (expr, depth)

Замещает части выражения expr заданного уровня вложенности depth кратким описанием.

Если depth больше или равен максимальному уровню вложенности в выражении expr, то reveal (expr, depth) возвращает expr без изменений.

reveal вычисляет свои аргументы. reveal возвращает анализируемое выражение.

Пример:

(%i1) e: expand ((a - b)^2)/expand ((exp(a) + exp(b))^2);
                          2            2
                         b  - 2 a b + a
(%o1)               -------------------------
                        b + a     2 b     2 a
                    2 %e      + %e    + %e
(%i2) reveal (e, 1);
(%o2)                       Quotient
(%i3) reveal (e, 2);
                             Sum(3)
(%o3)                        ------
                             Sum(3)
(%i4) reveal (e, 3);
                     Expt + Negterm + Expt
(%o4)               ------------------------
                    Product(2) + Expt + Expt
(%i5) reveal (e, 4);
                       2                 2
                      b  - Product(3) + a
(%o5)         ------------------------------------
                         Product(2)     Product(2)
              2 Expt + %e           + %e
(%i6) reveal (e, 5);
                         2            2
                        b  - 2 a b + a
(%o6)              --------------------------
                       Sum(2)     2 b     2 a
                   2 %e       + %e    + %e
(%i7) reveal (e, 6);
                          2            2
                         b  - 2 a b + a
(%o7)               -------------------------
                        b + a     2 b     2 a
                    2 %e      + %e    + %e
Управляющая переменная: rmxchar

Значение по умолчанию: ]

Правая сторона матриц изображается символами rmxchar.

См. также lmxchar.

Функция: save (filename, name_1, name_2, name_3, ...)
Функция: save (filename, values, functions, labels, ...)
Функция: save (filename, [m, n])
Функция: save (filename, name_1=expr_1, ...)
Функция: save (filename, all)
Функция: save (filename, name_1=expr_1, name_2=expr_2, ...)

Сохраняет текущие значения аргументов name_1, name_2, name_3, ..., в filename. Аргументами являются имена переменных, функций и прочих объектов. Если имя не имеет значения или связанной с ним функцией, оно игнорируется. save возвращает filename.

save сохраняет данные в форме Lisp выражений. Данные, сохраненные функцией save, можно загрузить при помощи load (filename).

Глобальная управляющая переменная file_output_append управляет тем, будет ли информация добавлена к файлу, или файл будет переписан заново. Когда file_output_append равен true, происходит добавление, иначе save переписывает файл вывода. В обоих случаях save создает файл, если он до этого не существовал.

Особая форма save (filename, values, functions, labels, ...) сохраняет элементы перечисленные в списках values, functions, labels и т. д. Возможны любые имена определенные в infolist. values включает все определенные пользователем переменные.

Особая форма save (filename, [m, n]) сохраняет значения входных и результирующих выражений с номерами от m до n. Заметим, что m и n должны быть буквальными целыми. Входные и результирующие метки можно также записать одну за другой, например, save ("foo.1", %i42, %o42). save (filename, labels) сохраняет все входные и результирующие выражения. Сохраненные выражения при загрузке заменяют существующие.

Особая форма save (filename, name_1=expr_1, name_2=expr_2, ...) сохраняет значения expr_1, expr_2, ... с именами name_1, name_2, ... Эту форму полезно применять для входных и результирующих меток, например, save ("foo.1", aa=%o88). С правой стороны равенства в этой форме может стоять любое выражение, которое вычисляется. Эта форма не вводит новые имена в текущий сеанс Maxima, только сохраняет их в filename.

Эти особые формы и общую форму функции save можно как угодно смешивать. Например: save (filename, aa, bb, cc=42, functions, [11, 17]).

Особая форма save (filename, all) сохраняет текущее состояние Maxima, включая все определенные пользователем переменные, функции, массивы и т. д., а также элементы, заданные автоматически. Сохраняемые элементы включают в себя системные переменные, такие как file_search_maxima или showtime, если пользователь присвоил им новые значения. См. myoptions.

save вычисляет filename, все остальные аргументы не вычисляются.

Управляющая переменная: savedef

Значение по умолчанию: true

Когда savedef равно true, Maxima версия определенной пользователем функции защищается, при ее трансляции. Это позволяет отобразить ее определение при помощи dispfun и дает возможность редактировать ее.

Когда savedef равна false, имена транслируемых функций удаляются из списка functions.

Функция: show (expr)

При отображении expr, у индексированных объектов ковариантные индексы показываются как нижние, а контравариантные – как верхние. Индексы дифференцирования отображаются нижними и отделяются от ковариантных запятой.

Функция: showratvars (expr)

Возвращает список переменных в каноническом рациональном выражении expr.

См. также ratvars.

Управляющая переменная: stardisp

Значение по умолчанию: false

Когда stardisp равно true, произведение отображается со звездочкой между операндами.

Функция: string (expr)

Преобразовывает expr в линейное представление, как оно было бы введено с клавиатуры.

Значение, возвращаемое функцией string, является строкой, поэтому не может использоваться в вычислениях.

Управляющая переменная: stringdisp

Значение по умолчанию: false

Когда stringdisp равна true, строки отображаются заключенными в двойные кавычки. В противном случае кавычки опускаются.

stringdisp всегда true, при выводе определений функций.

Примеры:

(%i1) stringdisp: false$
(%i2) "This is an example string.";
(%o2)              This is an example string.
(%i3) foo () :=
      print ("This is a string in a function definition.");
(%o3) foo() := 
              print("This is a string in a function definition.")
(%i4) stringdisp: true$
(%i5) "This is an example string.";
(%o5)             "This is an example string."
Функция: stringout (filename, expr_1, expr_2, expr_3, ...)
Функция: stringout (filename, [m, n])
Функция: stringout (filename, input)
Функция: stringout (filename, functions)
Функция: stringout (filename, values)

stringout записывает выражение в файл в той же форме, в которой оно было бы введено с клавиатуры. Файл можно использовать в качестве входного для команд batch или demo, его также можно редактировать для любых целей. stringout можно выполнять во время работы writefile.

Глобальная переменная file_output_append определяет будет ли stringout добавлять или переписывать выходной файл. Если file_output_append равна true, stringout дописывает выходной файл, иначе переписывает его. В обоих случаях stringout создает файл, если тот не существовал.

Общий вид команды stringout записывает значения одного или нескольких выражений в файл. Заметим, что если выражения являются переменной, записывается только значение переменной, но не ее имя. В полезном специальном случае, выражения могут быть метками входных (%i1, %i2, %i3, ...) или результирующих (%o1, %o2, %o3, ...) выражений.

Если grind равна true, stringout форматирует выход используя формат grind. Иначе используется формат string. См. grind и string.

Особая форма stringout (filename, [m, n) записывает значения входных выражений, с номерами от m до n, включительно.

Особая форма stringout (filename, input) записывает в файл все входные выражения.

Особая форма stringout (filename, functions) записывает в файл все пользовательские функции (перечисленные в глобальном списке functions).

Особая форма stringout (filename, values) записывает в файл все пользовательские переменные (перечисленные в глобальном списке values). Каждая переменная выводится как оператор присваивания: с именем переменной, двоеточием и ее значением. Заметим, что общая форма stringout не выводит переменные в виде операторов присваивания.

Функция: tex (expr)
Функция: tex (expr, filename)
Функция: tex (expr, false)
Функция: tex (label)
Функция: tex (label, filename)
Функция: tex (label, false)

Отображает выражение в представлении подходящим для системы подготовки документов TeX. Результат – фрагмент документа, который можно скопировать в больший документ, но сам по себе он для обработки не подходит.

tex (expr) отображает TeX-представление выражения expr в консоль.

(label) отображает TeX-представление выражения, помеченное label, и назначает его метке выражения (отображаемой слева от выражения). Метки выражений TeX совпадают с метками Maxima.

tex (expr, filename) и tex (label, filename) добавляют свой TeX-вывод в файл filename.

tex (expr, false) и tex (label, false) возвращают свой вывод в виде строки.

tex вычисляет свой первый аргумент после попытки определить, не является ли он меткой. Оператор две кавычки '' вызывает вычисление аргумента, предотвращая попытки проверить, является ли он меткой.

См. также texput.

Примеры:

(%i1) integrate (1/(1+x^3), x);
                                    2 x - 1
                  2            atan(-------)
             log(x  - x + 1)        sqrt(3)    log(x + 1)
(%o1)      - --------------- + ------------- + ----------
                    6             sqrt(3)          3
(%i2) tex (%o1);
$$-{{\log \left(x^2-x+1\right)}\over{6}}+{{\arctan \left({{2\,x-1
 }\over{\sqrt{3}}}\right)}\over{\sqrt{3}}}+{{\log \left(x+1\right)
 }\over{3}}\leqno{\tt (\%o1)}$$
(%o2)                          (\%o1)
(%i3) tex (integrate (sin(x), x));
$$-\cos x$$
(%o3)                           false
(%i4) tex (%o1, "foo.tex");
(%o4)                          (\%o1)

tex (expr, false) возвращает свой вывод в виде строки.

(%i1) S : tex (x * y * z, false);
(%o1) $$x\,y\,z$$
(%i2) S;
(%o2) $$x\,y\,z$$
Функция: texput (a, s)
Функция: texput (a, s, operator_type)
Функция: texput (a, [s_1, s_2], matchfix)
Функция: texput (a, [s_1, s_2, s_3], matchfix)

Задает TeX вывод для атома a, который может быть символом или именем оператора.

texput (a, s) заставляет функцию tex в своем выводе вставлять строку s вместо a.

texput (a, s, operator_type), где operator_type можеть принимать значения prefix, infix, postfix, nary или nofix, заставляет функцию tex вставлять s вместо a и помещать вставленный текст в подходящую позицию.

texput (a, [s_1, s_2], matchfix) заставляет tex вставлять s_1 и s_2 в вывод TeX с обоих сторон аргументов атома a. Аргументы (если их несколько) разделяются запятыми.

textpput (a, [s_1, s_2, s_3], matchfix) заставляет tex в TeX-выводе вставлять s_1 и s_2 с обоих сторон аргументов атома a и разделять их аргументом s_3.

Примеры:

Определение TeX вывода переменной.

(%i1) texput (me,"\\mu_e");
(%o1)                         \mu_e
(%i2) tex (me);
$$\mu_e$$
(%o2)                         false

Определение TeX вывода обычной функции (не оператору).

(%i1) texput (lcm, "\\mathrm{lcm}");
(%o1)                     \mathrm{lcm}
(%i2) tex (lcm (a, b));
$$\mathrm{lcm}\left(a , b\right)$$
(%o2)                         false

Определение TeX вывода префиксного оператора.

(%i1) prefix ("grad");
(%o1)                         grad
(%i2) texput ("grad", " \\nabla ", prefix);
(%o2)                        \nabla 
(%i3) tex (grad f);
$$ \nabla f$$
(%o3)                         false

Определение вывода инфиксного оператора.

(%i1) infix ("~");
(%o1)                           ~
(%i2) texput ("~", " \\times ", infix);
(%o2)                        \times 
(%i3) tex (a ~ b);
$$a \times b$$
(%o3)                         false

Определение вывода постфиксного оператора.

(%i1) postfix ("##");
(%o1)                          ##
(%i2) texput ("##", "!!", postfix);
(%o2)                          !!
(%i3) tex (x ##);
$$x!!$$
(%o3)                         false

Определение вывода n-арного оператора.

(%i1) nary ("@@");
(%o1)                          @@
(%i2) texput ("@@", " \\circ ", nary);
(%o2)                         \circ 
(%i3) tex (a @@ b @@ c @@ d);
$$a \circ b \circ c \circ d$$
(%o3)                         false

Определение TeX вывода безфиксного оператора без аргументов.

(%i1) nofix ("foo");
(%o1)                          foo
(%i2) texput ("foo", "\\mathsc{foo}", nofix);
(%o2)                     \mathsc{foo}
(%i3) tex (foo);
$$\mathsc{foo}$$
(%o3)                         false

Назначение вывода матчфиксному парному оператору.

(%i1) matchfix ("<<", ">>");
(%o1)                          <<
(%i2) texput ("<<", [" \\langle ", " \\rangle "], matchfix);
(%o2)                [ \langle ,  \rangle ]
(%i3) tex (<<a>>);
$$ \langle a \rangle $$
(%o3)                         false
(%i4) tex (<<a, b>>);
$$ \langle a , b \rangle $$
(%o4)                         false
(%i5) texput ("<<", [" \\langle ", " \\rangle ", " \\, | \\,"],
      matchfix);
(%o5)           [ \langle ,  \rangle ,  \, | \,]
(%i6) tex (<<a>>);
$$ \langle a \rangle $$
(%o6)                         false
(%i7) tex (<<a, b>>);
$$ \langle a \, | \,b \rangle $$
(%o7)                         false
Функция: system (command)

Выполняет команду command как отдельный процесс. Команда отправляется на выполнение командной оболочке, заданной по умолчанию. system поддерживается не всеми операционными системами, она в основном существует в Unix и Unix-подобных окружениях.

Предположим, что _hist.out – список частот, который вы хотите изобразить в виде гистограммы при помощи программы xgraph.

(%i1) (with_stdout("_hist.out",
           for i:1 thru length(hist) do (
             print(i,hist[i]))),
       system("xgraph -bar -brw .7 -nl < _hist.out"));

Для того чтобы создать готовый график в фоновом режиме (вернуться к управлению Maxima) и удалить временный файл после завершения, сделайте так:

system("(xgraph -bar -brw .7 -nl < _hist.out;  rm -f _hist.out)&")
Управляющая переменная: ttyoff

Значение по умолчанию: false

Когда ttyoff равна true, выводимые выражения не отображаются. Выводимые выражения по прежнему вычисляются и связываются с метками. См. labels.

ttyoff не влияет на текст, отображаемый встроенными функциями, такой как сообщения об ошибках и вывод describe.

Функция: with_stdout (f, expr_1, expr_2, expr_3, ...)
Функция: with_stdout (s, expr_1, expr_2, expr_3, ...)

Вычисляет expr_1, expr_2, expr_3, ... и записывает любой сгенерированный вывод в файл f или в выходной поток s. Вычисленные выражения не записываются в вывод. Вывод может генерироваться кроме прочих функциями print, display, grind.

Глобальная переменная file_output_append управляет тем, будет ли with_stdout дописывать или переписывать заново файл f. Если file_output_append равна true, with_stdout добавляет вывод к файлу. Иначе with_stdout переписывает файл. В обоих случаях, with_stdout создает файл, если тот не существовал.

with_stdout возвращает значение своего последнего аргумента.

См. также writefile.

(%i1) with_stdout ("tmp.out", for i:5 thru 10 do
      print (i, "! yields", i!))$
(%i2) printfile ("tmp.out")$
5 ! yields 120 
6 ! yields 720 
7 ! yields 5040 
8 ! yields 40320 
9 ! yields 362880 
10 ! yields 3628800
Функция: writefile (filename)

Начинает записывать копию сессии Maxima в filename. Все взаимодействия между пользователем и Maxima записываются в этот файл точно в том виде, в котором они показываются в консоли.

Копия печатается в формате консольного вывода, который не может быть перезагружен в Maxima. Если хотите создать файл, содержащий выражения, с возможностью его загрузки, см. save и stringout. save сохраняет выражения в форме Lisp, в то время как stringout сохраняет их в форме Maxima.

Результат выполнения writefile, когда filename уже существует, зависит от реализации лежащего в основе Lisp. Выходной файл может быть стерт или дописан. appendfile всегда дописывает файл.

Может оказаться удобным выполнить playback после writefile чтобы сохранить отображение предыдущих взаимодействий. Так playback отображает только входные или результирующие переменные (%i1, %o1 и т. д.), любой вывод, создаваемый печатающими выражениями в функциях (в противоположность возвращаемому значению), не отображается функцией playback.

closefile закрывает файл, который открыла writefile или appendfile.


Next: , Previous: Ввод и вывод, Up: Top   [Contents][Index]

10 Контексты


Previous: Контексты, Up: Контексты   [Contents][Index]

10.1 Функции для работы с контекстами

Функция: activate (context_1, ..., context_n)

Активизирует контексты context_1, ..., context_n. Факты в этих контекстах становятся доступными для процедур дедукции. Факты в данных контекстах не отображаются функцией facts ().

Переменная activecontexts содержит список активных контекстов, активированных с помощью activate.

Системная переменная: activecontexts

Значение по умолчанию: []

activecontexts – список активных контекстов, активизированных при помощи функции activate, в отличии от контекстов, которые являются активными как подконтексты текущего контекста.

Функция: assume (pred_1, ..., pred_n)

Добавляет предикаты pred_1, ..., pred_n к текущему контексту. Если предикаты являются противоречивыми или избыточными в текущем контексте, то добавление не производится. Контекст объединяет все предикаты от всех вызовов assume.

assume возвращает список предикатов, добавленных к базе данных и атомы redundant или inconsistent для избыточных или противоречивых предикатов соответственно.

Предикаты pred_1, ..., pred_n могут быть только выражениями, содержащими операторы отношения < <= equal notequal >= и >. Предикаты не могут быть буквальными равенствами = или неравенствами # выражений, и не могут включать функции-предикаты integerp.

Распознаются составные предикаты вида pred_1 and ... and pred_n, но не предикаты pred_1 or ... or pred_n. Распознается not pred_k, если pred_k является предикатом отношения. Выражения вида not (pred_1 and pred_2) и not (pred_1 or pred_2) не распознаются.

Механизм дедукции Maxima не очень силен. Существует много очевидных следствий, которые не могут быть выведены is. Это известная слабость.

assume вычисляет свои аргументы.

См. также is, facts, forget, context и declare.

Примеры:

(%i1) assume (xx > 0, yy < -1, zz >= 0);
(%o1)              [xx > 0, yy < - 1, zz >= 0]
(%i2) assume (aa < bb and bb < cc);
(%o2)                  [bb > aa, cc > bb]
(%i3) facts ();
(%o3)     [xx > 0, - 1 > yy, zz >= 0, bb > aa, cc > bb]
(%i4) is (xx > yy);
(%o4)                         true
(%i5) is (yy < -yy);
(%o5)                         true
(%i6) is (sinh (bb - aa) > 0);
(%o6)                         true
(%i7) forget (bb > aa);
(%o7)                       [bb > aa]
(%i8) prederror : false;
(%o8)                         false
(%i9) is (sinh (bb - aa) > 0);
(%o9)                        unknown
(%i10) is (bb^2 < cc^2);
(%o10)                       unknown
Управляющая переменная: assumescalar

Значение по умолчанию: true

assumescalar определяет, что выражения expr, для которых nonscalarp (expr) равно false, рассматриваются как скаляры при некоторых преобразованиях.

Пусть expr есть выражение отличное от списка или матрицы, и [1, 2, 3] есть список (или матрица). Тогда expr . [1, 2, 3] дает [expr, 2 expr, 3 expr] если assumescalar равно true, или scalarp (expr) равно true, или constantp (expr) равно true.

Если assumescalar равно true, такие выражения трактуются как скаляры только для коммутативных операций, но не для некоммутативного умножения ..

Когда assumescalar равно false, такие выражения трактуются как не-скалярные.

Когда assumescalar равно all, такие выражения трактуются как скаляры для всех перечисленных выше операций, включая некоммутативное умножение.

Управляющая переменная: assume_pos

Значение по умолчанию: false

Если assume_pos равно true и знак параметра x не может быть определен исходя из текущего контекста или другим способом, тогда sign и asksign (x) дают true. Таким образом подавить некоторые автоматические запросы asksign, возникающие при работе integrate или других вычислениях.

По умолчанию параметр x таков, что symbolp (x) или subvarp (x) истинны. Класс выражений, которые могут рассматриваться в качестве параметров, может в некоторой степени изменяться с помощью переменной assume_pos_pred.

sign и asksign пытаются определить знак выражения исходя из знаков операндов. Например, если a и b оба положительны, тогда a + b тоже положительно.

Однако, невозможно совсем обойтись без интерактивных запросов asksign. В частности, когда аргумент asksign является разницей x - y или логарифмом log(x), тогда asksign всегда запросит пользователя о знаке параметра, даже если assume_pos равно true и assume_pos_pred есть функция, возвращающая true для всех аргументов.

Управляющая переменная: assume_pos_pred

Значение по умолчанию: false

Если assume_pos_pred присвоено значение, являющееся именем функции или лямбда-выражение с одним аргументом x, тогда эта функция вызывается для того чтобы определить является ли x параметрам для assume_pos. assume_pos_pred игнорируется, когда assume_pos равно false.

Функция assume_pos_pred вызывается sign и asksign с аргументом x, который является либо атомом, либо переменной с индексом, либо вызовом функции. Если assume_pos_pred возвращает true, тогда x рассматривается как допустимый параметр для assume_pos.

По умолчанию параметром является x ткой, что symbolp (x) или subvarp (x) истинно.

См. также assume и assume_pos.

Примеры:

(%i1) assume_pos: true$
(%i2) assume_pos_pred: symbolp$
(%i3) sign (a);
(%o3)                          pos
(%i4) sign (a[1]);
(%o4)                          pnz
(%i5) assume_pos_pred: lambda ([x], display (x), true)$
(%i6) asksign (a);
                              x = a

(%o6)                          pos
(%i7) asksign (a[1]);
                             x = a
                                  1

(%o7)                          pos
(%i8) asksign (foo (a));
                           x = foo(a)

(%o8)                          pos
(%i9) asksign (foo (a) + bar (b));
                           x = foo(a)

                           x = bar(b)

(%o9)                          pos
(%i10) asksign (log (a));
                              x = a

Is  a - 1  positive, negative, or zero?

p;
(%o10)                         pos
(%i11) asksign (a - b);
                              x = a

                              x = b

                              x = a

                              x = b

Is  b - a  positive, negative, or zero?

p;
(%o11)                         neg
Управляющая переменная: context

Значение по умолчанию: initial

context служит для обозначения набора фактов формируемого при помощи assume и forget. assume добавляет факты к набору, обозначаемому context, а forget удаляет факты.

Присваивание context имени foo изменяет текущий контекст на foo. Если контекст с таким именем foo пока еще не существует, то он автоматически создается вызовом функции newcontext. Указанный контекст автоматически активируется.

См. contexts для общего описания механизма контекстов.

Управляющая переменная: contexts

Значение по умолчанию: [initial, global]

contexts – список существующих на данный момент контекстов, включая активный.

Механизм контекстов позволяет пользователю создавать поименованные наборы фактов (контексты). В результате можно легко активировать или деактивировать большие наборы фактов просто активируя или деактивируя соответствующие контексты.

Любой символ может быть контекстом, и факты содержащиеся в этом контексте сохраняются до тех пор пока не будут уничтожены поодиночке с помощью forget или целиком с помощью kill, уничтожающем весь контекст, которому они принадлежат.

Контексты имеют иерархическую структуру. Корневым элементом всегда является контекст global, который содержит информацию о Maxima нужную некоторым функциям. Когда мы находимся в определенном контексте, все его факты являются активными, т.е. используются в логических выводах. Аналогично активными являются все факты в подконтекстах текущего контекста.

При запуске Maxima, активным является контекст initial, подконтекстом которого является global.

См. также facts, newcontext, supcontext, killcontext, activate, deactivate, assume и forget.

Функция: deactivate (context_1, ..., context_n)

Деактивирует все указанные контексты context_1, ..., context_n.

Функция: facts (item)
Функция: facts ()

Если item является именем контекста, тогда facts (item) возвращает список содержащихся в нем фактов.

Если item не является именем контекста, тогда facts (item) возвращает список фактов известных о item в текущем контексте. Факты являющиеся активными, но принадлежащие другим контекстам не отображаются.

facts () (т.е. без аргументов) отображает все факты текущего контекста.

Декларация: features

Maxima "распознает" некоторые математические свойства (features) функций и переменных.

declare (x, foo) устанавливает свойство foo для функции или переменной x.

declare (foo, feature) объявляет новое свойство foo. Например, declare ([red, green, blue], feature) объявляет три свойства red, green и blue.

Предикат featurep (x, foo) возвращает true если x имеет свойство foo, и false в противном случае.

Информационный список features содержит все известные свойства. А именно integer, noninteger, even, odd, rational, irrational, real, imaginary, complex, analytic, increasing, decreasing, oddfun, evenfun, posfun, commutative, lassociative, rassociative, symmetric и antisymmetric, плюс свойства определенные пользователем.

features является списком математических свойств. Существует также список нематематических, системо-зависимых свойств. См. status.

Функция: forget (pred_1, ..., pred_n)
Функция: forget (L)

Удаляет предикаты установленные assume. Предикаты могут быть выражениями эквивалентными (но не обязательно идентичными) тем, которые первоначально были установлены с помощью assume.

forget (L), где L есть список предикатов, удаляет все предикаты из данного списка.

Функция: killcontext (context_1, ..., context_n)

Уничтожает контексты context_1, ..., context_n.

Если один из уничтожаемых контекстов является текущим, то в качестве нового текущего контекста выбирается первый доступный не уничтожаемый подконтекст текущего. Если первым доступным контекстом является global, тогда используется initial. Если initial тоже удаляется, то создается новый контекст initial.

killcontext отказывается удалять контекст, котрый является активным по причине того, что является подконтекстом текущего контекста или был активизирован функцией activate.

killcontext вычисляет свои аргументы. killcontext возвращает done.

Функция: newcontext (name)

Создает новый пустой контекст с именем name, имеющий контекст global в качестве своего подконтекста. Новый контекст становится текущим активным контекстом.

newcontext вычисляет свои аргумент. newcontext возвращает name.

Функция: supcontext (name, context)
Функция: supcontext (name)

Создает новый контекст с именем name, котрый имеет context в качестве подконтекста. context должен существовать.

Если context не указан, тогда подразумевается текущий контекст.


Next: , Previous: Контексты, Up: Top   [Contents][Index]

11 Polynomials


Next: , Up: Polynomials   [Contents][Index]

11.1 Introduction to Polynomials

Polynomials are stored in Maxima either in General Form or as Canonical Rational Expressions (CRE) form. The latter is a standard form, and is used internally by operations such as factor, ratsimp, and so on.

Canonical Rational Expressions constitute a kind of representation which is especially suitable for expanded polynomials and rational functions (as well as for partially factored polynomials and rational functions when ratfac is set to true). In this CRE form an ordering of variables (from most to least main) is assumed for each expression.

Polynomials are represented recursively by a list consisting of the main variable followed by a series of pairs of expressions, one for each term of the polynomial. The first member of each pair is the exponent of the main variable in that term and the second member is the coefficient of that term which could be a number or a polynomial in another variable again represented in this form. Thus the principal part of the CRE form of 3*x^2-1 is (X 2 3 0 -1) and that of 2*x*y+x-3 is (Y 1 (X 1 2) 0 (X 1 1 0 -3)) assuming y is the main variable, and is (X 1 (Y 1 2 0 1) 0 -3) assuming x is the main variable. "Main"-ness is usually determined by reverse alphabetical order.

The "variables" of a CRE expression needn’t be atomic. In fact any subexpression whose main operator is not +, -, *, / or ^ with integer power will be considered a "variable" of the expression (in CRE form) in which it occurs. For example the CRE variables of the expression x+sin(x+1)+2*sqrt(x)+1 are x, sqrt(X), and sin(x+1). If the user does not specify an ordering of variables by using the ratvars function Maxima will choose an alphabetic one.

In general, CRE’s represent rational expressions, that is, ratios of polynomials, where the numerator and denominator have no common factors, and the denominator is positive. The internal form is essentially a pair of polynomials (the numerator and denominator) preceded by the variable ordering list. If an expression to be displayed is in CRE form or if it contains any subexpressions in CRE form, the symbol /R/ will follow the line label.

See the rat function for converting an expression to CRE form.

An extended CRE form is used for the representation of Taylor series. The notion of a rational expression is extended so that the exponents of the variables can be positive or negative rational numbers rather than just positive integers and the coefficients can themselves be rational expressions as described above rather than just polynomials. These are represented internally by a recursive polynomial form which is similar to and is a generalization of CRE form, but carries additional information such as the degree of truncation. As with CRE form, the symbol /T/ follows the line label of such expressions.


Next: , Previous: Introduction to Polynomials, Up: Polynomials   [Contents][Index]

11.2 Functions and Variables for Polynomials

Option variable: algebraic

Default value: false

algebraic must be set to true in order for the simplification of algebraic integers to take effect.

Option variable: berlefact

Default value: true

When berlefact is false then the Kronecker factoring algorithm will be used otherwise the Berlekamp algorithm, which is the default, will be used.

Function: bezout (p1, p2, x)

an alternative to the resultant command. It returns a matrix. determinant of this matrix is the desired resultant.

Examples:

(%i1) bezout(a*x+b, c*x^2+d, x);
                         [ b c  - a d ]
(%o1)                    [            ]
                         [  a     b   ]
(%i2) determinant(%);
                            2      2
(%o2)                      a  d + b  c
(%i3) resultant(a*x+b, c*x^2+d, x);
                            2      2
(%o3)                      a  d + b  c
Function: bothcoef (expr, x)

Returns a list whose first member is the coefficient of x in expr (as found by ratcoef if expr is in CRE form otherwise by coeff) and whose second member is the remaining part of expr. That is, [A, B] where expr = A*x + B.

Example:

(%i1) islinear (expr, x) := block ([c],
        c: bothcoef (rat (expr, x), x),
        is (freeof (x, c) and c[1] # 0))$
(%i2) islinear ((r^2 - (x - r)^2)/x, x);
(%o2)                         true
Function: coeff
    coeff (expr, x, n)
    coeff (expr, x)

Returns the coefficient of x^n in expr, where expr is a polynomial or a monomial term in x. Other than ratcoef coeff is a strictly syntactical operation and will only find literal instances of x^n in the internal representation of expr.

coeff(expr, x^n) is equivalent to coeff(expr, x, n). coeff(expr, x, 0) returns the remainder of expr which is free of x. If omitted, n is assumed to be 1.

x may be a simple variable or a subscripted variable, or a subexpression of expr which comprises an operator and all of its arguments.

It may be possible to compute coefficients of expressions which are equivalent to expr by applying expand or factor. coeff itself does not apply expand or factor or any other function.

coeff distributes over lists, matrices, and equations.

See also ratcoef.

Examples:

coeff returns the coefficient x^n in expr.

(%i1) coeff (b^3*a^3 + b^2*a^2 + b*a + 1, a^3);
                                3
(%o1)                          b

coeff(expr, x^n) is equivalent to coeff(expr, x, n).

(%i1) coeff (c[4]*z^4 - c[3]*z^3 - c[2]*z^2 + c[1]*z, z, 3);
(%o1)                         - c
                                 3
(%i2) coeff (c[4]*z^4 - c[3]*z^3 - c[2]*z^2 + c[1]*z, z^3);
(%o2)                         - c
                                 3

coeff(expr, x, 0) returns the remainder of expr which is free of x.

(%i1) coeff (a*u + b^2*u^2 + c^3*u^3, b, 0);
                            3  3
(%o1)                      c  u  + a u

x may be a simple variable or a subscripted variable, or a subexpression of expr which comprises an operator and all of its arguments.

(%i1) coeff (h^4 - 2*%pi*h^2 + 1, h, 2);
(%o1)                        - 2 %pi
(%i2) coeff (v[1]^4 - 2*%pi*v[1]^2 + 1, v[1], 2);
(%o2)                        - 2 %pi
(%i3) coeff (sin(1+x)*sin(x) + sin(1+x)^3*sin(x)^3, sin(1+x)^3);
                                3
(%o3)                        sin (x)
(%i4) coeff ((d - a)^2*(b + c)^3 + (a + b)^4*(c - d), a + b, 4);
(%o4)                         c - d

coeff itself does not apply expand or factor or any other function.

(%i1) coeff (c*(a + b)^3, a);
(%o1)                           0
(%i2) expand (c*(a + b)^3);
                 3          2        2        3
(%o2)           b  c + 3 a b  c + 3 a  b c + a  c
(%i3) coeff (%, a);
                                2
(%o3)                        3 b  c
(%i4) coeff (b^3*c + 3*a*b^2*c + 3*a^2*b*c + a^3*c, (a + b)^3);
(%o4)                           0
(%i5) factor (b^3*c + 3*a*b^2*c + 3*a^2*b*c + a^3*c);
                                  3
(%o5)                      (b + a)  c
(%i6) coeff (%, (a + b)^3);
(%o6)                           c

coeff distributes over lists, matrices, and equations.

(%i1) coeff ([4*a, -3*a, 2*a], a);
(%o1)                      [4, - 3, 2]
(%i2) coeff (matrix ([a*x, b*x], [-c*x, -d*x]), x);
                          [  a    b  ]
(%o2)                     [          ]
                          [ - c  - d ]
(%i3) coeff (a*u - b*v = 7*u + 3*v, u);
(%o3)                         a = 7
Function: content (p_1, x_1, …, x_n)

Returns a list whose first element is the greatest common divisor of the coefficients of the terms of the polynomial p_1 in the variable x_n (this is the content) and whose second element is the polynomial p_1 divided by the content.

Examples:

(%i1) content (2*x*y + 4*x^2*y^2, y);
                                   2
(%o1)                   [2 x, 2 x y  + y]
Function: denom (expr)

Returns the denominator of the rational expression expr.

See also num

(%i1) g1:(x+2)*(x+1)/((x+3)^2);
                         (x + 1) (x + 2)
(%o1)                    ---------------
                                   2
                            (x + 3)
(%i2) denom(g1);
                                   2
(%o2)                       (x + 3)
(%i3) g2:sin(x)/10*cos(x)/y;
                          cos(x) sin(x)
(%o3)                     -------------
                              10 y
(%i4) denom(g2);
(%o4)                         10 y
Function: divide (p_1, p_2, x_1, …, x_n)

computes the quotient and remainder of the polynomial p_1 divided by the polynomial p_2, in a main polynomial variable, x_n. The other variables are as in the ratvars function. The result is a list whose first element is the quotient and whose second element is the remainder.

Examples:

(%i1) divide (x + y, x - y, x);
(%o1)                       [1, 2 y]
(%i2) divide (x + y, x - y);
(%o2)                      [- 1, 2 x]

Note that y is the main variable in the second example.

Function: eliminate ([eqn_1, …, eqn_n], [x_1, …, x_k])

Eliminates variables from equations (or expressions assumed equal to zero) by taking successive resultants. This returns a list of n - k expressions with the k variables x_1, …, x_k eliminated. First x_1 is eliminated yielding n - 1 expressions, then x_2 is eliminated, etc. If k = n then a single expression in a list is returned free of the variables x_1, …, x_k. In this case solve is called to solve the last resultant for the last variable.

Example:

(%i1) expr1: 2*x^2 + y*x + z;
                                      2
(%o1)                    z + x y + 2 x
(%i2) expr2: 3*x + 5*y - z - 1;
(%o2)                  - z + 5 y + 3 x - 1
(%i3) expr3: z^2 + x - y^2 + 5;
                          2    2
(%o3)                    z  - y  + x + 5
(%i4) eliminate ([expr3, expr2, expr1], [y, z]);
             8         7         6          5          4
(%o4) [7425 x  - 1170 x  + 1299 x  + 12076 x  + 22887 x

                                    3         2
                            - 5154 x  - 1291 x  + 7688 x + 15376]
Function: ezgcd (p_1, p_2, p_3, …)

Returns a list whose first element is the greatest common divisor of the polynomials p_1, p_2, p_3, … and whose remaining elements are the polynomials divided by the greatest common divisor. This always uses the ezgcd algorithm.

See also gcd, gcdex, gcdivide, and poly_gcd.

Examples:

The three polynomials have the greatest common divisor 2*x-3. The gcd is first calculated with the function gcd and then with the function ezgcd.

(%i1) p1 : 6*x^3-17*x^2+14*x-3;
                        3       2
(%o1)                6 x  - 17 x  + 14 x - 3
(%i2) p2 : 4*x^4-14*x^3+12*x^2+2*x-3;
                    4       3       2
(%o2)            4 x  - 14 x  + 12 x  + 2 x - 3
(%i3) p3 : -8*x^3+14*x^2-x-3;
                          3       2
(%o3)                - 8 x  + 14 x  - x - 3

(%i4) gcd(p1, gcd(p2, p3));
(%o4)                        2 x - 3

(%i5) ezgcd(p1, p2, p3);
                   2               3      2           2
(%o5) [2 x - 3, 3 x  - 4 x + 1, 2 x  - 4 x  + 1, - 4 x  + x + 1]
Option variable: facexpand

Default value: true

facexpand controls whether the irreducible factors returned by factor are in expanded (the default) or recursive (normal CRE) form.

Function: factor
    factor (expr)
    factor (expr, p)

Factors the expression expr, containing any number of variables or functions, into factors irreducible over the integers. factor (expr, p) factors expr over the field of rationals with an element adjoined whose minimum polynomial is p.

factor uses ifactors function for factoring integers.

factorflag if false suppresses the factoring of integer factors of rational expressions.

dontfactor may be set to a list of variables with respect to which factoring is not to occur. (It is initially empty). Factoring also will not take place with respect to any variables which are less important (using the variable ordering assumed for CRE form) than those on the dontfactor list.

savefactors if true causes the factors of an expression which is a product of factors to be saved by certain functions in order to speed up later factorizations of expressions containing some of the same factors.

berlefact if false then the Kronecker factoring algorithm will be used otherwise the Berlekamp algorithm, which is the default, will be used.

intfaclim if true maxima will give up factorization of integers if no factor is found after trial divisions and Pollard’s rho method. If set to false (this is the case when the user calls factor explicitly), complete factorization of the integer will be attempted. The user’s setting of intfaclim is used for internal calls to factor. Thus, intfaclim may be reset to prevent Maxima from taking an inordinately long time factoring large integers.

factor_max_degree if set to a positive integer n will prevent certain polynomials from being factored if their degree in any variable exceeds n.

See also collectterms and sqfr

Examples:

(%i1) factor (2^63 - 1);
                    2
(%o1)              7  73 127 337 92737 649657
(%i2) factor (-8*y - 4*x + z^2*(2*y + x));
(%o2)               (2 y + x) (z - 2) (z + 2)
(%i3) -1 - 2*x - x^2 + y^2 + 2*x*y^2 + x^2*y^2;
                2  2        2    2    2
(%o3)          x  y  + 2 x y  + y  - x  - 2 x - 1
(%i4) block ([dontfactor: [x]], factor (%/36/(1 + 2*y + y^2)));
                       2
                     (x  + 2 x + 1) (y - 1)
(%o4)                ----------------------
                           36 (y + 1)
(%i5) factor (1 + %e^(3*x));
                      x         2 x     x
(%o5)              (%e  + 1) (%e    - %e  + 1)
(%i6) factor (1 + x^4, a^2 - 2);
                    2              2
(%o6)             (x  - a x + 1) (x  + a x + 1)
(%i7) factor (-y^2*z^2 - x*z^2 + x^2*y^2 + x^3);
                       2
(%o7)              - (y  + x) (z - x) (z + x)
(%i8) (2 + x)/(3 + x)/(b + x)/(c + x)^2;
                             x + 2
(%o8)               ------------------------
                                           2
                    (x + 3) (x + b) (x + c)
(%i9) ratsimp (%);
                4                  3
(%o9) (x + 2)/(x  + (2 c + b + 3) x

     2                       2             2                   2
 + (c  + (2 b + 6) c + 3 b) x  + ((b + 3) c  + 6 b c) x + 3 b c )
(%i10) partfrac (%, x);
           2                   4                3
(%o10) - (c  - 4 c - b + 6)/((c  + (- 2 b - 6) c

     2              2         2                2
 + (b  + 12 b + 9) c  + (- 6 b  - 18 b) c + 9 b ) (x + c))

                 c - 2
 - ---------------------------------
     2                             2
   (c  + (- b - 3) c + 3 b) (x + c)

                         b - 2
 + -------------------------------------------------
             2             2       3      2
   ((b - 3) c  + (6 b - 2 b ) c + b  - 3 b ) (x + b)

                         1
 - ----------------------------------------------
             2
   ((b - 3) c  + (18 - 6 b) c + 9 b - 27) (x + 3)
(%i11) map ('factor, %);
              2
             c  - 4 c - b + 6                 c - 2
(%o11) - ------------------------- - ------------------------
                2        2                                  2
         (c - 3)  (c - b)  (x + c)   (c - 3) (c - b) (x + c)

                       b - 2                        1
            + ------------------------ - ------------------------
                             2                          2
              (b - 3) (c - b)  (x + b)   (b - 3) (c - 3)  (x + 3)
(%i12) ratsimp ((x^5 - 1)/(x - 1));
                       4    3    2
(%o12)                x  + x  + x  + x + 1
(%i13) subst (a, x, %);
                       4    3    2
(%o13)                a  + a  + a  + a + 1
(%i14) factor (%th(2), %);
                       2        3        3    2
(%o14)   (x - a) (x - a ) (x - a ) (x + a  + a  + a + 1)
(%i15) factor (1 + x^12);
                       4        8    4
(%o15)               (x  + 1) (x  - x  + 1)
(%i16) factor (1 + x^99);
                 2            6    3
(%o16) (x + 1) (x  - x + 1) (x  - x  + 1)

   10    9    8    7    6    5    4    3    2
 (x   - x  + x  - x  + x  - x  + x  - x  + x  - x + 1)

   20    19    17    16    14    13    11    10    9    7    6
 (x   + x   - x   - x   + x   + x   - x   - x   - x  + x  + x

    4    3            60    57    51    48    42    39    33
 - x  - x  + x + 1) (x   + x   - x   - x   + x   + x   - x

    30    27    21    18    12    9    3
 - x   - x   + x   + x   - x   - x  + x  + 1)
Option variable: factor_max_degree

Default value: 1000

When factor_max_degree is set to a positive integer n, it will prevent Maxima from attempting to factor certain polynomials whose degree in any variable exceeds n. If factor_max_degree_print_warning is true, a warning message will be printed. factor_max_degree can be used to prevent excessive memory usage and/or computation time and stack overflows. Note that "obvious" factoring of polynomials such as x^2000+x^2001 to x^2000*(x+1) will still take place. To disable this behavior, set factor_max_degree to 0.

Example:

(%i1) factor_max_degree : 100$
(%i2) factor(x^100-1);
                        2        4    3    2
(%o2) (x - 1) (x + 1) (x  + 1) (x  - x  + x  - x + 1)
   4    3    2            8    6    4    2
 (x  + x  + x  + x + 1) (x  - x  + x  - x  + 1)
   20    15    10    5        20    15    10    5
 (x   - x   + x   - x  + 1) (x   + x   + x   + x  + 1)
   40    30    20    10
 (x   - x   + x   - x   + 1)
(%i3) factor(x^101-1);
                               101
Refusing to factor polynomial x    - 1
               because its degree exceeds factor_max_degree (100)
                             101
(%o3)                       x    - 1

See also: factor_max_degree_print_warning

Option variable: factor_max_degree_print_warning

Default value: true

When factor_max_degree_print_warning is true, then Maxima will print a warning message when the factoring of a polynomial is prevented because its degree exceeds the value of factor_max_degree.

See also: factor_max_degree

Option variable: factorflag

Default value: false

When factorflag is false, suppresses the factoring of integer factors of rational expressions.

Function: factorout (expr, x_1, x_2, …)

Rearranges the sum expr into a sum of terms of the form f (x_1, x_2, …)*g where g is a product of expressions not containing any x_i and f is factored.

Note that the option variable keepfloat is ignored by factorout.

Example:

(%i1) expand (a*(x+1)*(x-1)*(u+1)^2);
             2  2          2      2      2
(%o1)     a u  x  + 2 a u x  + a x  - a u  - 2 a u - a
(%i2) factorout(%,x);
         2
(%o2) a u  (x - 1) (x + 1) + 2 a u (x - 1) (x + 1)
                                              + a (x - 1) (x + 1)
Function: factorsum (expr)

Tries to group terms in factors of expr which are sums into groups of terms such that their sum is factorable. factorsum can recover the result of expand ((x + y)^2 + (z + w)^2) but it can’t recover expand ((x + 1)^2 + (x + y)^2) because the terms have variables in common.

Example:

(%i1) expand ((x + 1)*((u + v)^2 + a*(w + z)^2));
           2      2                            2      2
(%o1) a x z  + a z  + 2 a w x z + 2 a w z + a w  x + v  x

                                     2        2    2            2
                        + 2 u v x + u  x + a w  + v  + 2 u v + u
(%i2) factorsum (%);
                                   2          2
(%o2)            (x + 1) (a (z + w)  + (v + u) )
Function: fasttimes (p_1, p_2)

Returns the product of the polynomials p_1 and p_2 by using a special algorithm for multiplication of polynomials. p_1 and p_2 should be multivariate, dense, and nearly the same size. Classical multiplication is of order n_1 n_2 where n_1 is the degree of p_1 and n_2 is the degree of p_2. fasttimes is of order max (n_1, n_2)^1.585.

Function: fullratsimp (expr)

fullratsimp repeatedly applies ratsimp followed by non-rational simplification to an expression until no further change occurs, and returns the result.

When non-rational expressions are involved, one call to ratsimp followed as is usual by non-rational ("general") simplification may not be sufficient to return a simplified result. Sometimes, more than one such call may be necessary. fullratsimp makes this process convenient.

fullratsimp (expr, x_1, ..., x_n) takes one or more arguments similar to ratsimp and rat.

Example:

(%i1) expr: (x^(a/2) + 1)^2*(x^(a/2) - 1)^2/(x^a - 1);
                       a/2     2   a/2     2
                     (x    - 1)  (x    + 1)
(%o1)                -----------------------
                              a
                             x  - 1
(%i2) ratsimp (expr);
                          2 a      a
                         x    - 2 x  + 1
(%o2)                    ---------------
                              a
                             x  - 1
(%i3) fullratsimp (expr);
                              a
(%o3)                        x  - 1
(%i4) rat (expr);
                       a/2 4       a/2 2
                     (x   )  - 2 (x   )  + 1
(%o4)/R/             -----------------------
                              a
                             x  - 1
Function: fullratsubst (new, old, expr)
    fullratsubst (old = new, expr)
    fullratsubst ([ old_1 = new_1, …, old_n = new_n ], expr)

fullratsubst applies lratsubst repeatedly until expr stops changing (or lrats_max_iter is reached). This function is useful when the replacement expression and the replaced expression have one or more variables in common.

fullratsubst accepts its arguments in the format of ratsubst or lratsubst.

Examples:

(%i2) subst ([a = b, c = d], a + c);
(%o2)                         d + b
(%i3) lratsubst ([a^2 = b, c^2 = d], (a + e)*c*(a + c));
(%o3)                (d + a c) e + a d + b c
(%i4) lratsubst (a^2 = b, a^3);
(%o4)                          a b
(%i5) ratsubst (b*a, a^2, a^3);
                               2
(%o5)                         a  b
(%i6) fullratsubst (b*a, a^2, a^3);
                                 2
(%o6)                         a b
(%i7) fullratsubst ([a^2 = b, b^2 = c, c^2 = a], a^3*b*c);
(%o7)                           b
(%i8) fullratsubst (a^2 = b*a, a^3);
                                 2
(%o8)                         a b
(%i9) fullratsubst (b*a^2, a^2, a^3), lrats_max_iter=15;
Warning: fullratsubst1(substexpr,forexpr,expr): reached maximum iterations of 15 . Increase `lrats_max_iter' to increase this limit.
                                     3  15
(%o7)                               a  b

See also lrats_max_iter and fullratsubstflag.

Option variable: fullratsubstflag

Default value: false

An option variable that is set to true in fullratsubst.

Function: gcd (p_1, p_2, x_1, …)

Returns the greatest common divisor of p_1 and p_2. The flag gcd determines which algorithm is employed. Setting gcd to ez, subres, red, or spmod selects the ezgcd, subresultant prs, reduced, or modular algorithm, respectively. If gcd false then gcd (p_1, p_2, x) always returns 1 for all x. Many functions (e.g. ratsimp, factor, etc.) cause gcd’s to be taken implicitly. For homogeneous polynomials it is recommended that gcd equal to subres be used. To take the gcd when an algebraic is present, e.g., gcd (x^2 - 2*sqrt(2)* x + 2, x - sqrt(2)), the option variable algebraic must be true and gcd must not be ez.

The gcd flag, default: spmod, if false will also prevent the greatest common divisor from being taken when expressions are converted to canonical rational expression (CRE) form. This will sometimes speed the calculation if gcds are not required.

See also ezgcd, gcdex, gcdivide, and poly_gcd.

Example:

(%i1) p1:6*x^3+19*x^2+19*x+6; 
                        3       2
(%o1)                6 x  + 19 x  + 19 x + 6
(%i2) p2:6*x^5+13*x^4+12*x^3+13*x^2+6*x;
                  5       4       3       2
(%o2)          6 x  + 13 x  + 12 x  + 13 x  + 6 x
(%i3) gcd(p1, p2);
                            2
(%o3)                    6 x  + 13 x + 6
(%i4) p1/gcd(p1, p2), ratsimp;
(%o4)                         x + 1
(%i5) p2/gcd(p1, p2), ratsimp;
                              3
(%o5)                        x  + x

ezgcd returns a list whose first element is the greatest common divisor of the polynomials p_1 and p_2, and whose remaining elements are the polynomials divided by the greatest common divisor.

(%i6) ezgcd(p1, p2);
                    2                     3
(%o6)           [6 x  + 13 x + 6, x + 1, x  + x]
Function: gcdex
    gcdex (f, g)
    gcdex (f, g, x)

Returns a list [a, b, u] where u is the greatest common divisor (gcd) of f and g, and u is equal to a f + b g. The arguments f and g should be univariate polynomials, or else polynomials in x a supplied main variable since we need to be in a principal ideal domain for this to work. The gcd means the gcd regarding f and g as univariate polynomials with coefficients being rational functions in the other variables.

gcdex implements the Euclidean algorithm, where we have a sequence of L[i]: [a[i], b[i], r[i]] which are all perpendicular to [f, g, -1] and the next one is built as if q = quotient(r[i]/r[i+1]) then L[i+2]: L[i] - q L[i+1], and it terminates at L[i+1] when the remainder r[i+2] is zero.

The arguments f and g can be integers. For this case the function `igcdex' is called by gcdex.

See also ezgcd, gcd, gcdivide, and poly_gcd.

Examples:

(%i1) gcdex (x^2 + 1, x^3 + 4);
                       2
                      x  + 4 x - 1  x + 4
(%o1)/R/           [- ------------, -----, 1]
                           17        17
(%i2) % . [x^2 + 1, x^3 + 4, -1];
(%o2)/R/                        0

Note that the gcd in the following is 1 since we work in k(y)[x], not the y+1 we would expect in k[y, x].

(%i1) gcdex (x*(y + 1), y^2 - 1, x);
                               1
(%o1)/R/                 [0, ------, 1]
                              2
                             y  - 1
Function: gcfactor (n)

Factors the Gaussian integer n over the Gaussian integers, i.e., numbers of the form a + b %i where a and b are rational integers (i.e., ordinary integers). Factors are normalized by making a and b non-negative.

Function: gfactor (expr)

Factors the polynomial expr over the Gaussian integers (that is, the integers with the imaginary unit %i adjoined). This is like factor (expr, a^2+1) where a is %i.

Example:

(%i1) gfactor (x^4 - 1);
(%o1)           (x - 1) (x + 1) (x - %i) (x + %i)
Function: gfactorsum (expr)

is similar to factorsum but applies gfactor instead of factor.

Function: hipow (expr, x)

Returns the highest explicit exponent of x in expr. x may be a variable or a general expression. If x does not appear in expr, hipow returns 0.

hipow does not consider expressions equivalent to expr. In particular, hipow does not expand expr, so hipow (expr, x) and hipow (expand (expr, x)) may yield different results.

Examples:

(%i1) hipow (y^3 * x^2 + x * y^4, x);
(%o1)                           2
(%i2) hipow ((x + y)^5, x);
(%o2)                           1
(%i3) hipow (expand ((x + y)^5), x);
(%o3)                           5
(%i4) hipow ((x + y)^5, x + y);
(%o4)                           5
(%i5) hipow (expand ((x + y)^5), x + y);
(%o5)                           0
Option variable: intfaclim

Default value: true

If true, maxima will give up factorization of integers if no factor is found after trial divisions and Pollard’s rho method and factorization will not be complete.

When intfaclim is false (this is the case when the user calls factor explicitly), complete factorization will be attempted. intfaclim is set to false when factors are computed in divisors, divsum and totient.

Internal calls to factor respect the user-specified value of intfaclim. Setting intfaclim to true may reduce the time spent factoring large integers.

Option variable: keepfloat

Default value: false

When keepfloat is true, prevents floating point numbers from being rationalized when expressions which contain them are converted to canonical rational expression (CRE) form.

Note that the function solve and those functions calling it (eigenvalues, for example) currently ignore this flag, converting floating point numbers anyway.

Examples:

(%i1) rat(x/2.0);

rat: replaced 0.5 by 1/2 = 0.5
                                x
(%o1)/R/                        -
                                2
(%i2) rat(x/2.0), keepfloat;
(%o2)/R/                      0.5 x

solve ignores keepfloat:

(%i1) solve(1.0-x,x), keepfloat;

rat: replaced 1.0 by 1/1 = 1.0
(%o1)                        [x = 1]
Function: lopow (expr, x)

Returns the lowest exponent of x which explicitly appears in expr. Thus

(%i1) lopow ((x+y)^2 + (x+y)^a, x+y);
(%o1)                       min(a, 2)
Function: lratsubst (new, old, expr)
    lratsubst (old = new, expr)
    lratsubst ([ old_1 = new_1, …, old_n = new_n ], expr)

lratsubst is analogous to subst except that it uses ratsubst to perform substitutions.

The first argument of lratsubst is an equation, a list of equations or a list of unit length whose first element is a list of equations (that is, the first argument is identical in format to that accepted by subst). The substitutions are made in the order given by the list of equations, that is, from left to right.

Examples:

(%i2) lratsubst ([a = b, c = d], a + c);
(%o2)                         d + b
(%i3) lratsubst ([a^2 = b, c^2 = d], (a + e)*c*(a + c));
(%o3)                (d + a c) e + a d + b c
(%i4) lratsubst (a^2 = b, a^3);
(%o4)                          a b
(%i5) lratsubst ([[a^2=b*a, b=c]], a^3);

                                      2
(%o5)                               a  c
(%i6) lratsubst ([[a^2=b*a, b=c],[a=b]], a^3);


                                 2
lratsubst: improper argument: [[a  = a b, b = c], [a = b]]
#0: lratsubst(listofeqns=[[a^2 = a*b,b = c],[a = b]],expr=a^3)
 -- an error. To debug this try: debugmode(true);

See also fullratsubst.

Option variable: lrats_max_iter

Default value: 100000

The upper limit on the number of iterations that fullratsubst and lratsubst may perform. It must be set to a positive integer. See the example for fullratsubst.

Option variable: modulus

Default value: false

When modulus is a positive number p, operations on canonical rational expressions (CREs, as returned by rat and related functions) are carried out modulo p, using the so-called "balanced" modulus system in which n modulo p is defined as an integer k in [-(p-1)/2, ..., 0, ..., (p-1)/2] when p is odd, or [-(p/2 - 1), ..., 0, ...., p/2] when p is even, such that a p + k equals n for some integer a.

If expr is already in canonical rational expression (CRE) form when modulus is reset, then you may need to re-rat expr, e.g., expr: rat (ratdisrep (expr)), in order to get correct results.

Typically modulus is set to a prime number. If modulus is set to a positive non-prime integer, this setting is accepted, but a warning message is displayed. Maxima signals an error, when zero or a negative integer is assigned to modulus.

Examples:

(%i1) modulus:7;
(%o1)                           7
(%i2) polymod([0,1,2,3,4,5,6,7]);
(%o2)            [0, 1, 2, 3, - 3, - 2, - 1, 0]
(%i3) modulus:false;
(%o3)                         false
(%i4) poly:x^6+x^2+1;
                            6    2
(%o4)                      x  + x  + 1
(%i5) factor(poly);
                            6    2
(%o5)                      x  + x  + 1
(%i6) modulus:13;
(%o6)                          13
(%i7) factor(poly);
                      2        4      2
(%o7)               (x  + 6) (x  - 6 x  - 2)
(%i8) polymod(%);
                            6    2
(%o8)                      x  + x  + 1
Function: num (expr)

Returns the numerator of expr if it is a ratio. If expr is not a ratio, expr is returned.

num evaluates its argument.

See also denom

(%i1) g1:(x+2)*(x+1)/((x+3)^2);
                         (x + 1) (x + 2)
(%o1)                    ---------------
                                   2
                            (x + 3)
(%i2) num(g1);
(%o2)                    (x + 1) (x + 2)
(%i3) g2:sin(x)/10*cos(x)/y;
                          cos(x) sin(x)
(%o3)                     -------------
                              10 y
(%i4) num(g2);
(%o4)                     cos(x) sin(x)
Function: polydecomp (p, x)

Decomposes the polynomial p in the variable x into the functional composition of polynomials in x. polydecomp returns a list [p_1, ..., p_n] such that

lambda ([x], p_1) (lambda ([x], p_2) (... (lambda ([x], p_n) (x))
  ...))

is equal to p. The degree of p_i is greater than 1 for i less than n.

Such a decomposition is not unique.

Examples:

(%i1) polydecomp (x^210, x);
                          7   5   3   2
(%o1)                   [x , x , x , x ]
(%i2) p : expand (subst (x^3 - x - 1, x, x^2 - a));
                6      4      3    2
(%o2)          x  - 2 x  - 2 x  + x  + 2 x - a + 1
(%i3) polydecomp (p, x);
                        2       3
(%o3)                 [x  - a, x  - x - 1]

The following function composes L = [e_1, ..., e_n] as functions in x; it is the inverse of polydecomp:

(%i1) compose (L, x) :=
  block ([r : x], for e in L do r : subst (e, x, r), r) $

Re-express above example using compose:

(%i1) polydecomp (compose ([x^2 - a, x^3 - x - 1], x), x);
                          2       3
(%o1)          [compose([x  - a, x  - x - 1], x)]

Note that though compose (polydecomp (p, x), x) always returns p (unexpanded), polydecomp (compose ([p_1, ..., p_n], x), x) does not necessarily return [p_1, ..., p_n]:

(%i1) polydecomp (compose ([x^2 + 2*x + 3, x^2], x), x);
                           2             2
(%o1)           [compose([x  + 2 x + 3, x ], x)]
(%i2) polydecomp (compose ([x^2 + x + 1, x^2 + x + 1], x), x);
                        2           2
(%o2)        [compose([x  + x + 1, x  + x + 1], x)]
Function: polymod
    polymod (p)
    polymod (p, m)

Converts the polynomial p to a modular representation with respect to the current modulus which is the value of the variable modulus.

polymod (p, m) specifies a modulus m to be used instead of the current value of modulus.

See modulus.

Function: polynomialp
    polynomialp (p, L, coeffp, exponp)
    polynomialp (p, L, coeffp)
    polynomialp (p, L)

Return true if p is a polynomial in the variables in the list L. The predicate coeffp must evaluate to true for each coefficient, and the predicate exponp must evaluate to true for all exponents of the variables in L. If you want to use a non-default value for exponp, you must supply coeffp with a value even if you want to use the default for coeffp.

The command polynomialp (p, L, coeffp) is equivalent to polynomialp (p, L, coeffp, 'nonnegintegerp) and the command polynomialp (p, L) is equivalent to polynomialp (p, L, 'constantp, 'nonnegintegerp).

The polynomial needn’t be expanded:

(%i1) polynomialp ((x + 1)*(x + 2), [x]);
(%o1)                         true
(%i2) polynomialp ((x + 1)*(x + 2)^a, [x]);
(%o2)                         false

An example using non-default values for coeffp and exponp:

(%i1) polynomialp ((x + 1)*(x + 2)^(3/2), [x], numberp, numberp);
(%o1)                         true
(%i2) polynomialp ((x^(1/2) + 1)*(x + 2)^(3/2), [x], numberp,
                                                        numberp);
(%o2)                         true

Polynomials with two variables:

(%i1) polynomialp (x^2 + 5*x*y + y^2, [x]);
(%o1)                         false
(%i2) polynomialp (x^2 + 5*x*y + y^2, [x, y]);
(%o2)                         true

Polynomial in one variable and accepting any expression free of x as a coefficient.

(%i1) polynomialp (a*x^2 + b*x + c, [x]);
(%o1)                         false
(%i2) polynomialp (a*x^2 + b*x + c, [x], lambda([ex], freeof(x, ex)));
(%o2)                         true
Function: quotient
    quotient (p_1, p_2)
    quotient (p_1, p_2, x_1, …, x_n)

Returns the polynomial p_1 divided by the polynomial p_2. The arguments x_1, …, x_n are interpreted as in ratvars.

quotient returns the first element of the two-element list returned by divide.

Function: rat
    rat (expr)
    rat (expr, x_1, …, x_n)

Converts expr to canonical rational expression (CRE) form by expanding and combining all terms over a common denominator and cancelling out the greatest common divisor of the numerator and denominator, as well as converting floating point numbers to rational numbers within a tolerance of ratepsilon. The variables are ordered according to the x_1, …, x_n, if specified, as in ratvars.

rat does not generally simplify functions other than addition +, subtraction -, multiplication *, division /, and exponentiation to an integer power, whereas ratsimp does handle those cases. Note that atoms (numbers and variables) in CRE form are not the same as they are in the general form. For example, rat(x)- x yields rat(0) which has a different internal representation than 0.

When ratfac is true, rat yields a partially factored form for CRE. During rational operations the expression is maintained as fully factored as possible without an actual call to the factor package. This should always save space and may save some time in some computations. The numerator and denominator are still made relatively prime (e.g., rat((x^2 - 1)^4/(x + 1)^2) yields (x - 1)^4 (x + 1)^2 when ratfac is true), but the factors within each part may not be relatively prime.

ratprint if false suppresses the printout of the message informing the user of the conversion of floating point numbers to rational numbers.

keepfloat if true prevents floating point numbers from being converted to rational numbers.

See also ratexpand and ratsimp.

Examples:

(%i1) ((x - 2*y)^4/(x^2 - 4*y^2)^2 + 1)*(y + a)*(2*y + x) /
      (4*y^2 + x^2);
                                           4
                                  (x - 2 y)
              (y + a) (2 y + x) (------------ + 1)
                                   2      2 2
                                 (x  - 4 y )
(%o1)         ------------------------------------
                              2    2
                           4 y  + x
(%i2) rat (%, y, a, x);
                            2 a + 2 y
(%o2)/R/                    ---------
                             x + 2 y
Option variable: ratalgdenom

Default value: true

When ratalgdenom is true, allows rationalization of denominators with respect to radicals to take effect. ratalgdenom has an effect only when canonical rational expressions (CRE) are used in algebraic mode.

Function: ratcoef
    ratcoef (expr, x, n)
    ratcoef (expr, x)

Returns the coefficient of the expression x^n in the expression expr. If omitted, n is assumed to be 1.

The return value is free (except possibly in a non-rational sense) of the variables in x. If no coefficient of this type exists, 0 is returned.

ratcoef expands and rationally simplifies its first argument and thus it may produce answers different from those of coeff which is purely syntactic. Thus ratcoef ((x + 1)/y + x, x) returns (y + 1)/y whereas coeff returns 1.

ratcoef (expr, x, 0), viewing expr as a sum, returns a sum of those terms which do not contain x. Therefore if x occurs to any negative powers, ratcoef should not be used.

Since expr is rationally simplified before it is examined, coefficients may not appear quite the way they were envisioned.

Example:

(%i1) s: a*x + b*x + 5$
(%i2) ratcoef (s, a + b);
(%o2)                           x
Function: ratdenom (expr)

Returns the denominator of expr, after coercing expr to a canonical rational expression (CRE). The return value is a CRE.

expr is coerced to a CRE by rat if it is not already a CRE. This conversion may change the form of expr by putting all terms over a common denominator.

denom is similar, but returns an ordinary expression instead of a CRE. Also, denom does not attempt to place all terms over a common denominator, and thus some expressions which are considered ratios by ratdenom are not considered ratios by denom.

Option variable: ratdenomdivide

Default value: true

When ratdenomdivide is true, ratexpand expands a ratio in which the numerator is a sum into a sum of ratios, all having a common denominator. Otherwise, ratexpand collapses a sum of ratios into a single ratio, the numerator of which is the sum of the numerators of each ratio.

Examples:

(%i1) expr: (x^2 + x + 1)/(y^2 + 7);
                            2
                           x  + x + 1
(%o1)                      ----------
                              2
                             y  + 7
(%i2) ratdenomdivide: true$
(%i3) ratexpand (expr);
                       2
                      x        x        1
(%o3)               ------ + ------ + ------
                     2        2        2
                    y  + 7   y  + 7   y  + 7
(%i4) ratdenomdivide: false$
(%i5) ratexpand (expr);
                            2
                           x  + x + 1
(%o5)                      ----------
                              2
                             y  + 7
(%i6) expr2: a^2/(b^2 + 3) + b/(b^2 + 3);
                                     2
                           b        a
(%o6)                    ------ + ------
                          2        2
                         b  + 3   b  + 3
(%i7) ratexpand (expr2);
                                  2
                             b + a
(%o7)                        ------
                              2
                             b  + 3
Function: ratdiff (expr, x)

Differentiates the rational expression expr with respect to x. expr must be a ratio of polynomials or a polynomial in x. The argument x may be a variable or a subexpression of expr.

The result is equivalent to diff, although perhaps in a different form. ratdiff may be faster than diff, for rational expressions.

ratdiff returns a canonical rational expression (CRE) if expr is a CRE. Otherwise, ratdiff returns a general expression.

ratdiff considers only the dependence of expr on x, and ignores any dependencies established by depends.

Example:

(%i1) expr: (4*x^3 + 10*x - 11)/(x^5 + 5);
                           3
                        4 x  + 10 x - 11
(%o1)                   ----------------
                              5
                             x  + 5
(%i2) ratdiff (expr, x);
                    7       5       4       2
                 8 x  + 40 x  - 55 x  - 60 x  - 50
(%o2)          - ---------------------------------
                          10       5
                         x   + 10 x  + 25
(%i3) expr: f(x)^3 - f(x)^2 + 7;
                         3       2
(%o3)                   f (x) - f (x) + 7
(%i4) ratdiff (expr, f(x));
                           2
(%o4)                   3 f (x) - 2 f(x)
(%i5) expr: (a + b)^3 + (a + b)^2;
                              3          2
(%o5)                  (b + a)  + (b + a)
(%i6) ratdiff (expr, a + b);
                    2                    2
(%o6)            3 b  + (6 a + 2) b + 3 a  + 2 a
Function: ratdisrep (expr)

Returns its argument as a general expression. If expr is a general expression, it is returned unchanged.

Typically ratdisrep is called to convert a canonical rational expression (CRE) into a general expression. This is sometimes convenient if one wishes to stop the "contagion", or use rational functions in non-rational contexts.

See also totaldisrep.

Function: ratexpand (expr)
Option variable: ratexpand

Expands expr by multiplying out products of sums and exponentiated sums, combining fractions over a common denominator, cancelling the greatest common divisor of the numerator and denominator, then splitting the numerator (if a sum) into its respective terms divided by the denominator.

The return value of ratexpand is a general expression, even if expr is a canonical rational expression (CRE).

The switch ratexpand if true will cause CRE expressions to be fully expanded when they are converted back to general form or displayed, while if it is false then they will be put into a recursive form. See also ratsimp.

When ratdenomdivide is true, ratexpand expands a ratio in which the numerator is a sum into a sum of ratios, all having a common denominator. Otherwise, ratexpand collapses a sum of ratios into a single ratio, the numerator of which is the sum of the numerators of each ratio.

When keepfloat is true, prevents floating point numbers from being rationalized when expressions which contain them are converted to canonical rational expression (CRE) form.

Examples:

(%i1) ratexpand ((2*x - 3*y)^3);
                     3         2       2        3
(%o1)          - 27 y  + 54 x y  - 36 x  y + 8 x
(%i2) expr: (x - 1)/(x + 1)^2 + 1/(x - 1);
                         x - 1       1
(%o2)                   -------- + -----
                               2   x - 1
                        (x + 1)
(%i3) expand (expr);
                    x              1           1
(%o3)          ------------ - ------------ + -----
                2              2             x - 1
               x  + 2 x + 1   x  + 2 x + 1
(%i4) ratexpand (expr);
                        2
                     2 x                 2
(%o4)           --------------- + ---------------
                 3    2            3    2
                x  + x  - x - 1   x  + x  - x - 1
Option variable: ratfac

Default value: false

When ratfac is true, canonical rational expressions (CRE) are manipulated in a partially factored form.

During rational operations the expression is maintained as fully factored as possible without calling factor. This should always save space and may save time in some computations. The numerator and denominator are made relatively prime, for example factor ((x^2 - 1)^4/(x + 1)^2) yields (x - 1)^4 (x + 1)^2, but the factors within each part may not be relatively prime.

In the ctensor (Component Tensor Manipulation) package, Ricci, Einstein, Riemann, and Weyl tensors and the scalar curvature are factored automatically when ratfac is true. ratfac should only be set for cases where the tensorial components are known to consist of few terms.

The ratfac and ratweight schemes are incompatible and may not both be used at the same time.

Function: ratnumer (expr)

Returns the numerator of expr, after coercing expr to a canonical rational expression (CRE). The return value is a CRE.

expr is coerced to a CRE by rat if it is not already a CRE. This conversion may change the form of expr by putting all terms over a common denominator.

num is similar, but returns an ordinary expression instead of a CRE. Also, num does not attempt to place all terms over a common denominator, and thus some expressions which are considered ratios by ratnumer are not considered ratios by num.

Function: ratp (expr)

Returns true if expr is a canonical rational expression (CRE) or extended CRE, otherwise false.

CRE are created by rat and related functions. Extended CRE are created by taylor and related functions.

Option variable: ratprint

Default value: true

When ratprint is true, a message informing the user of the conversion of floating point numbers to rational numbers is displayed.

Function: ratsimp (expr)
Function: ratsimp (expr, x_1, …, x_n)

Simplifies the expression expr and all of its subexpressions, including the arguments to non-rational functions. The result is returned as the quotient of two polynomials in a recursive form, that is, the coefficients of the main variable are polynomials in the other variables. Variables may include non-rational functions (e.g., sin (x^2 + 1)) and the arguments to any such functions are also rationally simplified.

ratsimp (expr, x_1, ..., x_n) enables rational simplification with the specification of variable ordering as in ratvars.

When ratsimpexpons is true, ratsimp is applied to the exponents of expressions during simplification.

See also ratexpand. Note that ratsimp is affected by some of the flags which affect ratexpand.

Examples:

(%i1) sin (x/(x^2 + x)) = exp ((log(x) + 1)^2 - log(x)^2);
                                         2      2
                   x         (log(x) + 1)  - log (x)
(%o1)        sin(------) = %e
                  2
                 x  + x
(%i2) ratsimp (%);
                             1          2
(%o2)                  sin(-----) = %e x
                           x + 1
(%i3) ((x - 1)^(3/2) - (x + 1)*sqrt(x - 1))/sqrt((x - 1)*(x + 1));
                       3/2
                (x - 1)    - sqrt(x - 1) (x + 1)
(%o3)           --------------------------------
                     sqrt((x - 1) (x + 1))
(%i4) ratsimp (%);
                           2 sqrt(x - 1)
(%o4)                    - -------------
                                 2
                           sqrt(x  - 1)
(%i5) x^(a + 1/a), ratsimpexpons: true;
                               2
                              a  + 1
                              ------
                                a
(%o5)                        x
Option variable: ratsimpexpons

Default value: false

When ratsimpexpons is true, ratsimp is applied to the exponents of expressions during simplification.

Option variable: radsubstflag

Default value: false

radsubstflag, if true, permits ratsubst to make substitutions such as u for sqrt (x) in x.

Function: ratsubst (a, b, c)

Substitutes a for b in c and returns the resulting expression. b may be a sum, product, power, etc.

ratsubst knows something of the meaning of expressions whereas subst does a purely syntactic substitution. Thus subst (a, x + y, x + y + z) returns x + y + z whereas ratsubst returns z + a.

When radsubstflag is true, ratsubst makes substitutions for radicals in expressions which don’t explicitly contain them.

ratsubst ignores the value true of the option variables keepfloat, float, and numer.

Examples:

(%i1) ratsubst (a, x*y^2, x^4*y^3 + x^4*y^8);
                              3      4
(%o1)                      a x  y + a
(%i2) cos(x)^4 + cos(x)^3 + cos(x)^2 + cos(x) + 1;
               4         3         2
(%o2)       cos (x) + cos (x) + cos (x) + cos(x) + 1
(%i3) ratsubst (1 - sin(x)^2, cos(x)^2, %);
            4           2                     2
(%o3)    sin (x) - 3 sin (x) + cos(x) (2 - sin (x)) + 3
(%i4) ratsubst (1 - cos(x)^2, sin(x)^2, sin(x)^4);
                        4           2
(%o4)                cos (x) - 2 cos (x) + 1
(%i5) radsubstflag: false$
(%i6) ratsubst (u, sqrt(x), x);
(%o6)                           x
(%i7) radsubstflag: true$
(%i8) ratsubst (u, sqrt(x), x);
                                2
(%o8)                          u
Function: ratvars (x_1, …, x_n)
Function: ratvars ()
System variable: ratvars

Declares main variables x_1, …, x_n for rational expressions. x_n, if present in a rational expression, is considered the main variable. Otherwise, x_[n-1] is considered the main variable if present, and so on through the preceding variables to x_1, which is considered the main variable only if none of the succeeding variables are present.

If a variable in a rational expression is not present in the ratvars list, it is given a lower priority than x_1.

The arguments to ratvars can be either variables or non-rational functions such as sin(x).

The variable ratvars is a list of the arguments of the function ratvars when it was called most recently. Each call to the function ratvars resets the list. ratvars () clears the list.

Option variable: ratvarswitch

Default value: true

Maxima keeps an internal list in the Lisp variable VARLIST of the main variables for rational expressions. If ratvarswitch is true, every evaluation starts with a fresh list VARLIST. This is the default behavior. Otherwise, the main variables from previous evaluations are not removed from the internal list VARLIST.

The main variables, which are declared with the function ratvars are not affected by the option variable ratvarswitch.

Examples:

If ratvarswitch is true, every evaluation starts with a fresh list VARLIST.

(%i1) ratvarswitch:true$

(%i2) rat(2*x+y^2);
                             2
(%o2)/R/                    y  + 2 x
(%i3) :lisp varlist
($X $Y)

(%i3) rat(2*a+b^2);
                             2
(%o3)/R/                    b  + 2 a

(%i4) :lisp varlist
($A $B)

If ratvarswitch is false, the main variables from the last evaluation are still present.

(%i4) ratvarswitch:false$

(%i5) rat(2*x+y^2);
                             2
(%o5)/R/                    y  + 2 x
(%i6) :lisp varlist
($X $Y)

(%i6) rat(2*a+b^2);
                             2
(%o6)/R/                    b  + 2 a

(%i7) :lisp varlist
($A $B $X $Y)
Function: ratweight
    ratweight (x_1, w_1, …, x_n, w_n)
    ratweight ()

Assigns a weight w_i to the variable x_i. This causes a term to be replaced by 0 if its weight exceeds the value of the variable ratwtlvl (default yields no truncation). The weight of a term is the sum of the products of the weight of a variable in the term times its power. For example, the weight of 3 x_1^2 x_2 is 2 w_1 + w_2. Truncation according to ratwtlvl is carried out only when multiplying or exponentiating canonical rational expressions (CRE).

ratweight () returns the cumulative list of weight assignments.

Note: The ratfac and ratweight schemes are incompatible and may not both be used at the same time.

Examples:

(%i1) ratweight (a, 1, b, 1);
(%o1)                     [a, 1, b, 1]
(%i2) expr1: rat(a + b + 1)$
(%i3) expr1^2;
                  2                  2
(%o3)/R/         b  + (2 a + 2) b + a  + 2 a + 1
(%i4) ratwtlvl: 1$
(%i5) expr1^2;
(%o5)/R/                  2 b + 2 a + 1
System variable: ratweights

Default value: []

ratweights is the list of weights assigned by ratweight. The list is cumulative: each call to ratweight places additional items in the list.

kill (ratweights) and save (ratweights) both work as expected.

Option variable: ratwtlvl

Default value: false

ratwtlvl is used in combination with the ratweight function to control the truncation of canonical rational expressions (CRE). For the default value of false, no truncation occurs.

Function: remainder
    remainder (p_1, p_2)
    remainder (p_1, p_2, x_1, …, x_n)

Returns the remainder of the polynomial p_1 divided by the polynomial p_2. The arguments x_1, …, x_n are interpreted as in ratvars.

remainder returns the second element of the two-element list returned by divide.

Function: resultant (p_1, p_2, x)

The function resultant computes the resultant of the two polynomials p_1 and p_2, eliminating the variable x. The resultant is a determinant of the coefficients of x in p_1 and p_2, which equals zero if and only if p_1 and p_2 have a non-constant factor in common.

If p_1 or p_2 can be factored, it may be desirable to call factor before calling resultant.

The option variable resultant controls which algorithm will be used to compute the resultant. See the option variable resultant.

The function bezout takes the same arguments as resultant and returns a matrix. The determinant of the return value is the desired resultant.

Examples:

(%i1) resultant(2*x^2+3*x+1, 2*x^2+x+1, x);
(%o1)                           8
(%i2) resultant(x+1, x+1, x);
(%o2)                           0
(%i3) resultant((x+1)*x, (x+1), x);
(%o3)                           0
(%i4) resultant(a*x^2+b*x+1, c*x + 2, x);
                         2
(%o4)                   c  - 2 b c + 4 a

(%i5) bezout(a*x^2+b*x+1, c*x+2, x);
                        [ 2 a  2 b - c ]
(%o5)                   [              ]
                        [  c      2    ]
(%i6) determinant(%);
(%o6)                   4 a - (2 b - c) c
Option variable: resultant

Default value: subres

The option variable resultant controls which algorithm will be used to compute the resultant with the function resultant. The possible values are:

subres

for the subresultant polynomial remainder sequence (PRS) algorithm,

mod

(not enabled) for the modular resultant algorithm, and

red

for the reduced polynomial remainder sequence (PRS) algorithm.

On most problems the default value subres should be best.

Option variable: savefactors

Default value: false

When savefactors is true, causes the factors of an expression which is a product of factors to be saved by certain functions in order to speed up later factorizations of expressions containing some of the same factors.

Function: showratvars (expr)

Returns a list of the canonical rational expression (CRE) variables in expression expr.

See also ratvars.

Function: sqfr (expr)

is similar to factor except that the polynomial factors are "square-free." That is, they have factors only of degree one. This algorithm, which is also used by the first stage of factor, utilizes the fact that a polynomial has in common with its n’th derivative all its factors of degree greater than n. Thus by taking greatest common divisors with the polynomial of the derivatives with respect to each variable in the polynomial, all factors of degree greater than 1 can be found.

Example:

(%i1) sqfr (4*x^4 + 4*x^3 - 3*x^2 - 4*x - 1);
                                2   2
(%o1)                  (2 x + 1)  (x  - 1)
Function: tellrat
    tellrat (p_1, …, p_n)
    tellrat ()

Adds to the ring of algebraic integers known to Maxima the elements which are the solutions of the polynomials p_1, …, p_n. Each argument p_i is a polynomial with integer coefficients.

tellrat (x) effectively means substitute 0 for x in rational functions.

tellrat () returns a list of the current substitutions.

algebraic must be set to true in order for the simplification of algebraic integers to take effect.

Maxima initially knows about the imaginary unit %i and all roots of integers.

There is a command untellrat which takes kernels and removes tellrat properties.

When tellrat’ing a multivariate polynomial, e.g., tellrat (x^2 - y^2), there would be an ambiguity as to whether to substitute y^2 for x^2 or vice versa. Maxima picks a particular ordering, but if the user wants to specify which, e.g. tellrat (y^2 = x^2) provides a syntax which says replace y^2 by x^2.

Examples:

(%i1) 10*(%i + 1)/(%i + 3^(1/3));
                           10 (%i + 1)
(%o1)                      -----------
                                  1/3
                            %i + 3
(%i2) ev (ratdisrep (rat(%)), algebraic);
             2/3      1/3              2/3      1/3
(%o2)    (4 3    - 2 3    - 4) %i + 2 3    + 4 3    - 2
(%i3) tellrat (1 + a + a^2);
                            2
(%o3)                     [a  + a + 1]
(%i4) 1/(a*sqrt(2) - 1) + a/(sqrt(3) + sqrt(2));
                      1                 a
(%o4)           ------------- + -----------------
                sqrt(2) a - 1   sqrt(3) + sqrt(2)
(%i5) ev (ratdisrep (rat(%)), algebraic);
         (7 sqrt(3) - 10 sqrt(2) + 2) a - 2 sqrt(2) - 1
(%o5)    ----------------------------------------------
                               7
(%i6) tellrat (y^2 = x^2);
                        2    2   2
(%o6)                 [y  - x , a  + a + 1]
Function: totaldisrep (expr)

Converts every subexpression of expr from canonical rational expressions (CRE) to general form and returns the result. If expr is itself in CRE form then totaldisrep is identical to ratdisrep.

totaldisrep may be useful for ratdisrepping expressions such as equations, lists, matrices, etc., which have some subexpressions in CRE form.

Function: untellrat (x_1, …, x_n)

Removes tellrat properties from x_1, …, x_n.


Next: , Previous: Functions and Variables for Polynomials, Up: Polynomials   [Contents][Index]

11.3 Introduction to algebraic extensions

We assume here that the fields are of characteristic 0 so that irreductible polynomials have simple roots (are separable, thus square free). The base fields K of interest are the field Q of rational numbers, for algebraic numbers, and the fields of rational functions on the real numbers R or the complex numbers C, that is R(t) or C(t), when considering algebraic functions. An extension of degree n is defined by an irreducible degree n polynomial p(x) with coefficients in the base field, and consists of the quotient of the ring K[x] of polynomials by the multiples of p(x). So if p(x) = x^n + p_0 x^{n - 1} + ... + p_n, each time one encounters x^n one substitutes -(p_0 x^{n - 1} + ... + p_n). This is a field because of Bezout’s identity, and a vector space of dimension n over K spanned by 1, x, ..., x^{n - 1}. When K = C(t), this field can be identified with the field of algebraic functions on the algebraic curve of equation p(x, t) = 0.

In Maxima the process of taking rationals modulo p is obtained by the function tellrat when algebraic is true. The best way to ensure, in particular when considering the case where p depends on other variables that this simplification property is attached to x is to write (note the polynomial must be monic): tellrat(x^n = -(p_0*x^(n - 1) + ... + p_n)) where the p_i may depend on other variables. When one wants to remove this tellrat property one then has to write untellrat(x).

In the field K[x] one may do all sorts of algebraic computations, taking quotients, GCD of two elements, etc. by the same algorithms as in the usual case. In particular one can do factorization of polynomials on an extension, using the function algfac below. Moreover multiplication by an element f is a linear operation of the vector space K[x] over K and as such has a trace and a determinant. These are called algtrace and algnorm below. One can see that the trace of an element f(x) in K[x] is the sum of the values f(a) when a runs over roots of p and the norm is the product of the f(a). Both are symmetric in the roots of p and thus belong to K.

The field K[x] is also called the field obtained by adjoining a root a of p(x) to K. One can similarly adjoin a second root b of another polynomial obtaining a new extension K[a,b]. In fact there is a “prime element” c in K[a, b] such that K[a, b] = K[c]. This is obtained by function primeelmt below. Recursively one can thus adjoin any number of elements. In particular adjoining all the roots of p(x) to K one gets the splitting field of p, which is the smallest extension in which p completely splits in linear functions. The function splitfield constructs a primitive element of the splitting field, which in general is of very high degree.

The relevant concepts are explained in a concise and self-contained way in the small books edited by Dover: “Algebraic theory of numbers,” by Pierre Samuel, “Algebraic curves,” by Robert Walker, and the methods presented here are described in the article “Algebraic factoring and rational function integration” by B. Trager, Proceedings of the 1976 AMS Symposium on Symbolic and Algebraic Computation.


Previous: Introduction to algebraic extensions, Up: Polynomials   [Contents][Index]

11.4 Functions and Variables for algebraic extensions

Function: algfac (f, p)

Returns the factorization of f in the field K[a]. Does the same as factor(f, p) which in fact calls algfac. One can also specify the variable a as in algfac(f, p, a).

Examples:

(%i1) algfac(x^4 + 1, a^2 - 2);
                           2              2
(%o1)                    (x  - a x + 1) (x  + a x + 1)
(%i2) algfac(x^4 - t*x^2 + 1, a^2 - t - 2, a);
                           2              2
(%o2)                    (x  - a x + 1) (x  + a x + 1)

In the second example note that a = sqrt(2 + t).

Function: algnorm (f, p, a)

Returns the norm of the polynomial f(a) in the extension obtained by a root a of polynomial p. The coefficients of f may depend on other variables.

Examples:

(%i1) algnorm(x*a^2 + y*a + z,a^2 - 2, a);
                            2              2      2
(%o1)/R/                   z  + 4 x z - 2 y  + 4 x

The norm is also the resultant of polynomials f and p, and the product of the differences of the roots of f and p.

Function: algtrace (f, p, a)

Returns the trace of the polynomial f(a) in the extension obtained by a root a of polynomial p. The coefficients of f may depend on other variables which remain “inert”.

Example:

(%i1) algtrace(x*a^5 + y*a^3 + z + 1, a^2 + a + 1, a);
(%o1)/R/                       2 z + 2 y - x + 2
Function: bdiscr (args)

Computes the discriminant of a basis x_i in K[a] as the determinant of the matrix of elements trace(x_i*x_j). The args are the elements of the basis followed by the minimal polynomial.

Example:

(%i1) bdiscr(1, x, x^2, x^3 - 2);
(%o1)/R/                             - 108
(%i2) poly_discriminant(x^3 - 2, x);
(%o2)                                - 108

A standard base in an extension of degree n is 1, x, ..., x^{n - 1}. In this case it is known that the discriminant of this base is the discriminant of the minimal polynomial. This is checked in (%o2) above.

Function: primelmt (f_b, p_a, c)

Computes a prime element for the extension of K[a] by a root b of a polynomial f_b(b) whose coefficients may depend on a. One assumes that f_b is square free. The function returns an irreducible polynomial, a root of which generates K[a, b], and the expression of this primitive element in terms of a and b.

Examples:

(%i1) primelmt(b^2 - a*b - 1, a^2 - 2, c);
                              4       2
(%o1)                       [c  - 12 c  + 9, b + a]
(%i2) solve(b^2 - sqrt(2)*b - 1)[1];
                                  sqrt(6) - sqrt(2)
(%o2)                       b = - -----------------
                                          2
(%i3) primelmt(b^2 - 3, a^2 - 2, c);
                              4       2
(%o3)                       [c  - 10 c  + 1, b + a]
(%i4) factor(c^4 - 12*c^2 + 9, a^4 - 10*a^2 + 1);
                 3    2                       3    2
(%o4) ((4 c - 3 a  - a  + 27 a + 5) (4 c - 3 a  + a  + 27 a - 5)
                           3    2                       3    2
                 (4 c + 3 a  - a  - 27 a + 5) (4 c + 3 a  + a  - 27 a - 5))/256
(%i5) primelmt(b^3 - 3, a^2 - 2, c);
                   6      4      3       2
(%o5)            [c  - 6 c  - 6 c  + 12 c  - 36 c + 1, b + a]
(%i6) factor(b^3 - 3, %[1]);
            5       4        3        2
(%o6) ((48 c  + 27 c  - 320 c  - 468 c  + 124 c + 755 b - 1092)
           5        5         4       4          3        3          2        2
 ((- 48 b c ) - 54 c  - 27 b c  + 64 c  + 320 b c  + 360 c  + 468 b c  + 149 c
                           2
 - 124 b c - 1272 c + 755 b  + 1092 b + 1606))/570025

In (%o1), f_b depends on a. Using solve, the solution depends on sqrt(2) and sqrt(3). In (%o3), K[sqrt(2), sqrt(3)] is computed, and we see that the the primitive polynomial in (%o1) factorizes completely here. In (%i5), we compute K[sqrt(2), 3^{1/3}], and we see that b^3 - 3 gets one factor in this extension. If we assume this extension is real, the two other factors are complex.

Function: splitfield (p, x)

Computes the splitting field of the polynomial p(x). In the generic case it is of degree n! in terms of the degree n of p, but may be of lower order if the Galois group of p is a strict subgroup of the group of permutations of n elements. The function returns a primitive polynomial for this extension and the expressions of the roots of p as polynomials of a root of this primitive polynomial. The polynomial f may be irreducible or factorizable.

Examples:

(%i1) splitfield(x^3 + x + 1, x);
                                              4         2
              6         4         2       alg1  + 5 alg1  - 9 alg1 + 4
(%o1)/R/ [alg1  + 6 alg1  + 9 alg1  + 31, ----------------------------, 
                                                       18
                                 4         2          4         2
                             alg1  + 5 alg1  + 4  alg1  + 5 alg1  + 9 alg1 + 4
                           - -------------------, ----------------------------]
                                      9                        18
(%i2) splitfield(x^4 + 10*x^2 - 96*x - 71, x)[1];
             8           6           5            4             3
(%o2)/R/ alg2  + 148 alg2  - 576 alg2  + 9814 alg2  - 42624 alg2
                                                    2
                                       + 502260 alg2  + 1109952 alg2 + 18860337

In the first case we have the primitive polynomial of degree 6 and the 3 roots of the third degree equations in terms of a variable alg1 produced by the system. In the second case the primitive polynomial is of degree 8 instead of 24, because the Galois group of the equation is reduced to D8 since there are relations between the roots.


Next: , Previous: Polynomials, Up: Top   [Contents][Index]

12 Константы


Previous: Константы, Up: Константы   [Contents][Index]

12.1 Математические константы

Константа: %e

%e представляет основание натурального логарифма, также известное как число Эйлера. Численное значение %e является числом с плавающей точкой двойной точности 2.718281828459045d0.

Константа: %i

%i представляет мнимую единицу, sqrt(-1).

Константа: false

false – логическая константа "ложь". В Maxima false представляется значением NIL в Lisp.

Константа: ind

ind представляет конечный, неопределенный результат.

См. также limit.

Пример:

(%i1) limit (sin(1/x), x, 0);
(%o1)                          ind
Константа: inf

inf представляет вещественную положительную бесконечность.

Константа: infinity

infinity представляет комплексную бесконечность.

Константа: minf

minf представляет вещественную минус (т.е. отрицательную) бесконечность.

Константа: %phi

%phi представляет так называемое золотое сечение, (1 + sqrt(5))/2. Численное значение %phi является числом с плавающей точкой двойной точности 1.618033988749895d0.

fibtophi выражает числа Фибоначчи fib(n) в терминах %phi.

По умолчанию Maxima не знает алгебраические свойства %phi. После выполнения tellrat(%phi^2 - %phi - 1) и algebraic: true, ratsimp может упрощать некоторые выражения, содержащие %phi.

Примеры:

fibtophi выражает числа Фибоначчи fib(n) в терминах %phi.

(%i1) fibtophi (fib (n));
                           n             n
                       %phi  - (1 - %phi)
(%o1)                  -------------------
                           2 %phi - 1
(%i2) fib (n-1) + fib (n) - fib (n+1);
(%o2)          - fib(n + 1) + fib(n) + fib(n - 1)
(%i3) fibtophi (%);
            n + 1             n + 1       n             n
        %phi      - (1 - %phi)        %phi  - (1 - %phi)
(%o3) - --------------------------- + -------------------
                2 %phi - 1                2 %phi - 1
                                          n - 1             n - 1
                                      %phi      - (1 - %phi)
                                    + ---------------------------
                                              2 %phi - 1
(%i4) ratsimp (%);
(%o4)                           0

По умолчанию Maxima не знает алгебраические свойства %phi. После выполнения tellrat(%phi^2 - %phi - 1) и algebraic: true, ratsimp может упрощать некоторые выражения, содержащие %phi.

(%i1) e : expand ((%phi^2 - %phi - 1) * (A + 1));
                 2                      2
(%o1)        %phi  A - %phi A - A + %phi  - %phi - 1
(%i2) ratsimp (e);
                  2                     2
(%o2)        (%phi  - %phi - 1) A + %phi  - %phi - 1
(%i3) tellrat (%phi^2 - %phi - 1);
                            2
(%o3)                  [%phi  - %phi - 1]
(%i4) algebraic : true;
(%o4)                         true
(%i5) ratsimp (e);
(%o5)                           0
Константа: %pi

%pi представляет отношение длины окружности к ее диаметру. Численное значение %pi является числом с плавающей точкой двойной точности 3.141592653589793d0.

Константа: true

true – логическая константа "истина". В Maxima true представляется значением T в Lisp.

Константа: und

und представляет неопределенный результат.

См. также limit.

Пример:

(%i1) limit (1/x, x, 0);
(%o1)                          und

Next: , Previous: Константы, Up: Top   [Contents][Index]

13 Тригонометрия


Next: , Previous: Тригонометрия, Up: Тригонометрия   [Contents][Index]

13.1 Тригонометрия в Maxima

В Maxima определено много тригонометрических функций. Запрограммированны не все тригонометрические тождества, но пользователь может добавить большинство из них благодаря возможностям системы по поиску совпадений с шаблонами (подстановки). В Maxima определены следующие тригонометрические функции acos, acosh, acot, acoth, acsc, acsch, asec, asech, asin, asinh, atan, atanh, cos, cosh, cot, coth, csc, csch, sec, sech, sin, sinh, tan и tanh. Для работы с тригонометрическими функциями есть ряд особых команд, см. trigexpand, trigreduce и trigsign. Два встроенных пакета расширяют правила упрощения Maxima: ntrig и atrig1. Для подробностей запустите describe(command).


Previous: Тригонометрия в Maxima, Up: Тригонометрия   [Contents][Index]

13.2 Функции и переменные для тригонометрии

Управляющая переменная: %piargs

Значение по умолчанию: true

Если %piargs равно true, то тригонометрические функции упрощаются до алгебраических констант, если аргумент кратен %pi, %pi/2, %pi/3, %pi/4 или %pi/6.

Maxima использует некоторые тождества, применимые, если %pi домножается на целую переменную (символ, определенный как целое число).

Примеры:

(%i1) %piargs : false;
(%o1)                         false
(%i2) [sin (%pi), sin (%pi/2), sin (%pi/3)];
                                %pi       %pi
(%o2)            [sin(%pi), sin(---), sin(---)]
                                 2         3
(%i3) [sin (%pi/4), sin (%pi/5), sin (%pi/6)];
                      %pi       %pi       %pi
(%o3)            [sin(---), sin(---), sin(---)]
                       4         5         6
(%i4) %piargs : true;
(%o4)                         true
(%i5) [sin (%pi), sin (%pi/2), sin (%pi/3)];
                                sqrt(3)
(%o5)                    [0, 1, -------]
                                   2
(%i6) [sin (%pi/4), sin (%pi/5), sin (%pi/6)];
                         1         %pi   1
(%o6)                [-------, sin(---), -]
                      sqrt(2)       5    2
(%i7) [cos (%pi/3), cos (10*%pi/3), tan (10*%pi/3), cos (sqrt(2)*%pi/3)];
                1    1               sqrt(2) %pi
(%o7)          [-, - -, sqrt(3), cos(-----------)]
                2    2                    3

Некоторые тождества применяются, если %pi и %pi/2 домножается на целую переменную (символ, определенный как целое число):

(%i1) declare (n, integer, m, even);
(%o1)                         done
(%i2) [sin (%pi * n), cos (%pi * m), sin (%pi/2 * m), cos (%pi/2 * m)];
                                      m/2
(%o2)                  [0, 1, 0, (- 1)   ]
Управляющая переменная: %iargs

Значение по умолчанию: true

Если %iargs равно true, то тригонометрические функции упрощаются до гиперболических, если аргумент явно домножается на мнимую единицу %i.

Упрощение производится, даже если аргумент явно является вещественным; Maxima лишь проверяет, просматривается ли явно в аргументе множитель %i.

Примеры:

(%i1) %iargs : false;
(%o1)                         false
(%i2) [sin (%i * x), cos (%i * x), tan (%i * x)];
(%o2)           [sin(%i x), cos(%i x), tan(%i x)]
(%i3) %iargs : true;
(%o3)                         true
(%i4) [sin (%i * x), cos (%i * x), tan (%i * x)];
(%o4)           [%i sinh(x), cosh(x), %i tanh(x)]

Упрощение проводится, даже если аргумент явно является вещественным:

(%i1) declare (x, imaginary);
(%o1)                         done
(%i2) [featurep (x, imaginary), featurep (x, real)];
(%o2)                     [true, false]
(%i3) sin (%i * x);
(%o3)                      %i sinh(x)
Функция: acos (x)

- Арккосинус.

Функция: acosh (x)

- Ареакосинус (гиперболический арккосинус).

Функция: acot (x)

- Арккотангенс.

Функция: acoth (x)

- Ареакотангенс (гиперболический арккотангенс).

Функция: acsc (x)

- Арккосеканс.

Функция: acsch (x)

- Ареакосеканс (гиперболический арккосеканс).

Функция: asec (x)

- Арксеканс.

Функция: asech (x)

- Ареасеканс (гиперболический арксеканс).

Функция: asin (x)

- Арксинус.

Функция: asinh (x)

- Ареасинус (гиперболический арксинус).

Функция: atan (x)

- Арктангенс.

Функция: atan2 (y, x)

- соответствует значению atan(y/x) на интервале (-%pi, %pi).

Функция: atanh (x)

- Ареатангенс (гиперболический арктангенс).

Пакет: atrig1

Пакет atrig1 содержит несколько дополнительных правил упрощения для обратных тригонометрических функций. Вместе с уже известными Maxima правилами, полностью реализована работа с углами 0, %pi/6, %pi/4, %pi/3 и %pi/2, а также соответствующими углами в трех других четвертях. Для использования пакета выполните load("atrig1");.

Функция: cos (x)

- Косинус.

Функция: cosh (x)

- Ареакосинус (гиперболический арккосинус).

Функция: cot (x)

- Котангенс.

Функция: coth (x)

- Ареакотангенс (гиперболический арккотангенс).

Функция: csc (x)

- Косеканс.

Функция: csch (x)

- Ареакосеканс (гиперболический арккосеканс).

Управляющая переменная: halfangles

Значение по умолчанию: false

Если halfangles равно true, то тригонометрические функции аргументов expr/2 упрощаются в функции от expr.

Примеры:

(%i1) halfangles : false;
(%o1)                         false
(%i2) sin (x / 2);
                                 x
(%o2)                        sin(-)
                                 2
(%i3) halfangles : true;
(%o3)                         true
(%i4) sin (x / 2);
                        sqrt(1 - cos(x))
(%o4)                   ----------------
                            sqrt(2)
Пакет: ntrig

Пакет ntrig содержит набор правил упрощения для тригонометрических функций с аргументами вида f(n %pi/10), где f - одна из функций sin, cos, tan, csc, sec и cot.

Функция: sec (x)

- Секанс.

Функция: sech (x)

- Гиперболический секанс.

Функция: sin (x)

- Синус.

Функция: sinh (x)

- Гиперболический синус.

Функция: tan (x)

- Тангенс.

Функция: tanh (x)

- Гиперболический тангенс.

Функция: trigexpand (expr)

Раскрывает тригонометрические и гиперболические функции суммы или произведения углов в expr. Для получения лучших результатов нужно сначала раскрыть expr. Для повышения пользовательского контроля за упрощением функция раскрывает только один уровень сумм/произведений за раз. Для полного раскрытия в синусы и косинусы укажите trigexpand: true.

trigexpand управляется следующими глобальными флагами:

trigexpand

Раскрывать все получающиеся в последствии выражения с синусами и косинусами.

halfangles

Раскрывать функции половинных углов в функции полных углов.

trigexpandplus

Раскрывать функции сумм аргументов (например, sin(x + y)).

trigexpandtimes

Раскрывать функции кратных аргументов (например, sin(2 x)).

Примеры:

(%i1) x+sin(3*x)/sin(x),trigexpand=true,expand;
                         2           2
(%o1)               - sin (x) + 3 cos (x) + x
(%i2) trigexpand(sin(10*x+y));
(%o2)          cos(10 x) sin(y) + sin(10 x) cos(y)

Управляющая переменная: trigexpandplus

Значение по умолчанию: true

trigexpandplus управляет раскрытием функций от сумм аргументов в trigexpand (если trigexpand равно true, либо в функции trigexpand), например, sin(x+y). Упрощение производится, только если trigexpandplus равно true.

Управляющая переменная: trigexpandtimes

Значение по умолчанию: true

trigexpandplus управляет раскрытием функций от произведений аргументов в trigexpand (если trigexpand равно true, либо в функции trigexpand), например, sin(2*x). Упрощение производится, только если trigexpandtimes равно true.

Управляющая переменная: triginverses

Значение по умолчанию: all

triginverses управляет раскрытием композиций тригонометрических и гиперболических функций со своими обратными функциями.

Если all, то и atan(tan(x)), и tan(atan(x)) упрощается в x.

Если true, то упрощение arcfun(fun(x)) не производится.

Если false, то ни arcfun(fun(x)), ни fun(arcfun(x)) не будет упрощено.

Функция: trigreduce (expr, x)
Функция: trigreduce (expr)

Раскрывает произведения и степени sin, cos, sinh, cosh в функции кратных аргументов x. Также производится попытка исключить такие функции из знаменателей. Если x не указано, будут использоваться все переменные из expr.

См. также poissimp.

(%i1) trigreduce(-sin(x)^2+3*cos(x)^2+x);
               cos(2 x)      cos(2 x)   1        1
(%o1)          -------- + 3 (-------- + -) + x - -
                  2             2       2        2

В некоторых простых случаях команды упрощения используют информацию о переменных, объявленную следующим образом:

(%i1) declare(j, integer, e, even, o, odd)$
(%i2) sin(x + (e + 1/2)*%pi);
(%o2)                        cos(x)
(%i3) sin(x + (o + 1/2)*%pi);
(%o3)                       - cos(x)

Управляющая переменная: trigsign

Значение по умолчанию: true

Если trigsign равно true, допускается упрощение отрицательных аргументов тригонометрических функций. Например, sin(-x) раскроется в -sin(x).

Функция: trigsimp (expr)

Применяет тождества sin(x)^2 + cos(x)^2 = 1 и cosh(x)^2 - sinh(x)^2 = 1 для упрощения выражений с tan, sec, и так далее, до выражений с sin, cos, sinh, cosh.

Результат может упрощаться далее с trigreduce, ratsimp, и radcan.

demo ("trgsmp.dem") показывает несколько примеров для trigsimp.

Функция: trigrat (expr)

Возвращает канонический упрощенный квазилинейный вид тригонометрического выражения; expr - рациональная дробь с функциями sin, cos или tan, аргументы которых - линейные формы некоторых переменных и %pi/n (n - целое) с целыми коэффициентами. Результат - упрощенная дробь с линейным числителем и знаменателем с sin и cos. Таким образом, trigrat переходит к линейному виду, только если это возможно.

(%i1) trigrat(sin(3*a)/sin(a+%pi/3));
(%o1)            sqrt(3) sin(2 a) + cos(2 a) - 1

Следующий пример взят из раздела 1.5.5, "Теорема Морлея", книги Davenport, Siret, Tournier, Calcul Formel, изд-во Masson (английский перевод - Addison-Wesley).

(%i1) c: %pi/3 - a - b;
                                    %pi
(%o1)                     - b - a + ---
                                     3
(%i2) bc: sin(a)*sin(3*c)/sin(a+b);
                      sin(a) sin(3 b + 3 a)
(%o2)                 ---------------------
                           sin(b + a)
(%i3) ba: bc, c=a, a=c$
(%i4) ac2: ba^2 + bc^2 - 2*bc*ba*cos(b);
         2       2
      sin (a) sin (3 b + 3 a)
(%o4) -----------------------
               2
            sin (b + a)

                                        %pi
   2 sin(a) sin(3 a) cos(b) sin(b + a - ---) sin(3 b + 3 a)
                                         3
 - --------------------------------------------------------
                           %pi
                   sin(a - ---) sin(b + a)
                            3

      2         2         %pi
   sin (3 a) sin (b + a - ---)
                           3
 + ---------------------------
             2     %pi
          sin (a - ---)
                    3
(%i5) trigrat (ac2);
(%o5) - (sqrt(3) sin(4 b + 4 a) - cos(4 b + 4 a)

 - 2 sqrt(3) sin(4 b + 2 a) + 2 cos(4 b + 2 a)

 - 2 sqrt(3) sin(2 b + 4 a) + 2 cos(2 b + 4 a)

 + 4 sqrt(3) sin(2 b + 2 a) - 8 cos(2 b + 2 a) - 4 cos(2 b - 2 a)

 + sqrt(3) sin(4 b) - cos(4 b) - 2 sqrt(3) sin(2 b) + 10 cos(2 b)

 + sqrt(3) sin(4 a) - cos(4 a) - 2 sqrt(3) sin(2 a) + 10 cos(2 a)

 - 9)/4


Next: , Previous: Тригонометрия, Up: Top   [Contents][Index]

14 Special Functions


Next: , Up: Special Functions   [Contents][Index]

14.1 Introduction to Special Functions

Special function notation follows:

bessel_j (index, expr)         Bessel function, 1st kind
bessel_y (index, expr)         Bessel function, 2nd kind
bessel_i (index, expr)         Modified Bessel function, 1st kind
bessel_k (index, expr)         Modified Bessel function, 2nd kind

hankel_1 (v,z)                 Hankel function of the 1st kind
hankel_2 (v,z)                 Hankel function of the 2nd kind
struve_h (v,z)                 Struve H function
struve_l (v,z)                 Struve L function

assoc_legendre_p[v,u] (z)      Legendre function of degree v and order u 
assoc_legendre_q[v,u] (z)      Legendre function, 2nd kind

%f[p,q] ([], [], expr)         Generalized Hypergeometric function
gamma (z)                      Gamma function
gamma_incomplete_lower (a,z)   Lower incomplete gamma function
gamma_incomplete (a,z)         Tail of incomplete gamma function
hypergeometric (l1, l2, z)     Hypergeometric function
%s[u,v] (z)                    Lommel "small" s function
slommel[u,v] (z)               Lommel "big" S function
%m[u,k] (z)                    Whittaker function, 1st kind
%w[u,k] (z)                    Whittaker function, 2nd kind
erfc (z)                       Complement of the erf function

expintegral_e (v,z)            Exponential integral E
expintegral_e1 (z)             Exponential integral E1
expintegral_ei (z)             Exponential integral Ei
expintegral_li (z)             Logarithmic integral Li
expintegral_si (z)             Exponential integral Si
expintegral_ci (z)             Exponential integral Ci
expintegral_shi (z)            Exponential integral Shi
expintegral_chi (z)            Exponential integral Chi

kelliptic (z)                  Complete elliptic integral of the first 
                               kind (K)
parabolic_cylinder_d (v,z)     Parabolic cylinder D function

Next: , Previous: Introduction to Special Functions, Up: Special Functions   [Contents][Index]

14.2 Bessel Functions

Function: bessel_j (v, z)

The Bessel function of the first kind of order v and argument z. See A&S eqn 9.1.10 and DLMF 10.2.E2.

bessel_j is defined as

$$ J_v(z) = \sum_{k=0}^{\infty }{{{\left(-1\right)^{k}\,\left(z\over 2\right)^{v+2\,k} }\over{k!\,\Gamma\left(v+k+1\right)}}} $$

although the infinite series is not used for computations.

When besselexpand is true, bessel_j is expanded in terms of elementary functions when the order v is half of an odd integer. See besselexpand.

Function: bessel_y (v, z)

The Bessel function of the second kind of order v and argument z. See A&S eqn 9.1.2 and DLMF 10.2.E3.

bessel_y is defined as $$ Y_v(z) = {{\cos(\pi v)\, J_v(z) - J_{-v}(z)}\over{\sin{\pi v}}} $$

when v is not an integer. When v is an integer n, the limit as v approaches n is taken.

When besselexpand is true, bessel_y is expanded in terms of elementary functions when the order v is half of an odd integer. See besselexpand.

Function: bessel_i (v, z)

The modified Bessel function of the first kind of order v and argument z. See A&S eqn 9.6.10 and DLMF 10.25.E2.

bessel_i is defined as $$ I_v(z) = \sum_{k=0}^{\infty } {{1\over{k!\,\Gamma \left(v+k+1\right)}} {\left(z\over 2\right)^{v+2\,k}}} $$

although the infinite series is not used for computations.

When besselexpand is true, bessel_i is expanded in terms of elementary functions when the order v is half of an odd integer. See besselexpand.

Function: bessel_k (v, z)

The modified Bessel function of the second kind of order v and argument z. See A&S eqn 9.6.2 and DLMF 10.27.E4.

bessel_k is defined as $$ K_v(z) = {{\pi\,\csc \left(\pi\,v\right)\,\left(I_{-v}(z)-I_{v}(z)\right)}\over{2}} $$

when v is not an integer. If v is an integer n, then the limit as v approaches n is taken.

When besselexpand is true, bessel_k is expanded in terms of elementary functions when the order v is half of an odd integer. See besselexpand.

Function: hankel_1 (v, z)

The Hankel function of the first kind of order v and argument z. See A&S eqn 9.1.3 and DLMF 10.4.E3.

hankel_1 is defined as

$$ H^{(1)}_v(z) = J_v(z) + i Y_v(z) $$

Maxima evaluates hankel_1 numerically for a complex order v and complex argument z in float precision. The numerical evaluation in bigfloat precision is not supported.

When besselexpand is true, hankel_1 is expanded in terms of elementary functions when the order v is half of an odd integer. See besselexpand.

Maxima knows the derivative of hankel_1 wrt the argument z.

Examples:

Numerical evaluation:

(%i1) hankel_1(1,0.5);
(%o1)        0.24226845767487 - 1.471472392670243 %i
(%i2) hankel_1(1,0.5+%i);
(%o2)       - 0.25582879948621 %i - 0.23957560188301

Expansion of hankel_1 when besselexpand is true:

(%i1) hankel_1(1/2,z),besselexpand:true;
               sqrt(2) sin(z) - sqrt(2) %i cos(z)
(%o1)          ----------------------------------
                       sqrt(%pi) sqrt(z)

Derivative of hankel_1 wrt the argument z. The derivative wrt the order v is not supported. Maxima returns a noun form:

(%i1) diff(hankel_1(v,z),z);
             hankel_1(v - 1, z) - hankel_1(v + 1, z)
(%o1)        ---------------------------------------
                                2
(%i2) diff(hankel_1(v,z),v);
                       d
(%o2)                  -- (hankel_1(v, z))
                       dv
Function: hankel_2 (v, z)

The Hankel function of the second kind of order v and argument z. See A&S eqn 9.1.4 and DLMF 10.4.E3.

hankel_2 is defined as

$$ H^{(2)}_v(z) = J_v(z) - i Y_v(z) $$

Maxima evaluates hankel_2 numerically for a complex order v and complex argument z in float precision. The numerical evaluation in bigfloat precision is not supported.

When besselexpand is true, hankel_2 is expanded in terms of elementary functions when the order v is half of an odd integer. See besselexpand.

Maxima knows the derivative of hankel_2 wrt the argument z.

For examples see hankel_1.

Option variable: besselexpand

Default value: false

Controls expansion of the Bessel, Hankel and Struve functions when the order is half of an odd integer. In this case, the functions can be expanded in terms of other elementary functions. When besselexpand is true, the Bessel function is expanded.

(%i1) besselexpand: false$
(%i2) bessel_j (3/2, z);
                                    3
(%o2)                      bessel_j(-, z)
                                    2
(%i3) besselexpand: true$
(%i4) bessel_j (3/2, z);
                                        sin(z)   cos(z)
                       sqrt(2) sqrt(z) (------ - ------)
                                           2       z
                                          z
(%o4)                  ---------------------------------
                                   sqrt(%pi)
(%i5) bessel_y(3/2,z);
                                        sin(z)    cos(z)
                    sqrt(2) sqrt(z) ((- ------) - ------)
                                          z          2
                                                    z
(%o5)               -------------------------------------
                                  sqrt(%pi)
(%i6) bessel_i(3/2,z);
                                      cosh(z)   sinh(z)
                     sqrt(2) sqrt(z) (------- - -------)
                                         z         2
                                                  z
(%o6)                -----------------------------------
                                  sqrt(%pi)
(%i7) bessel_k(3/2,z);
                                      1        - z
                           sqrt(%pi) (- + 1) %e
                                      z
(%o7)                      -----------------------
                               sqrt(2) sqrt(z)

Function: scaled_bessel_i (v, z)

The scaled modified Bessel function of the first kind of order v and argument z. That is,

$$ {\rm scaled\_bessel\_i}(v,z) = e^{-|z|} I_v(z). $$

This function is particularly useful for calculating \(I_v(z)\) for large z, which is large. However, maxima does not otherwise know much about this function. For symbolic work, it is probably preferable to work with the expression exp(-abs(z))*bessel_i(v, z).

Function: scaled_bessel_i0 (z)

Identical to scaled_bessel_i(0,z).

Function: scaled_bessel_i1 (z)

Identical to scaled_bessel_i(1,z).

Function: %s [u,v] (z)

Lommel’s little \(s_{\mu,\nu}(z)\) function. (DLMF 11.9.E3)(G&R 8.570.1).

This Lommel function is the particular solution of the inhomogeneous Bessel differential equation:

$$ {d^2\over dz^2} + {1\over z}{dw\over dz} + \left(1-{\nu^2\over z^2}\right) w = z^{\mu-1} $$

This can be defined by the series

$$ s_{\mu,\nu}(z) = z^{\mu+1}\sum_{k=0}^{\infty} (-1)^k {z^{2k}\over a_{k+1}(\mu, \nu)} $$

where

$$ a_k(\mu,\nu) = \prod_{m=1}^k \left(\left(\mu + 2m-1\right)^2-\nu^2\right) = 4^k\left(\mu-\nu+1\over 2\right)_k \left(\mu+\nu+1\over 2\right)_k $$
Function: slommel [u,v] (z)

Lommel’s big \(S_{\mu,\nu}(z)\) function. (DLMF 11.9.E5)(G&R 8.570.2).

Lommels big S function is another particular solution of the inhomogeneous Bessel differential equation (see %s) defined for all values of \(\mu\) and \(\nu\), where

$$ \eqalign{ S_{\mu,\nu}(z) = s_{\mu,\nu}(z) + 2^{\mu-1} & \Gamma\left({\mu\over 2} + {\nu\over 2} + {1\over 2}\right) \Gamma\left({\mu\over 2} - {\nu\over 2} + {1\over 2}\right) \cr & \times \left(\sin\left({(\mu-\nu)\pi\over 2}\right) J_{\nu}(z) - \cos\left({(\mu-\nu)\pi\over 2}\right) Y_{\nu}(z)\right) } $$

When \(\mu\pm \nu\)) is an odd negative integer, the limit must be used.


Next: , Previous: Bessel Functions, Up: Special Functions   [Contents][Index]

14.3 Airy Functions

The Airy functions \({\rm Ai}(x)\) and \({\rm Bi}(x)\) are defined in Abramowitz and Stegun, Handbook of Mathematical Functions, A&S Section 10.4 and DLMF 9.

The Airy differential equation is:

$$ {d^2 y\over dx^2} - xy = 0 $$

The numerically satisfactory pair of solutions (DLMF 9.2#T1) on the real line are \(y = {\rm Ai}(x)\) and \(y = {\rm Bi}(x).\)

These two solutions are oscillatory for x < 0. \({\rm Ai}(x)\) is the solution subject to the condition that \(y\rightarrow 0\) as \(x\rightarrow +\infty,\) and \({\rm Bi}(x)\) is the second solution with the same amplitude as \({\rm Ai}(x)\) as \(x\rightarrow-\infty\) which differs in phase by \(\pi/2.\) Also, \({\rm Bi}(x)\) is unbounded as \(x\rightarrow +\infty.\)

If the argument x is a real or complex floating point number, the numerical value of the function is returned.

Function: airy_ai (x)

The Airy function \({\rm Ai}(x).\) See A&S eqn 10.4.2 and DLMF 9.

See also airy_bi, airy_dai, and airy_dbi.

Function: airy_dai (x)

The derivative of the Airy function \({\rm Ai}(x)\):

$$ {\rm airy\_dai}(x) = {d\over dx}{\rm Ai}(x) $$

See airy_ai.

Function: airy_bi (x)

The Airy function \({\rm Bi}(x)\). See A&S eqn 10.4.3 and DLMF 9.

See airy_ai, and airy_dbi.

Function: airy_dbi (x)

The derivative of the Airy function \({\rm Bi}(x)\):

$$ {\rm airy\_dbi}(x) = {d\over dx}{\rm Bi}(x) $$

See airy_ai, and airy_bi.


Next: , Previous: Airy Functions, Up: Special Functions   [Contents][Index]

14.4 Gamma and Factorial Functions

The gamma function and the related beta, psi and incomplete gamma functions are defined in Abramowitz and Stegun, Handbook of Mathematical Functions, Chapter 6.

Function: bffac (expr, n)

Bigfloat version of the factorial (shifted gamma) function. The second argument is how many digits to retain and return, it’s a good idea to request a couple of extra.

(%i1) bffac(1/2,16);
(%o1)                        8.862269254527584b-1
(%i2) (1/2)!,numer;
(%o2)                          0.886226925452758
(%i3) bffac(1/2,32);
(%o3)                 8.862269254527580136490837416707b-1
Function: bfpsi (n, z, fpprec)
Function: bfpsi0 (z, fpprec)

bfpsi is the polygamma function of real argument z and integer order n. See psi for further information. bfpsi0 is the digamma function. bfpsi0(z, fpprec) is equivalent to bfpsi(0, z, fpprec).

These functions return bigfloat values. fpprec is the bigfloat precision of the return value.

(%i1) bfpsi0(1/3, 15);
(%o1)                        - 3.13203378002081b0
(%i2) bfpsi0(1/3, 32);
(%o2)                - 3.1320337800208063229964190742873b0
(%i3) bfpsi(0,1/3,32);
(%o3)                - 3.1320337800208063229964190742873b0
(%i4) psi[0](1/3);
                          3 log(3)       %pi
(%o4)                  (- --------) - --------- - %gamma
                             2        2 sqrt(3)
(%i5) float(%);
(%o5)                         - 3.132033780020806
Function: cbffac (z, fpprec)

Complex bigfloat factorial.

load ("bffac") loads this function.

(%i1) cbffac(1+%i,16);
(%o1)           3.430658398165453b-1 %i + 6.529654964201666b-1
(%i2) (1+%i)!,numer;
(%o2)             0.3430658398165453 %i + 0.6529654964201667
Function: gamma (z)

The basic definition of the gamma function (DLMF 5.2.E1 and A&S eqn 6.1.1) is

$$ \Gamma\left(z\right)=\int_{0}^{\infty }{t^{z-1}\,e^ {- t }\;dt} $$

Maxima simplifies gamma for positive integer and positive and negative rational numbers. For half integral values the result is a rational number times \(\sqrt{\pi}\). The simplification for integer values is controlled by factlim. For integers greater than factlim the numerical result of the factorial function, which is used to calculate gamma, will overflow. The simplification for rational numbers is controlled by gammalim to avoid internal overflow. See factlim and gammalim.

For negative integers gamma is not defined.

Maxima can evaluate gamma numerically for real and complex values in float and bigfloat precision.

gamma has mirror symmetry.

When gamma_expand is true, Maxima expands gamma for arguments z+n and z-n where n is an integer.

Maxima knows the derivative of gamma.

Examples:

Simplification for integer, half integral, and rational numbers:

(%i1) map('gamma,[1,2,3,4,5,6,7,8,9]);
(%o1)        [1, 1, 2, 6, 24, 120, 720, 5040, 40320]
(%i2) map('gamma,[1/2,3/2,5/2,7/2]);
                    sqrt(%pi)  3 sqrt(%pi)  15 sqrt(%pi)
(%o2)   [sqrt(%pi), ---------, -----------, ------------]
                        2           4            8
(%i3) map('gamma,[2/3,5/3,7/3]);
                                  2           1
                          2 gamma(-)  4 gamma(-)
                      2           3           3
(%o3)          [gamma(-), ----------, ----------]
                      3       3           9

Numerical evaluation for real and complex values:

(%i4) map('gamma,[2.5,2.5b0]);
(%o4)     [1.329340388179137, 1.3293403881791370205b0]
(%i5) map('gamma,[1.0+%i,1.0b0+%i]);
(%o5) [0.498015668118356 - .1549498283018107 %i, 
          4.9801566811835604272b-1 - 1.5494982830181068513b-1 %i]

gamma has mirror symmetry:

(%i6) declare(z,complex)$
(%i7) conjugate(gamma(z));
(%o7)                  gamma(conjugate(z))

Maxima expands gamma(z+n) and gamma(z-n), when gamma_expand is true:

(%i8) gamma_expand:true$

(%i9) [gamma(z+1),gamma(z-1),gamma(z+2)/gamma(z+1)];
                               gamma(z)
(%o9)             [z gamma(z), --------, z + 1]
                                z - 1

The derivative of gamma:

(%i10) diff(gamma(z),z);
(%o10)                  psi (z) gamma(z)
                           0

See also makegamma.

The Euler-Mascheroni constant is %gamma.

Function: log_gamma (z)

The natural logarithm of the gamma function.

(%i1) gamma(6);
(%o1)                                 120
(%i2) log_gamma(6);
(%o2)                              log(120)
(%i3) log_gamma(0.5);
(%o3)                         0.5723649429247004
Function: gamma_incomplete_lower (a, z)

The lower incomplete gamma function (DLMF 8.2.E1 and A&S eqn 6.5.2):

$$ \gamma\left(a , z\right)=\int_{0}^{z}{t^{a-1}\,e^ {- t }\;dt} $$

See also gamma_incomplete (upper incomplete gamma function).

Function: gamma_incomplete (a, z)

The incomplete upper gamma function (DLMF 8.2.E2 and A&S eqn 6.5.3):

$$ \Gamma\left(a , z\right)=\int_{z}^{\infty }{t^{a-1}\,e^ {- t }\;dt} $$

See also gamma_expand for controlling how gamma_incomplete is expressed in terms of elementary functions and erfc.

Also see the related functions gamma_incomplete_regularized and gamma_incomplete_generalized.

Function: gamma_incomplete_regularized (a, z)

The regularized incomplete upper gamma function (DLMF 8.2.E4):

$$ Q\left(a , z\right)={{\Gamma\left(a , z\right)}\over{\Gamma\left(a\right)}} $$

See also gamma_expand for controlling how gamma_incomplete is expressed in terms of elementary functions and erfc.

Also see gamma_incomplete.

Function: gamma_incomplete_generalized (a, z1, z1)

The generalized incomplete gamma function.

$$ \Gamma\left(a , z_{1}, z_{2}\right)=\int_{z_{1}}^{z_{2}}{t^{a-1}\,e^ {- t }\;dt} $$

Also see gamma_incomplete and gamma_incomplete_regularized.

Option variable: gamma_expand

Default value: false

gamma_expand controls expansion of gamma_incomplete. When gamma_expand is true, gamma_incomplete(v,z) is expanded in terms of z, exp(z), and gamma_incomplete or erfc when possible.

(%i1) gamma_incomplete(2,z);
(%o1)                       gamma_incomplete(2, z)
(%i2) gamma_expand:true;
(%o2)                                true
(%i3) gamma_incomplete(2,z);
                                           - z
(%o3)                            (z + 1) %e
(%i4) gamma_incomplete(3/2,z);
                              - z   sqrt(%pi) erfc(sqrt(z))
(%o4)               sqrt(z) %e    + -----------------------
                                               2
(%i5) gamma_incomplete(4/3,z);
                                                    1
                                   gamma_incomplete(-, z)
                       1/3   - z                    3
(%o5)                 z    %e    + ----------------------
                                             3
(%i6) gamma_incomplete(a+2,z);
             a               - z
(%o6)       z  (z + a + 1) %e    + a (a + 1) gamma_incomplete(a, z)
(%i7) gamma_incomplete(a-2, z);
        gamma_incomplete(a, z)    a - 2         z            1      - z
(%o7)   ---------------------- - z      (--------------- + -----) %e
           (1 - a) (2 - a)               (a - 2) (a - 1)   a - 2

Option variable: gammalim

Default value: 10000

gammalim controls simplification of the gamma function for integral and rational number arguments. If the absolute value of the argument is not greater than gammalim, then simplification will occur. Note that the factlim switch controls simplification of the result of gamma of an integer argument as well.

Function: makegamma (expr)

Transforms instances of binomial, factorial, and beta functions in expr into gamma functions.

See also makefact.

(%i1) makegamma(binomial(n,k));
                                 gamma(n + 1)
(%o1)                    -----------------------------
                         gamma(k + 1) gamma(n - k + 1)
(%i2) makegamma(x!);
(%o2)                            gamma(x + 1)
(%i3) makegamma(beta(a,b));
                               gamma(a) gamma(b)
(%o3)                          -----------------
                                 gamma(b + a)
Function: beta (a, b)

The beta function is defined as $$ {\rm B}(a, b) = {{\Gamma(a) \Gamma(b)}\over{\Gamma(a+b)}} $$

(DLMF 5.12.E1 and A&S eqn 6.2.1).

Maxima simplifies the beta function for positive integers and rational numbers, which sum to an integer. When beta_args_sum_to_integer is true, Maxima simplifies also general expressions which sum to an integer.

For a or b equal to zero the beta function is not defined.

In general the beta function is not defined for negative integers as an argument. The exception is for a=-n, n a positive integer and b a positive integer with b<=n, it is possible to define an analytic continuation. Maxima gives for this case a result.

When beta_expand is true, expressions like beta(a+n,b) and beta(a-n,b) or beta(a,b+n) and beta(a,b-n) with n an integer are simplified.

Maxima can evaluate the beta function for real and complex values in float and bigfloat precision. For numerical evaluation Maxima uses log_gamma:

           - log_gamma(b + a) + log_gamma(b) + log_gamma(a)
         %e

Maxima knows that the beta function is symmetric and has mirror symmetry.

Maxima knows the derivatives of the beta function with respect to a or b.

To express the beta function as a ratio of gamma functions see makegamma.

Examples:

Simplification, when one of the arguments is an integer:

(%i1) [beta(2,3),beta(2,1/3),beta(2,a)];
                               1   9      1
(%o1)                         [--, -, ---------]
                               12  4  a (a + 1)

Simplification for two rational numbers as arguments which sum to an integer:

(%i2) [beta(1/2,5/2),beta(1/3,2/3),beta(1/4,3/4)];
                          3 %pi   2 %pi
(%o2)                    [-----, -------, sqrt(2) %pi]
                            8    sqrt(3)

When setting beta_args_sum_to_integer to true more general expression are simplified, when the sum of the arguments is an integer:

(%i3) beta_args_sum_to_integer:true$
(%i4) beta(a+1,-a+2);
                                %pi (a - 1) a
(%o4)                         ------------------
                              2 sin(%pi (2 - a))

The possible results, when one of the arguments is a negative integer:

(%i5) [beta(-3,1),beta(-3,2),beta(-3,3)];
                                    1  1    1
(%o5)                            [- -, -, - -]
                                    3  6    3

beta(a+n,b) or beta(a-n,b) with n an integer simplifies when beta_expand is true:

(%i6) beta_expand:true$
(%i7) [beta(a+1,b),beta(a-1,b),beta(a+1,b)/beta(a,b+1)];
                    a beta(a, b)  beta(a, b) (b + a - 1)  a
(%o7)              [------------, ----------------------, -]
                       b + a              a - 1           b

Beta is not defined, when one of the arguments is zero:

(%i7) beta(0,b);
beta: expected nonzero arguments; found 0, b
 -- an error.  To debug this try debugmode(true);

Numerical evaluation for real and complex arguments in float or bigfloat precision:

(%i8) beta(2.5,2.3);
(%o8) .08694748611299981

(%i9) beta(2.5,1.4+%i);
(%o9) 0.0640144950796695 - .1502078053286415 %i

(%i10) beta(2.5b0,2.3b0);
(%o10) 8.694748611299969b-2

(%i11) beta(2.5b0,1.4b0+%i);
(%o11) 6.401449507966944b-2 - 1.502078053286415b-1 %i

Beta is symmetric and has mirror symmetry:

(%i14) beta(a,b)-beta(b,a);
(%o14)                                 0
(%i15) declare(a,complex,b,complex)$
(%i16) conjugate(beta(a,b));
(%o16)                 beta(conjugate(a), conjugate(b))

The derivative of the beta function wrt a:

(%i17) diff(beta(a,b),a);
(%o17)               - beta(a, b) (psi (b + a) - psi (a))
                                      0             0
Function: beta_incomplete (a, b, z)

The basic definition of the incomplete beta function (DLMF 8.17.E1 and A&S eqn 6.6.1) is

$$ {\rm B}_z(a,b) = \int_0^z t^{a-1}(1-t)^{b-1}\; dt $$

This definition is possible for \({\rm Re}(a) > 0\) and \({\rm Re}(b) > 0\) and \(|z| < 1\). For other values the incomplete beta function can be defined through a generalized hypergeometric function:

   gamma(a) hypergeometric_generalized([a, 1 - b], [a + 1], z) z

(See https://functions.wolfram.com/GammaBetaErf/Beta3/ for a complete definition of the incomplete beta function.)

For negative integers a = -n and positive integers b=m with \(m \le n\) the incomplete beta function is defined through

$$ z^{n-1}\sum_{k=0}^{m-1} {{(1-m)_k z^k} \over {k! (n-k)}} $$

Maxima uses this definition to simplify beta_incomplete for a a negative integer.

For a a positive integer, beta_incomplete simplifies for any argument b and z and for b a positive integer for any argument a and z, with the exception of a a negative integer.

For z=0 and \({\rm Re}(a) > 0\), beta_incomplete has the specific value zero. For z=1 and \({\rm Re}(b) > 0\), beta_incomplete simplifies to the beta function beta(a,b).

Maxima evaluates beta_incomplete numerically for real and complex values in float or bigfloat precision. For the numerical evaluation an expansion of the incomplete beta function in continued fractions is used.

When the option variable beta_expand is true, Maxima expands expressions like beta_incomplete(a+n,b,z) and beta_incomplete(a-n,b,z) where n is a positive integer.

Maxima knows the derivatives of beta_incomplete with respect to the variables a, b and z and the integral with respect to the variable z.

Examples:

Simplification for a a positive integer:

(%i1) beta_incomplete(2,b,z);
                                       b
                            1 - (1 - z)  (b z + 1)
(%o1)                       ----------------------
                                  b (b + 1)

Simplification for b a positive integer:

(%i2) beta_incomplete(a,2,z);
                                               a
                              (a (1 - z) + 1) z
(%o2)                         ------------------
                                  a (a + 1)

Simplification for a and b a positive integer:

(%i3) beta_incomplete(3,2,z);
                                               3
                              (3 (1 - z) + 1) z
(%o3)                         ------------------
                                      12

a is a negative integer and b<=(-a), Maxima simplifies:

(%i4) beta_incomplete(-3,1,z);
                                       1
(%o4)                              - ----
                                        3
                                     3 z

For the specific values z=0 and z=1, Maxima simplifies:

(%i5) assume(a>0,b>0)$
(%i6) beta_incomplete(a,b,0);
(%o6)                                 0
(%i7) beta_incomplete(a,b,1);
(%o7)                            beta(a, b)

Numerical evaluation in float or bigfloat precision:

(%i8) beta_incomplete(0.25,0.50,0.9);
(%o8)                          4.594959440269333
(%i9)  fpprec:25$
(%i10) beta_incomplete(0.25,0.50,0.9b0);
(%o10)                    4.594959440269324086971203b0

For abs(z)>1 beta_incomplete returns a complex result:

(%i11) beta_incomplete(0.25,0.50,1.7);
(%o11)              5.244115108584249 - 1.45518047787844 %i

Results for more general complex arguments:

(%i14) beta_incomplete(0.25+%i,1.0+%i,1.7+%i);
(%o14)             2.726960675662536 - .3831175704269199 %i
(%i15) beta_incomplete(1/2,5/4*%i,2.8+%i);
(%o15)             13.04649635168716 %i - 5.802067956270001
(%i16) 

Expansion, when beta_expand is true:

(%i23) beta_incomplete(a+1,b,z),beta_expand:true;
                                                       b  a
                   a beta_incomplete(a, b, z)   (1 - z)  z
(%o23)             -------------------------- - -----------
                             b + a                 b + a

(%i24) beta_incomplete(a-1,b,z),beta_expand:true;
                                                       b  a - 1
       beta_incomplete(a, b, z) (- b - a + 1)   (1 - z)  z
(%o24) -------------------------------------- - ---------------
                       1 - a                         1 - a

Derivative and integral for beta_incomplete:

(%i34) diff(beta_incomplete(a, b, z), z);
                              b - 1  a - 1
(%o34)                 (1 - z)      z
(%i35) integrate(beta_incomplete(a, b, z), z);
              b  a
       (1 - z)  z
(%o35) ----------- + beta_incomplete(a, b, z) z
          b + a
                                       a beta_incomplete(a, b, z)
                                     - --------------------------
                                                 b + a
(%i36) factor(diff(%, z));
(%o36)              beta_incomplete(a, b, z)
Function: beta_incomplete_regularized (a, b, z)

The regularized incomplete beta function (DLMF 8.17.E2 and A&S eqn 6.6.2), defined as

$$ I_z(a,b) = {{\rm B}_z(a,b)\over {\rm B}(a,b)} $$

As for beta_incomplete this definition is not complete. See https://functions.wolfram.com/GammaBetaErf/BetaRegularized/ for a complete definition of beta_incomplete_regularized.

beta_incomplete_regularized simplifies a or b a positive integer.

For z=0 and \({\rm Re}(a)>0\), beta_incomplete_regularized has the specific value 0. For z=1 and \({\rm Re}(b) > 0\), beta_incomplete_regularized simplifies to 1.

Maxima can evaluate beta_incomplete_regularized for real and complex arguments in float and bigfloat precision.

When beta_expand is true, Maxima expands beta_incomplete_regularized for arguments a+n or a-n, where n is an integer.

Maxima knows the derivatives of beta_incomplete_regularized with respect to the variables a, b, and z and the integral with respect to the variable z.

Examples:

Simplification for a or b a positive integer:

(%i1) beta_incomplete_regularized(2,b,z);
                                       b
(%o1)                       1 - (1 - z)  (b z + 1)

(%i2) beta_incomplete_regularized(a,2,z);
                                               a
(%o2)                         (a (1 - z) + 1) z

(%i3) beta_incomplete_regularized(3,2,z);
                                               3
(%o3)                         (3 (1 - z) + 1) z

For the specific values z=0 and z=1, Maxima simplifies:

(%i4) assume(a>0,b>0)$
(%i5) beta_incomplete_regularized(a,b,0);
(%o5)                                 0
(%i6) beta_incomplete_regularized(a,b,1);
(%o6)                                 1

Numerical evaluation for real and complex arguments in float and bigfloat precision:

(%i7) beta_incomplete_regularized(0.12,0.43,0.9);
(%o7)                         .9114011367359802
(%i8) fpprec:32$
(%i9) beta_incomplete_regularized(0.12,0.43,0.9b0);
(%o9)               9.1140113673598075519946998779975b-1
(%i10) beta_incomplete_regularized(1+%i,3/3,1.5*%i);
(%o10)             .2865367499935403 %i - 0.122995963334684
(%i11) fpprec:20$
(%i12) beta_incomplete_regularized(1+%i,3/3,1.5b0*%i);
(%o12)      2.8653674999354036142b-1 %i - 1.2299596333468400163b-1

Expansion, when beta_expand is true:

(%i13) beta_incomplete_regularized(a+1,b,z);
                                                     b  a
                                              (1 - z)  z
(%o13) beta_incomplete_regularized(a, b, z) - ------------
                                              a beta(a, b)
(%i14) beta_incomplete_regularized(a-1,b,z);
(%o14) beta_incomplete_regularized(a, b, z)
                                                     b  a - 1
                                              (1 - z)  z
                                         - ----------------------
                                           beta(a, b) (b + a - 1)

The derivative and the integral wrt z:

(%i15) diff(beta_incomplete_regularized(a,b,z),z);
                              b - 1  a - 1
                       (1 - z)      z
(%o15)                 -------------------
                           beta(a, b)
(%i16) integrate(beta_incomplete_regularized(a,b,z),z);
(%o16) beta_incomplete_regularized(a, b, z) z
                                                           b  a
                                                    (1 - z)  z
          a (beta_incomplete_regularized(a, b, z) - ------------)
                                                    a beta(a, b)
        - -------------------------------------------------------
                                   b + a
Function: beta_incomplete_generalized (a, b, z1, z2)

The basic definition of the generalized incomplete beta function is

$$ \int_{z_1}^{z_2} t^{a-1}(1-t)^{b-1}\; dt $$

Maxima simplifies beta_incomplete_regularized for a and b a positive integer.

For \({\rm Re}(a) > 0\) and \(z_1 = 0\) or \(z_2 = 0\), Maxima simplifies beta_incomplete_generalized to beta_incomplete. For \({\rm Re}(b) > 0\) and \(z_1 = 1\) or \(z_2 = 1\), Maxima simplifies to an expression with beta and beta_incomplete.

Maxima evaluates beta_incomplete_regularized for real and complex values in float and bigfloat precision.

When beta_expand is true, Maxima expands beta_incomplete_generalized for a+n and a-n, n a positive integer.

Maxima knows the derivative of beta_incomplete_generalized with respect to the variables a, b, z1, and z2 and the integrals with respect to the variables z1 and z2.

Examples:

Maxima simplifies beta_incomplete_generalized for a and b a positive integer:

(%i1) beta_incomplete_generalized(2,b,z1,z2);
                   b                      b
           (1 - z1)  (b z1 + 1) - (1 - z2)  (b z2 + 1)
(%o1)      -------------------------------------------
                            b (b + 1)
(%i2) beta_incomplete_generalized(a,2,z1,z2);
                              a                      a
           (a (1 - z2) + 1) z2  - (a (1 - z1) + 1) z1
(%o2)      -------------------------------------------
                            a (a + 1)
(%i3) beta_incomplete_generalized(3,2,z1,z2);
              2      2                       2      2
      (1 - z1)  (3 z1  + 2 z1 + 1) - (1 - z2)  (3 z2  + 2 z2 + 1)
(%o3) -----------------------------------------------------------
                                  12

Simplification for specific values z1=0, z2=0, z1=1, or z2=1:

(%i4) assume(a > 0, b > 0)$
(%i5) beta_incomplete_generalized(a,b,z1,0);
(%o5)                    - beta_incomplete(a, b, z1)

(%i6) beta_incomplete_generalized(a,b,0,z2);
(%o6)                    - beta_incomplete(a, b, z2)

(%i7) beta_incomplete_generalized(a,b,z1,1);
(%o7)              beta(a, b) - beta_incomplete(a, b, z1)

(%i8) beta_incomplete_generalized(a,b,1,z2);
(%o8)              beta_incomplete(a, b, z2) - beta(a, b)

Numerical evaluation for real arguments in float or bigfloat precision:

(%i9) beta_incomplete_generalized(1/2,3/2,0.25,0.31);
(%o9)                        .09638178086368676

(%i10) fpprec:32$
(%i10) beta_incomplete_generalized(1/2,3/2,0.25,0.31b0);
(%o10)               9.6381780863686935309170054689964b-2

Numerical evaluation for complex arguments in float or bigfloat precision:

(%i11) beta_incomplete_generalized(1/2+%i,3/2+%i,0.25,0.31);
(%o11)           - .09625463003205376 %i - .003323847735353769
(%i12) fpprec:20$
(%i13) beta_incomplete_generalized(1/2+%i,3/2+%i,0.25,0.31b0);
(%o13)     - 9.6254630032054178691b-2 %i - 3.3238477353543591914b-3

Expansion for a+n or a-n, n a positive integer, when beta_expand is true:

(%i14) beta_expand:true$

(%i15) beta_incomplete_generalized(a+1,b,z1,z2);

               b   a           b   a
       (1 - z1)  z1  - (1 - z2)  z2
(%o15) -----------------------------
                   b + a
                      a beta_incomplete_generalized(a, b, z1, z2)
                    + -------------------------------------------
                                         b + a
(%i16) beta_incomplete_generalized(a-1,b,z1,z2);

       beta_incomplete_generalized(a, b, z1, z2) (- b - a + 1)
(%o16) -------------------------------------------------------
                                1 - a
                                    b   a - 1           b   a - 1
                            (1 - z2)  z2      - (1 - z1)  z1
                          - -------------------------------------
                                            1 - a

Derivative wrt the variable z1 and integrals wrt z1 and z2:

(%i17) diff(beta_incomplete_generalized(a,b,z1,z2),z1);
                               b - 1   a - 1
(%o17)               - (1 - z1)      z1
(%i18) integrate(beta_incomplete_generalized(a,b,z1,z2),z1);
(%o18) beta_incomplete_generalized(a, b, z1, z2) z1
                                  + beta_incomplete(a + 1, b, z1)
(%i19) integrate(beta_incomplete_generalized(a,b,z1,z2),z2);
(%o19) beta_incomplete_generalized(a, b, z1, z2) z2
                                  - beta_incomplete(a + 1, b, z2)
Option variable: beta_expand

Default value: false

When beta_expand is true, beta(a,b) and related functions are expanded for arguments like a+n or a-n, where n is an integer.

See beta for examples.

Option variable: beta_args_sum_to_integer

Default value: false

When beta_args_sum_to_integer is true, Maxima simplifies beta(a,b), when the arguments a and b sum to an integer.

See beta for examples.

Function: psi [n](x)

psi[n](x) is the polygamma function (DLMF 5.2E2, DLMF 5.15, A&S eqn 6.3.1 and A&S eqn 6.4.1) defined by $$ \psi^{(n)}(x) = {d^{n+1}\over{dx^{n+1}}} \log\Gamma(x) $$

Thus, psi[0](x) is the first derivative, psi[1](x) is the second derivative, etc.

Maxima can compute some exact values for rational args as well for float and bfloat args. Several variables control what range of rational args \(\psi^{(n)}(x)\)) will return an exact value, if possible. See maxpsiposint, maxpsinegint, maxpsifracnum, and maxpsifracdenom. That is, x must lie between maxpsinegint and maxpsiposint. If the absolute value of the fractional part of x is rational and has a numerator less than maxpsifracnum and has a denominator less than maxpsifracdenom, \(\psi^{(0)}(x)\) will return an exact value.

The function bfpsi in the bffac package can compute numerical values.

(%i1) psi[0](.25);
(%o1)                        - 4.227453533376265
(%i2) psi[0](1/4);
                                        %pi
(%o2)                    (- 3 log(2)) - --- - %gamma
                                         2
(%i3) float(%);
(%o3)                        - 4.227453533376265
(%i4) psi[2](0.75);
(%o4)                        - 5.30263321633764
(%i5) psi[2](3/4);
                                   1         3
(%o5)                         psi (-) + 4 %pi
                                 2 4
(%i6) float(%);
(%o6)                        - 5.30263321633764
Option variable: maxpsiposint

Default value: 20

maxpsiposint is the largest positive integer value for which \(\psi^{(n)}(m)\) gives an exact value for rational x.

(%i1) psi[0](20);
                             275295799
(%o1)                        --------- - %gamma
                             77597520
(%i2) psi[0](21);
(%o2)                             psi (21)
                                     0
(%i3) psi[2](20);
                      1683118856778495358491487
(%o3)              2 (------------------------- - zeta(3))
                      1401731326612193601024000
(%i4) psi[2](21);
(%o4)                            psi (21)
                                      2

Option variable: maxpsinegint

Default value: -10

maxpsinegint is the most negative value for which \(\psi^{(0)}(x)\) will try to compute an exact value for rational x. That is if x is less than maxpsinegint, \(\psi^{(n)}(x)\) will not return simplified answer, even if it could.

(%i1) psi[0](-100/9);
                                        100
(%o1)                            psi (- ---)
                                    0    9
(%i2) psi[0](-100/11);
                         100 %pi         1     5231385863539
(%o2)            %pi cot(-------) + psi (--) + -------------
                           11          0 11    381905105400

(%i3) psi[2](-100/9);
                                        100
(%o3)                            psi (- ---)
                                    2    9
(%i4) psi[2](-100/11);
           3     100 %pi     2 100 %pi         1
(%o4) 2 %pi  cot(-------) csc (-------) + psi (--)
                   11            11          2 11
                                         74191313259470963498957651385614962459
                                       + --------------------------------------
                                          27850718060013605318710152732000000
Option variable: maxpsifracnum

Default value: 6

Let x be a rational number of the form p/q. If p is greater than maxpsifracnum, then \(\psi^{(0)}(x)\) will not try to return a simplified value.

(%i1) psi[0](3/4);
                                        %pi
(%o1)                    (- 3 log(2)) + --- - %gamma
                                         2
(%i2) psi[2](3/4);
                                   1         3
(%o2)                         psi (-) + 4 %pi
                                 2 4
(%i3) maxpsifracnum:2;
(%o3)                                 2
(%i4) psi[0](3/4);
                                        3
(%o4)                              psi (-)
                                      0 4
(%i5) psi[2](3/4);
                                   1         3
(%o5)                         psi (-) + 4 %pi
                                 2 4
Option variable: maxpsifracdenom

Default value: 6

Let x be a rational number of the form p/q. If q is greater than maxpsifracdenom, then \(\psi^{(0)}(x)\) will not try to return a simplified value.

(%i1) psi[0](3/4);
                                        %pi
(%o1)                    (- 3 log(2)) + --- - %gamma
                                         2
(%i2) psi[2](3/4);
                                   1         3
(%o2)                         psi (-) + 4 %pi
                                 2 4
(%i3) maxpsifracdenom:2;
(%o3)                                 2
(%i4) psi[0](3/4);
                                        3
(%o4)                              psi (-)
                                      0 4
(%i5) psi[2](3/4);
                                   1         3
(%o5)                         psi (-) + 4 %pi
                                 2 4
Function: makefact (expr)

Transforms instances of binomial, gamma, and beta functions in expr into factorials.

See also makegamma.

(%i1) makefact(binomial(n,k));
                                      n!
(%o1)                             -----------
                                  k! (n - k)!
(%i2) makefact(gamma(x));
(%o2)                              (x - 1)!
(%i3) makefact(beta(a,b));
                               (a - 1)! (b - 1)!
(%o3)                          -----------------
                                 (b + a - 1)!
Function: numfactor (expr)

Returns the numerical factor multiplying the expression expr, which should be a single term.

content returns the greatest common divisor (gcd) of all terms in a sum.

(%i1) gamma (7/2);
                          15 sqrt(%pi)
(%o1)                     ------------
                               8
(%i2) numfactor (%);
                               15
(%o2)                          --
                               8

Next: , Previous: Gamma and Factorial Functions, Up: Special Functions   [Contents][Index]

14.5 Exponential Integrals

The Exponential Integral and related functions are defined in Abramowitz and Stegun, Handbook of Mathematical Functions, A&S Chapter 5.

Function: expintegral_e1 (z)

The Exponential Integral E1(z) defined as

$$ E_1(z) = \int_z^\infty {e^{-t} \over t} dt $$

with \(\left| \arg z \right| < \pi\). (A&S eqn 5.1.1) and (DLMF 6.2E2)

This can be written in terms of other functions. See expintrep for examples.

Function: expintegral_ei (x)

The Exponential Integral Ei(x) defined as

$$ Ei(x) = - -\kern-10.5pt\int_{-x}^\infty {e^{-t} \over t} dt = -\kern-10.5pt\int_{-\infty}^x {e^{t} \over t} dt $$

with x real and x > 0. (A&S eqn 5.1.2) and (DLMF 6.2E5)

This can be written in terms of other functions. See expintrep for examples.

Function: expintegral_li (x)

The Exponential Integral li(x) defined as

$$ li(x) = -\kern-10.5pt\int_0^x {dt \over \ln t} $$

with x real and x > 1. (A&S eqn 5.1.3) and (DLMF 6.2E8)

This can be written in terms of other functions. See expintrep for examples.

Function: expintegral_e (n,z)

The Exponential Integral En(z) (A&S eqn 5.1.4) defined as

$$ E_n(z) = \int_1^\infty {e^{-zt} \over t^n} dt $$

with \({\rm Re}(z) > 1\) and n a non-negative integer.

For half-integral orders, this can be written in terms of erfc or erf. See expintexpand for examples.

Function: expintegral_si (z)

The Exponential Integral Si(z) (A&S eqn 5.2.1 and DLMF 6.2#E9) defined as

$$ {\rm Si}(z) = \int_0^z {\sin t \over t} dt $$

This can be written in terms of other functions. See expintrep for examples.

Function: expintegral_ci (z)

The Exponential Integral Ci(z) (A&S eqn 5.2.2 and DLMF 6.2#E13) defined as

$$ {\rm Ci}(z) = \gamma + \log z + \int_0^z {{\cos t - 1} \over t} dt $$

with \(|\arg z| < \pi\).

This can be written in terms of other functions. See expintrep for examples.

Function: expintegral_shi (z)

The Exponential Integral Shi(z) (A&S eqn 5.2.3 and DLMF 6.2#E15) defined as

$$ {\rm Shi}(z) = \int_0^z {\sinh t \over t} dt $$

This can be written in terms of other functions. See expintrep for examples.

Function: expintegral_chi (z)

The Exponential Integral Chi(z) (A&S eqn 5.2.4 and DLMF 6.2#E16) defined as

$$ {\rm Chi}(z) = \gamma + \log z + \int_0^z {{\cosh t - 1} \over t} dt $$

with \(|\arg z| < \pi\).

This can be written in terms of other functions. See expintrep for examples.

Option variable: expintrep

Default value: false

Change the representation of one of the exponential integrals, expintegral_e(m, z), expintegral_e1, or expintegral_ei to an equivalent form if possible.

Possible values for expintrep are false, gamma_incomplete, expintegral_e1, expintegral_ei, expintegral_li, expintegral_trig, or expintegral_hyp.

false means that the representation is not changed. Other values indicate the representation is to be changed to use the function specified where expintegral_trig means expintegral_si, expintegral_ci; and expintegral_hyp means expintegral_shi or expintegral_chi.

Here are some examples for expintrep set to gamma_incomplete:

(%i1) expintrep:'gamma_incomplete;
(%o1)                          gamma_incomplete
(%i2) expintegral_e1(z);
(%o2)                       gamma_incomplete(0, z)
(%i3) expintegral_ei(z);
(%o3)            log(z) - log(- z) - gamma_incomplete(0, - z)
(%i4) expintegral_li(z);
(%o4)     log(log(z)) - log(- log(z)) - gamma_incomplete(0, - log(z))
(%i5) expintegral_e(n,z);
                                                   n - 1
(%o5)                  gamma_incomplete(1 - n, z) z
(%i6) expintegral_si(z);
(%o6) (%i ((- log(%i z)) + log(- %i z) - gamma_incomplete(0, %i z)
                                              + gamma_incomplete(0, - %i z)))/2
(%i7) expintegral_ci(z);
(%o7) log(z) - (log(%i z) + log(- %i z) + gamma_incomplete(0, %i z)
                                               + gamma_incomplete(0, - %i z))/2
(%i8) expintegral_shi(z);
      log(z) - log(- z) + gamma_incomplete(0, z) - gamma_incomplete(0, - z)
(%o8) ---------------------------------------------------------------------
                                        2
(%i9) expintegral_chi(z);
(%o9) 
      (- log(z)) + log(- z) + gamma_incomplete(0, z) + gamma_incomplete(0, - z)
    - -------------------------------------------------------------------------
                                          2

For expintrep set to expintegral_e1:

(%i1) expintrep:'expintegral_e1;
(%o1)                           expintegral_e1
(%i2) expintegral_ei(z);
(%o2)               log(z) - log(- z) - expintegral_e1(- z)
(%i3) expintegral_li(z);
(%o3)       log(log(z)) - log(- log(z)) - expintegral_e1(- log(z))
(%i4) expintegral_e(n,z);
(%o4)                         expintegral_e(n, z)
(%i5) expintegral_si(z);
(%o5) (%i ((- log(%i z)) - expintegral_e1(%i z) + log(- %i z)
                                                   + expintegral_e1(- %i z)))/2
(%i6) expintegral_ci(z);
(%o6) log(z)
          log(- %i z) (expintegral_e1(%i z) + expintegral_e1(- %i z)) log(%i z)
        - ---------------------------------------------------------------------
                                            2
(%i7) expintegral_shi(z);
          log(z) + expintegral_e1(z) - log(- z) - expintegral_e1(- z)
(%o7)     -----------------------------------------------------------
                                       2
(%i8) expintegral_chi(z);
         (- log(z)) + expintegral_e1(z) + log(- z) + expintegral_e1(- z)
(%o8)  - ---------------------------------------------------------------
                                        2

For expintrep set to expintegral_ei:

(%i1) expintrep:'expintegral_ei;
(%o1)                           expintegral_ei
(%i2) expintegral_e1(z);
                                          1
                         log(- z) - log(- -)
                                          z
(%o2)       (- log(z)) + ------------------- - expintegral_ei(- z)
                                  2
(%i3) expintegral_ei(z);
(%o3)                          expintegral_ei(z)
(%i4) expintegral_li(z);
(%o4)                       expintegral_ei(log(z))
(%i5) expintegral_e(n,z);
(%o5)                         expintegral_e(n, z)
(%i6) expintegral_si(z);
(%o6) (%i (log(%i z) + 2 (expintegral_ei(- %i z) - expintegral_ei(%i z))
                                                            %i          %i
                                        - log(- %i z) + log(--) - log(- --)))/4
                                                            z           z
(%i7) expintegral_ci(z);
(%o7) ((- log(%i z)) + 2 (expintegral_ei(%i z) + expintegral_ei(- %i z))
                                                    %i          %i
                                - log(- %i z) + log(--) + log(- --))/4 + log(z)
                                                    z           z
(%i8) expintegral_shi(z);
(%o8) ((- 2 log(z)) + 2 (expintegral_ei(z) - expintegral_ei(- z)) + log(- z)
                                                                          1
                                                                  - log(- -))/4
                                                                          z
(%i9) expintegral_chi(z);
(%o9) 
                                                                             1
   2 log(z) + 2 (expintegral_ei(z) + expintegral_ei(- z)) - log(- z) + log(- -)
                                                                             z
   ----------------------------------------------------------------------------
                                        4

For expintrep set to expintegral_li:

(%i1) expintrep:'expintegral_li;
(%o1)                           expintegral_li
(%i2) expintegral_e1(z);
                                                                 1
                                                log(- z) - log(- -)
                               - z                               z
(%o2)      (- expintegral_li(%e   )) - log(z) + -------------------
                                                         2
(%i3) expintegral_ei(z);
                                               z
(%o3)                         expintegral_li(%e )
(%i4) expintegral_li(z);
(%o4)                          expintegral_li(z)
(%i5) expintegral_e(n,z);
(%o5)                         expintegral_e(n, z)
(%i6) expintegral_si(z);
                             %i z                     - %e z    %pi signum(z)
        %i (expintegral_li(%e    ) - expintegral_li(%e      ) - -------------)
                                                                      2
(%o6) - ----------------------------------------------------------------------
                                          2
(%i7) expintegral_ci(z);
                        %i z                     - %i z
       expintegral_li(%e    ) + expintegral_li(%e      )
(%o7)  ------------------------------------------------- - signum(z) + 1
                               2
(%i8) expintegral_shi(z);
                                   z                     - z
                  expintegral_li(%e ) - expintegral_li(%e   )
(%o8)             -------------------------------------------
                                       2
(%i9) expintegral_chi(z);
                                   z                     - z
                  expintegral_li(%e ) + expintegral_li(%e   )
(%o9)             -------------------------------------------
                                       2

For expintrep set to expintegral_trig:

(%i1) expintrep:'expintegral_trig;
(%o1)                          expintegral_trig
(%i2) expintegral_e1(z);
(%o2) log(%i z) - %i expintegral_si(%i z) - expintegral_ci(%i z) - log(z)
(%i3) expintegral_ei(z);
(%o3) (- log(%i z)) - %i expintegral_si(%i z) + expintegral_ci(%i z) + log(z)
(%i4) expintegral_li(z);
(%o4) (- log(%i log(z))) - %i expintegral_si(%i log(z))
                                      + expintegral_ci(%i log(z)) + log(log(z))
(%i5) expintegral_e(n,z);
(%o5)                         expintegral_e(n, z)
(%i6) expintegral_si(z);
(%o6)                          expintegral_si(z)
(%i7) expintegral_ci(z);
(%o7)                          expintegral_ci(z)
(%i8) expintegral_shi(z);
(%o8)                      - %i expintegral_si(%i z)
(%i9) expintegral_chi(z);
(%o9)            (- log(%i z)) + expintegral_ci(%i z) + log(z)

For expintrep set to expintegral_hyp:

(%i1) expintrep:'expintegral_hyp;
(%o1)                           expintegral_hyp
(%i2) expintegral_e1(z);
(%o2)               expintegral_shi(z) - expintegral_chi(z)
(%i3) expintegral_ei(z);
(%o3)               expintegral_shi(z) + expintegral_chi(z)
(%i4) expintegral_li(z);
(%o4)          expintegral_shi(log(z)) + expintegral_chi(log(z))
(%i5) expintegral_e(n,z);
(%o5)                         expintegral_e(n, z)
(%i6) expintegral_si(z);
(%o6)                     - %i expintegral_shi(%i z)
(%i7) expintegral_ci(z);
(%o7)           (- log(%i z)) + expintegral_chi(%i z) + log(z)
(%i8) expintegral_shi(z);
(%o8)                         expintegral_shi(z)
(%i9) expintegral_chi(z);
(%o9)                         expintegral_chi(z)
Option variable: expintexpand

Default value: false

Expand expintegral_e(n,z) for half integral values in terms of erfc or erf and for positive integers in terms of expintegral_ei.

(%i1) expintegral_e(1/2,z);
                                            1
(%o1)                         expintegral_e(-, z)
                                            2
(%i2) expintegral_e(1,z);
(%o2)                         expintegral_e(1, z)
(%i3) expintexpand:true;
(%o3)                                true
(%i4) expintegral_e(1/2,z);
                            sqrt(%pi) erfc(sqrt(z))
(%o4)                       -----------------------
                                    sqrt(z)
(%i5) expintegral_e(1,z);
                               1
                         log(- -) - log(- z)
                               z
(%o5)       (- log(z)) - ------------------- - expintegral_ei(- z)
                                  2

Next: , Previous: Exponential Integrals, Up: Special Functions   [Contents][Index]

14.6 Error Function

The Error function and related functions are defined in Abramowitz and Stegun, Handbook of Mathematical Functions, A&S Chapter 7 and (DLMF 7)

Function: erf (z)

The Error Function erf(z): $$ {\rm erf}\ z = {{2\over \sqrt{\pi}}} \int_0^z e^{-t^2}\, dt $$

(A&S eqn 7.1.1) and (DLMF 7.2.E1).

See also flag erfflag. This can also be expressed in terms of a hypergeometric function. See hypergeometric_representation.

Function: erfc (z)

The Complementary Error Function erfc(z): $$ {\rm erfc}\ z = 1 - {\rm erf}\ z $$

(A&S eqn 7.1.2) and (DLMF 7.2.E2).

This can also be expressed in terms of a hypergeometric function. See hypergeometric_representation.

Function: erfi (z)

The Imaginary Error Function. $$ {\rm erfi}\ z = -i\, {\rm erf}(i z) $$

Function: erf_generalized (z1,z2)

Generalized Error function Erf(z1,z2): $$ {\rm erf}(z_1, z_2) = {{2\over \sqrt{\pi}}} \int_{z_1}^{z_2} e^{-t^2}\, dt $$

This can also be expressed in terms of a hypergeometric function. See hypergeometric_representation.

Function: fresnel_c (z)

The Fresnel Integral

$$ C(z) = \int_0^z \cos\left({\pi \over 2} t^2\right)\, dt $$

(A&S eqn 7.3.1) and (DLMF 7.2.E7).

The simplification \(C(-x) = -C(x)\) is applied when flag `trigsign' is true.

The simplification \(C(ix) = iC(x)\) is applied when flag `%iargs' is true.

See flags erf_representation and hypergeometric_representation.

Function: fresnel_s (z)

The Fresnel Integral $$ S(z) = \int_0^z \sin\left({\pi \over 2} t^2\right)\, dt $$

(A&S eqn 7.3.2) and (DLMF 7.2.E8).

The simplification \(S(-x) = -S(x)\) is applied when flag `trigsign' is true.

The simplification \(S(ix) = iS(x)\) is applied when flag `%iargs' is true.

See flags erf_representation and hypergeometric_representation.

Option variable: erf_representation

Default value: false

erf_representation controls how the error functions are represented. It must be set to one of false, erf, erfc, or erfi. When set to false, the error functions are not modified. When set to erf, all error functions (erfc, erfi, erf_generalized, fresnel_s and fresnel_c) are converted to erf functions. Similary, erfc converts error functions to erfc. Finally erfi converts the functions to erfi.

Converting to erf:

(%i1) erf_representation:erf;
(%o1)                                true
(%i2) erfc(z);
(%o2)                               erfc(z)
(%i3) erfi(z);
(%o3)                               erfi(z)
(%i4) erf_generalized(z1,z2);
(%o4)                          erf(z2) - erf(z1)
(%i5) fresnel_c(z);
                    sqrt(%pi) (%i + 1) z           sqrt(%pi) (1 - %i) z
      (1 - %i) (erf(--------------------) + %i erf(--------------------))
                             2                              2
(%o5) -------------------------------------------------------------------
                                       4
(%i6) fresnel_s(z);
                    sqrt(%pi) (%i + 1) z           sqrt(%pi) (1 - %i) z
      (%i + 1) (erf(--------------------) - %i erf(--------------------))
                             2                              2
(%o6) -------------------------------------------------------------------
                                       4

Converting to erfc:

(%i1) erf_representation:erfc;
(%o1)                                erfc
(%i2) erf(z);
(%o2)                             1 - erfc(z)
(%i3) erfc(z);
(%o3)                               erfc(z)
(%i4) erf_generalized(z1,z2);
(%o4)                         erfc(z1) - erfc(z2)
(%i5) fresnel_s(c);
                         sqrt(%pi) (%i + 1) c
(%o5) ((%i + 1) ((- erfc(--------------------))
                                  2
                                                 sqrt(%pi) (1 - %i) c
                                  - %i (1 - erfc(--------------------)) + 1))/4
                                                          2
(%i6) fresnel_c(c);
                         sqrt(%pi) (%i + 1) c
(%o6) ((1 - %i) ((- erfc(--------------------))
                                  2
                                                 sqrt(%pi) (1 - %i) c
                                  + %i (1 - erfc(--------------------)) + 1))/4
                                                          2

Converting to erfc:

(%i1) erf_representation:erfi;
(%o1)                                erfi
(%i2) erf(z);
(%o2)                           - %i erfi(%i z)
(%i3) erfc(z);
(%o3)                          %i erfi(%i z) + 1
(%i4) erfi(z);
(%o4)                               erfi(z)
(%i5) erf_generalized(z1,z2);
(%o5)                   %i erfi(%i z1) - %i erfi(%i z2)
(%i6) fresnel_s(z);
                            sqrt(%pi) %i (%i + 1) z
(%o6) ((%i + 1) ((- %i erfi(-----------------------))
                                       2
                                                   sqrt(%pi) (1 - %i) %i z
                                            - erfi(-----------------------)))/4
                                                              2
(%i7) fresnel_c(z);
(%o7) 
                   sqrt(%pi) (1 - %i) %i z            sqrt(%pi) %i (%i + 1) z
    (1 - %i) (erfi(-----------------------) - %i erfi(-----------------------))
                              2                                  2
    ---------------------------------------------------------------------------
                                         4
Option variable: hypergeometric_representation

Default value: false

Enables transformation to a Hypergeometric representation for fresnel_s and fresnel_c and other error functions.

(%i1) hypergeometric_representation:true;
(%o1)                                true
(%i2) fresnel_s(z);
                                                      2  4
                                     3    3  7     %pi  z    3
                 %pi hypergeometric([-], [-, -], - -------) z
                                     4    2  4       16
(%o2)            ---------------------------------------------
                                       6
(%i3) fresnel_c(z);
                                                    2  4
                                   1    1  5     %pi  z
(%o3)              hypergeometric([-], [-, -], - -------) z
                                   4    2  4       16
(%i4) erf(z);
                                        1    3      2
                      2 hypergeometric([-], [-], - z ) z
                                        2    2
(%o4)                 ----------------------------------
                                  sqrt(%pi)
(%i5) erfi(z);
                                         1    3    2
                       2 hypergeometric([-], [-], z ) z
                                         2    2
(%o5)                  --------------------------------
                                  sqrt(%pi)
(%i6) erfc(z);
                                          1    3      2
                        2 hypergeometric([-], [-], - z ) z
                                          2    2
(%o6)               1 - ----------------------------------
                                    sqrt(%pi)
(%i7) erf_generalized(z1,z2);
                        1    3       2
      2 hypergeometric([-], [-], - z2 ) z2
                        2    2
(%o7) ------------------------------------
                   sqrt(%pi)
                                                             1    3       2
                                           2 hypergeometric([-], [-], - z1 ) z1
                                                             2    2
                                         - ------------------------------------
                                                        sqrt(%pi)

Next: , Previous: Error Function, Up: Special Functions   [Contents][Index]

14.7 Struve Functions

The Struve functions are defined in Abramowitz and Stegun, Handbook of Mathematical Functions, A&S Chapter 12 and (DLMF 11). The Struve Function \({\bf H}_{\nu}(z)\) is a particular solution of the differential equation: $$ z^2 {d^2 w \over dz^2} + z {dw \over dz} + (z^2-\nu^2)w = {{4\left({1\over 2} z\right)^{\nu+1}} \over \sqrt{\pi} \Gamma\left(\nu + {1\over 2}\right)} $$

which has the general soution $$ w = aJ_{\nu}(z) + bY_{\nu}(z) + {\bf H}_{\nu}(z) $$

Function: struve_h (v, z)

The Struve Function H of order \(\nu\) and argument z:

$$ {\bf H}_{\nu}(z) = \left({z\over 2}\right)^{\nu+1} \sum_{k=0}^{\infty} {(-1)^k\left({z\over 2}\right)^{2k} \over \Gamma\left(k + {3\over 2}\right) \Gamma\left(k + \nu + {3\over 2}\right)} $$

(A&S eqn 12.1.3) and (DLMF 11.2.E1).

When besselexpand is true, struve_h is expanded in terms of elementary functions when the order v is half of an odd integer. See besselexpand.

Function: struve_l (v, z)

The Modified Struve Function L of order \(\nu\) and argument z: $$ {\bf L}_{\nu}(z) = -ie^{-{i\nu\pi\over 2}} {\bf H}_{\nu}(iz) $$

(A&S eqn 12.2.1) and (DLMF 11.2.E2).

When besselexpand is true, struve_l is expanded in terms of elementary functions when the order v is half of an odd integer. See besselexpand.


Next: , Previous: Struve Functions, Up: Special Functions   [Contents][Index]

14.8 Hypergeometric Functions

The Hypergeometric Functions are defined in Abramowitz and Stegun, Handbook of Mathematical Functions, A&S Chapters 13 and A&S 15.

Maxima has very limited knowledge of these functions. They can be returned from function hgfred.

Function: %m [k,u] (z)

Whittaker M function (A&S eqn 13.1.32):

$$ M_{\kappa,\mu}(z) = e^{-{1\over 2}z} z^{{1\over 2} + \mu} M\left({1\over 2} + \mu - \kappa, 1 + 2\mu, z\right) $$

where M(a,b,z) is Kummer’s solution of the confluent hypergeometric equation.

This can also be expressed by the series (DLMF 13.14.E6): $$ M_{\kappa,\mu}(z) = e^{-{1\over 2} z} z^{{1\over 2} + \mu} \sum_{s=0}^{\infty} {\left({1\over 2} + \mu - \kappa\right)_s \over (1 + 2\mu)_s s!} z^s $$

Function: %w [k,u] (z)

Whittaker W function (A&S eqn 13.1.33): $$ W_{\kappa,\mu}(z) = e^{-{1\over 2}z} z^{{1\over 2} + \mu} U\left({1\over 2} + \mu - \kappa, 1+2\mu,z\right) $$

where U(a,b,z) is Kummer’s second solution of the confluent hypergeometric equation.

Function: %f [p,q] ([a],[b],z)

The \(_{p}F_{q}(a_1,a_2,...,a_p;b_1,b_2,...,b_q;z)\) hypergeometric function, where a a list of length p and b a list of length q.

Function: hypergeometric ([a1, ..., ap],[b1, ... ,bq], x)

The hypergeometric function. Unlike Maxima’s %f hypergeometric function, the function hypergeometric is a simplifying function; also, hypergeometric supports complex double and big floating point evaluation. For the Gauss hypergeometric function, that is p = 2 and q = 1, floating point evaluation outside the unit circle is supported, but in general, it is not supported.

When the option variable expand_hypergeometric is true (default is false) and one of the arguments a1 through ap is a negative integer (a polynomial case), hypergeometric returns an expanded polynomial.

Examples:

(%i1)  hypergeometric([],[],x);
(%o1) %e^x

Polynomial cases automatically expand when expand_hypergeometric is true:

(%i2) hypergeometric([-3],[7],x);
(%o2) hypergeometric([-3],[7],x)

(%i3) hypergeometric([-3],[7],x), expand_hypergeometric : true;
(%o3) -x^3/504+3*x^2/56-3*x/7+1

Both double float and big float evaluation is supported:

(%i4) hypergeometric([5.1],[7.1 + %i],0.42);
(%o4)       1.346250786375334 - 0.0559061414208204 %i
(%i5) hypergeometric([5,6],[8], 5.7 - %i);
(%o5)     .007375824009774946 - .001049813688578674 %i
(%i6) hypergeometric([5,6],[8], 5.7b0 - %i), fpprec : 30;
(%o6) 7.37582400977494674506442010824b-3
                          - 1.04981368857867315858055393376b-3 %i
Function: hypergeometric_simp (e)

hypergeometric_simp simplifies hypergeometric functions by applying hgfred to the arguments of any hypergeometric functions in the expression e.

Only instances of hypergeometric are affected; any %f, %w, and %m in the expression e are not affected. Any unsimplified hypergeometric functions are returned unchanged (instead of changing to %f as hgfred would).

load("hypergeometric"); loads this function.

See also hgfred.

Examples:

(%i1) load ("hypergeometric") $
(%i2) foo : [hypergeometric([1,1], [2], z), hypergeometric([1/2], [1], z)];
(%o2) [hypergeometric([1, 1], [2], z), 
                                                     1
                                     hypergeometric([-], [1], z)]
                                                     2
(%i3) hypergeometric_simp (foo);
                 log(1 - z)              z    z/2
(%o3)         [- ----------, bessel_i(0, -) %e   ]
                     z                   2
(%i4) bar : hypergeometric([n], [m], z + 1);
(%o4)            hypergeometric([n], [m], z + 1)
(%i5) hypergeometric_simp (bar);
(%o5)            hypergeometric([n], [m], z + 1)
Function: hgfred (a, b, t)

Simplify the generalized hypergeometric function in terms of other, simpler, forms. a is a list of numerator parameters and b is a list of the denominator parameters.

If hgfred cannot simplify the hypergeometric function, it returns an expression of the form %f[p,q]([a], [b], x) where p is the number of elements in a, and q is the number of elements in b. This is the usual \(_pF_q\) generalized hypergeometric function.

(%i1) assume(not(equal(z,0)));
(%o1)                          [notequal(z, 0)]
(%i2) hgfred([v+1/2],[2*v+1],2*%i*z);

                     v/2                               %i z
                    4    bessel_j(v, z) gamma(v + 1) %e
(%o2)               ---------------------------------------
                                       v
                                      z
(%i3) hgfred([1,1],[2],z);

                                   log(1 - z)
(%o3)                            - ----------
                                       z
(%i4) hgfred([a,a+1/2],[3/2],z^2);

                               1 - 2 a          1 - 2 a
                        (z + 1)        - (1 - z)
(%o4)                   -------------------------------
                                 2 (1 - 2 a) z

It can be beneficial to load orthopoly too as the following example shows. Note that L is the generalized Laguerre polynomial.

(%i5) load("orthopoly")$
(%i6) hgfred([-2],[a],z);
                                    (a - 1)
                                 2 L       (z)
                                    2
(%o6)                            -------------
                                   a (a + 1)
(%i7) ev(%);

                                  2
                                 z        2 z
(%o7)                         --------- - --- + 1
                              a (a + 1)    a


Next: , Previous: Hypergeometric Functions, Up: Special Functions   [Contents][Index]

14.9 Parabolic Cylinder Functions

The Parabolic Cylinder Functions are defined in Abramowitz and Stegun, Handbook of Mathematical Functions, A&S Chapter 19.

Maxima has very limited knowledge of these functions. They can be returned from function specint.

Function: parabolic_cylinder_d (v, z)

The parabolic cylinder function parabolic_cylinder_d(v,z). (A&S eqn 19.3.1).

The solution of the Weber differential equation $$ y''(z) + \left(\nu + {1\over 2} - {1\over 4} z^2\right) y(z) = 0 $$

has two independent solutions, one of which is \(D_{\nu}(z)\), the parabolic cylinder d function.

Function specint can return expressions containing parabolic_cylinder_d(v,z) if the option variable prefer_d is true.


Previous: Parabolic Cylinder Functions, Up: Special Functions   [Contents][Index]

14.10 Functions and Variables for Special Functions

Function: lambert_w (z)

The principal branch of Lambert’s W function W(z) (DLMF 4.13), the solution of $$ z = W(z)e^{W(z)} $$

Function: generalized_lambert_w (k, z)

The k-th branch of Lambert’s W function W(z) (DLMF 4.13), the solution of \(z=W(z)e^{W(z)}\).

The principal branch, denoted \(W_p(z)\) in DLMF, is lambert_w(z) = generalized_lambert_w(0,z).

The other branch with real values, denoted \(W_m(z)\) in DLMF, is generalized_lambert_w(-1,z).

Function: kbateman [v] (x)

The Bateman k function

$$ k_v(x) = \frac{2}{\pi} \int_0^{\frac{\pi}{2}} \cos(x \tan\theta-v\theta)d\theta $$

It is a special case of the confluent hypergeometric function. Maxima can calculate the Laplace transform of kbateman using laplace or specint, but has no other knowledge of this function.

Function: nzeta (z)

The Plasma Dispersion Function $$ {\rm nzeta}(z) = i\sqrt{\pi}e^{-z^2}(1-{\rm erf}(-iz)) $$

Function: nzetar (z)

Returns realpart(nzeta(z)).

Function: nzetai (z)

Returns imagpart(nzeta(z)).


Next: , Previous: Special Functions, Up: Top   [Contents][Index]

15 Эллиптические функции


Next: , Up: Top   [Contents][Index]

15.1 Эллиптические функции и интегралы в Maxima

Maxima поддерживает работу с эллиптическими функциями Якоби, а также полными и неполными эллиптическими интегралами - как символьную манипуляцию, так и численные расчеты. Определение этих функций и множество их свойств можно найти в главах 16, 17 справочника Abramowitz, Stegun. Мы используем определения и отношения из книги Абрамовица и Стиган там, где это возможно.

В частности, все эллиптические функции и нтегралы используют параметр m вместо модуля k или амплитуды \alpha. Это единственное расхождение с Амбрамовицем и Стиган, которые используют для эллиптических функций амплитуду. Действуют следующие отношения:

В первую очередь упор делался на символьные вычисления с эллиптическими функциями и интегралами. Поэтому известно большинство производных для функций и интегралов. Однако, если в какчестве параметра заданы числа с плавающей точкой, то возвращается численное значение.

Поддержка большинства других свойств эллиптических функций и интегралов, помимо выражения их производных, еще не реализована.

Несколько примеров для эллиптических функций:

(%i1) jacobi_sn (u, m);
(%o1)                    jacobi_sn(u, m)
(%i2) jacobi_sn (u, 1);
(%o2)                        tanh(u)
(%i3) jacobi_sn (u, 0);
(%o3)                        sin(u)
(%i4) diff (jacobi_sn (u, m), u);
(%o4)            jacobi_cn(u, m) jacobi_dn(u, m)
(%i5) diff (jacobi_sn (u, m), m);
(%o5) jacobi_cn(u, m) jacobi_dn(u, m)

      elliptic_e(asin(jacobi_sn(u, m)), m)
 (u - ------------------------------------)/(2 m)
                     1 - m

            2
   jacobi_cn (u, m) jacobi_sn(u, m)
 + --------------------------------
              2 (1 - m)

Несколько примеров для эллиптических интегралов:

(%i1) elliptic_f (phi, m);
(%o1)                  elliptic_f(phi, m)
(%i2) elliptic_f (phi, 0);
(%o2)                          phi
(%i3) elliptic_f (phi, 1);
                               phi   %pi
(%o3)                  log(tan(--- + ---))
                                2     4
(%i4) elliptic_e (phi, 1);
(%o4)                       sin(phi)
(%i5) elliptic_e (phi, 0);
(%o5)                          phi
(%i6) elliptic_kc (1/2);
                                     1
(%o6)                    elliptic_kc(-)
                                     2
(%i7) makegamma (%);
                                 2 1
                            gamma (-)
                                   4
(%o7)                      -----------
                           4 sqrt(%pi)
(%i8) diff (elliptic_f (phi, m), phi);
                                1
(%o8)                 ---------------------
                                    2
                      sqrt(1 - m sin (phi))
(%i9) diff (elliptic_f (phi, m), m);
       elliptic_e(phi, m) - (1 - m) elliptic_f(phi, m)
(%o9) (-----------------------------------------------
                              m

                                 cos(phi) sin(phi)
                             - ---------------------)/(2 (1 - m))
                                             2
                               sqrt(1 - m sin (phi))

Поддержку эллиптических функций и интегралов реализовал Реймонд Той, и его код доступен под лицензии GPL, как и весь код Maxima.


Next: , Previous: Эллиптические функции и интегралы в Maxima, Up: Top   [Contents][Index]

15.2 Функции и переменные для эллиптических функций

Функция: jacobi_sn (u, m)

Эллиптическая функция Якоби sn(u,m).

Функция: jacobi_cn (u, m)

Эллиптическая функция Якоби cn(u,m).

Функция: jacobi_dn (u, m)

Эллиптическая функция Якоби dn(u,m).

Функция: jacobi_ns (u, m)

Эллиптическая функция Якоби ns(u,m) = 1/sn(u,m).

Функция: jacobi_sc (u, m)

Эллиптическая функция Якоби sc(u,m) = sn(u,m)/cn(u,m).

Функция: jacobi_sd (u, m)

Эллиптическая функция Якоби sd(u,m) = sn(u,m)/dn(u,m).

Функция: jacobi_nc (u, m)

Эллиптическая функция Якоби nc(u,m) = 1/cn(u,m).

Функция: jacobi_cs (u, m)

Эллиптическая функция Якоби cs(u,m) = cn(u,m)/sn(u,m).

Функция: jacobi_cd (u, m)

Эллиптическая функция Якоби cd(u,m) = cn(u,m)/dn(u,m).

Функция: jacobi_nd (u, m)

Эллиптическая функция Якоби nc(u,m) = 1/cn(u,m).

Функция: jacobi_ds (u, m)

Эллиптическая функция Якоби ds(u,m) = dn(u,m)/sn(u,m).

Функция: jacobi_dc (u, m)

Эллиптическая функция Якоби dc(u,m) = dn(u,m)/cn(u,m).

Функция: inverse_jacobi_sn (u, m)

Обратная эллиптическая функция Якоби для sn(u,m).

Функция: inverse_jacobi_cn (u, m)

Обратная эллиптическая функция Якоби для cn(u,m).

Функция: inverse_jacobi_dn (u, m)

Обратная эллиптическая функция Якоби для dn(u,m).

Функция: inverse_jacobi_ns (u, m)

Обратная эллиптическая функция Якоби для ns(u,m).

Функция: inverse_jacobi_sc (u, m)

Обратная эллиптическая функция Якоби для sc(u,m).

Функция: inverse_jacobi_sd (u, m)

Обратная эллиптическая функция Якоби для sd(u,m).

Функция: inverse_jacobi_nc (u, m)

Обратная эллиптическая функция Якоби для nc(u,m).

Функция: inverse_jacobi_cs (u, m)

Обратная эллиптическая функция Якоби для cs(u,m).

Функция: inverse_jacobi_cd (u, m)

Обратная эллиптическая функция Якоби для cd(u,m).

Функция: inverse_jacobi_nd (u, m)

Обратная эллиптическая функция Якоби для nc(u,m).

Функция: inverse_jacobi_ds (u, m)

Обратная эллиптическая функция Якоби для ds(u,m).

Функция: inverse_jacobi_dc (u, m)

Обратная эллиптическая функция Якоби для dc(u,m).


Next: , Previous: Top   [Contents][Index]

15.3 Функции и переменные для эллиптических интегралов

Функция: elliptic_f (phi, m)

Неполный эллиптический интеграл первого рода, заданный в виде

integrate(1/sqrt(1 - m*sin(x)^2), x, 0, phi)

См. также elliptic_e и elliptic_kc.

Функция: elliptic_e (phi, m)

Неполный эллиптический интеграл второго рода, заданный в виде

elliptic_e(u, m) = integrate(sqrt(1 - m*sin(x)^2), x, 0, phi)

См. также elliptic_e и elliptic_ec.

Функция: elliptic_eu (u, m)

Неполный эллиптический интеграл второго рода, заданный в виде

integrate(dn(v,m)^2,v,0,u) = integrate(sqrt(1-m*t^2)/sqrt(1-t^2), t, 0, tau)

где tau = sn(u,m)

Это связано с elliptic_e отношением См. также elliptic_e.

Функция: elliptic_pi (n, phi, m)

Неполный эллиптический интеграл третьего рода, заданный в виде

integrate(1/(1-n*sin(x)^2)/sqrt(1 - m*sin(x)^2), x, 0, phi)

Для Maxima известна только производная по phi.

Функция: elliptic_kc (m)

Полный эллиптический интеграл первого рода, заданный в виде

integrate(1/sqrt(1 - m*sin(x)^2), x, 0, %pi/2)

Для конкретных значений m значение интеграла выражается через гамма-функцию. Для вычисления используйте makegamma.

Функция: elliptic_ec (m)

Полный эллиптический интеграл второго рода, заданный в виде

integrate(sqrt(1 - m*sin(x)^2), x, 0, %pi/2)

Для конкретных значений m значение интеграла выражается через гамма-функцию. Для вычисления используйте makegamma.


Next: , Previous: Эллиптические функции, Up: Top   [Contents][Index]

16 Пределы


Previous: Пределы, Up: Пределы   [Contents][Index]

16.1 Функции для работы с пределами

Управляющая переменная: lhospitallim

Значение по умолчанию: 4

lhospitallim есть максимальное число применений правила Лопиталя в limit. Это предотвращает зацикливание в случаях вроде limit (cot(x)/csc(x), x, 0).

Функция: limit (expr, x, val, dir)
Функция: limit (expr, x, val)
Функция: limit (expr)

Рассчитывает предел expr при стремлении вещественной переменной x к val по направлению dir. dir может иметь значение plus для предела справа, minus для предела слева, либо опускаться (будет рассчитан двусторонний предел).

limit использует специальные символы: inf (плюс бесконечность) и minf (минус бесконечность). Вывод может использовать und (неопределенность), ind (неопределенность, но ограниченность) и infinity (комплексная бесконечность).

lhospitallim есть максимальное число применений правила Лопиталя в limit. Это предотвращает зацикливание в случаях вроде limit (cot(x)/csc(x), x, 0).

Если tlimswitch равно true, команда limit использует разложение в ряды Тейлора там, где это возможно.

limsubst предотвращает подстановки над неизвестными формами в limit. Это позволяет избежать ошибок, когда выражение вида limit (f(n)/f(n+1), n, inf) дает 1. Подобные подстановки будут использоваться, если limsubst равно true.

limit с одним аргументом часто вызывается для упрощения константных выражений, например limit (inf-1).

example (limit) выводит некоторые примеры.

Относительно метода см. Wang, P., "Evaluation of Definite Integrals by Symbolic Manipulation", Ph.D. thesis, MAC TR-92, October 1971.

Управляющая переменная: limsubst

Значение по умолчанию: false – предотвращает подстановки над неизвестными формами в limit. Это позволяет избежать ошибок, когда выражение вида limit (f(n)/f(n+1), n, inf) дает 1. Подобные подстановки будут использоваться, если limsubst равно true.

Функция: tlimit (expr, x, val, dir)
Функция: tlimit (expr, x, val)
Функция: tlimit (expr)

Вычисляет предел разложения выражения expr в ряд Тейлора в точке x равной val с направления dir.

Управляющая переменная: tlimswitch

Значение по умолчанию: true

Если значение tlimswitch равно true, то команда limit будет использовать разложение в ряд Тейлора, если предел выражения не может быть вычислен непосредственно. Это позволяет вычислять пределы типа limit(x/(x-1)-1/log(x),x,1,plus). Если значение tlimswitch равно false и предел выражения не может быть вычислен непосредственно, то limit возвращает исходное выражение предела невычисленным.


Next: , Previous: Пределы, Up: Top   [Contents][Index]

17 Differentiation


Previous: Differentiation, Up: Differentiation   [Contents][Index]

17.1 Functions and Variables for Differentiation

Function: antid (expr, x, u(x))

Returns a two-element list, such that an antiderivative of expr with respect to x can be constructed from the list. The expression expr may contain an unknown function u and its derivatives.

Let L, a list of two elements, be the return value of antid. Then L[1] + 'integrate (L[2], x) is an antiderivative of expr with respect to x.

When antid succeeds entirely, the second element of the return value is zero. Otherwise, the second element is nonzero, and the first element is nonzero or zero. If antid cannot make any progress, the first element is zero and the second nonzero.

load ("antid") loads this function. The antid package also defines the functions nonzeroandfreeof and linear.

antid is related to antidiff as follows. Let L, a list of two elements, be the return value of antid. Then the return value of antidiff is equal to L[1] + 'integrate (L[2], x) where x is the variable of integration.

Examples:

(%i1) load ("antid")$
(%i2) expr: exp (z(x)) * diff (z(x), x) * y(x);
                            z(x)  d
(%o2)                y(x) %e     (-- (z(x)))
                                  dx
(%i3) a1: antid (expr, x, z(x));
                       z(x)      z(x)  d
(%o3)          [y(x) %e    , - %e     (-- (y(x)))]
                                       dx
(%i4) a2: antidiff (expr, x, z(x));
                            /
                     z(x)   [   z(x)  d
(%o4)         y(x) %e     - I %e     (-- (y(x))) dx
                            ]         dx
                            /
(%i5) a2 - (first (a1) + 'integrate (second (a1), x));
(%o5)                           0
(%i6) antid (expr, x, y(x));
                             z(x)  d
(%o6)             [0, y(x) %e     (-- (z(x)))]
                                   dx
(%i7) antidiff (expr, x, y(x));
                  /
                  [        z(x)  d
(%o7)             I y(x) %e     (-- (z(x))) dx
                  ]              dx
                  /
Function: antidiff (expr, x, u(x))

Returns an antiderivative of expr with respect to x. The expression expr may contain an unknown function u and its derivatives.

When antidiff succeeds entirely, the resulting expression is free of integral signs (that is, free of the integrate noun). Otherwise, antidiff returns an expression which is partly or entirely within an integral sign. If antidiff cannot make any progress, the return value is entirely within an integral sign.

load ("antid") loads this function. The antid package also defines the functions nonzeroandfreeof and linear.

antidiff is related to antid as follows. Let L, a list of two elements, be the return value of antid. Then the return value of antidiff is equal to L[1] + 'integrate (L[2], x) where x is the variable of integration.

Examples:

(%i1) load ("antid")$
(%i2) expr: exp (z(x)) * diff (z(x), x) * y(x);
                            z(x)  d
(%o2)                y(x) %e     (-- (z(x)))
                                  dx
(%i3) a1: antid (expr, x, z(x));
                       z(x)      z(x)  d
(%o3)          [y(x) %e    , - %e     (-- (y(x)))]
                                       dx
(%i4) a2: antidiff (expr, x, z(x));
                            /
                     z(x)   [   z(x)  d
(%o4)         y(x) %e     - I %e     (-- (y(x))) dx
                            ]         dx
                            /
(%i5) a2 - (first (a1) + 'integrate (second (a1), x));
(%o5)                           0
(%i6) antid (expr, x, y(x));
                             z(x)  d
(%o6)             [0, y(x) %e     (-- (z(x)))]
                                   dx
(%i7) antidiff (expr, x, y(x));
                  /
                  [        z(x)  d
(%o7)             I y(x) %e     (-- (z(x))) dx
                  ]              dx
                  /
Function: at
    at (expr, [eqn_1, …, eqn_n])
    at (expr, eqn)

Evaluates the expression expr with the variables assuming the values as specified for them in the list of equations [eqn_1, ..., eqn_n] or the single equation eqn.

If a subexpression depends on any of the variables for which a value is specified but there is no atvalue specified and it can’t be otherwise evaluated, then a noun form of the at is returned which displays in a two-dimensional form.

at carries out multiple substitutions in parallel.

See also atvalue. For other functions which carry out substitutions, see also subst and ev.

Examples:

(%i1) atvalue (f(x,y), [x = 0, y = 1], a^2);
                                2
(%o1)                          a
(%i2) atvalue ('diff (f(x,y), x), x = 0, 1 + y);
(%o2)                        @2 + 1
(%i3) printprops (all, atvalue);
                                !
                  d             !
                 --- (f(@1, @2))!       = @2 + 1
                 d@1            !
                                !@1 = 0

                                     2
                          f(0, 1) = a

(%o3)                         done
(%i4) diff (4*f(x, y)^2 - u(x, y)^2, x);
                  d                          d
(%o4)  8 f(x, y) (-- (f(x, y))) - 2 u(x, y) (-- (u(x, y)))
                  dx                         dx
(%i5) at (%, [x = 0, y = 1]);
                                            !
                 2              d           !
(%o5)        16 a  - 2 u(0, 1) (-- (u(x, 1))!     )
                                dx          !
                                            !x = 0

Note that in the last line y is treated differently to x as y isn’t used as a differentiation variable.

The difference between subst, at and ev can be seen in the following example:

(%i1) e1:I(t)=C*diff(U(t),t)$
(%i2) e2:U(t)=L*diff(I(t),t)$
(%i3) at(e1,e2);
                               !
                      d        !
(%o3)       I(t) = C (-- (U(t))!                    )
                      dt       !          d
                               !U(t) = L (-- (I(t)))
                                          dt
(%i4) subst(e2,e1);
                            d      d
(%o4)             I(t) = C (-- (L (-- (I(t)))))
                            dt     dt
(%i5) ev(e1,e2,diff);
                                  2
                                 d
(%o5)                I(t) = C L (--- (I(t)))
                                   2
                                 dt
Property: atomgrad

atomgrad is the atomic gradient property of an expression. This property is assigned by gradef.

Function: atvalue
    atvalue (expr, [x_1 = a_1, …, x_m = a_m], c)
    atvalue (expr, x_1 = a_1, c)

Assigns the value c to expr at the point x = a. Typically boundary values are established by this mechanism.

expr is a function evaluation, f(x_1, ..., x_m), or a derivative, diff (f(x_1, ..., x_m), x_1, n_1, ..., x_n, n_m) in which the function arguments explicitly appear. n_i is the order of differentiation with respect to x_i.

The point at which the atvalue is established is given by the list of equations [x_1 = a_1, ..., x_m = a_m]. If there is a single variable x_1, the sole equation may be given without enclosing it in a list.

printprops ([f_1, f_2, ...], atvalue) displays the atvalues of the functions f_1, f_2, ... as specified by calls to atvalue. printprops (f, atvalue) displays the atvalues of one function f. printprops (all, atvalue) displays the atvalues of all functions for which atvalues are defined.

The symbols @1, @2, … represent the variables x_1, x_2, … when atvalues are displayed.

atvalue evaluates its arguments. atvalue returns c, the atvalue.

See also at.

Examples:

(%i1) atvalue (f(x,y), [x = 0, y = 1], a^2);
                                2
(%o1)                          a
(%i2) atvalue ('diff (f(x,y), x), x = 0, 1 + y);
(%o2)                        @2 + 1
(%i3) printprops (all, atvalue);
                                !
                  d             !
                 --- (f(@1, @2))!       = @2 + 1
                 d@1            !
                                !@1 = 0

                                     2
                          f(0, 1) = a

(%o3)                         done
(%i4) diff (4*f(x,y)^2 - u(x,y)^2, x);
                  d                          d
(%o4)  8 f(x, y) (-- (f(x, y))) - 2 u(x, y) (-- (u(x, y)))
                  dx                         dx
(%i5) at (%, [x = 0, y = 1]);
                                            !
                 2              d           !
(%o5)        16 a  - 2 u(0, 1) (-- (u(x, 1))!     )
                                dx          !
                                            !x = 0
Function: cartan

The exterior calculus of differential forms is a basic tool of differential geometry developed by Elie Cartan and has important applications in the theory of partial differential equations. The cartan package implements the functions ext_diff and lie_diff, along with the operators ~ (wedge product) and | (contraction of a form with a vector.) Type demo ("tensor") to see a brief description of these commands along with examples.

cartan was implemented by F.B. Estabrook and H.D. Wahlquist.

Function: init_cartan ([x_1, ..., x_n])

init_cartan([x_1, ..., x_n]) initializes global variables for the cartan package. The sole argument is a list of symbols, from which the Cartan basis is constructed.

init_cartan returns the basis which is constructed.

init_cartan assigns values to the following global variables: cartan_coords, cartan_dim, extdim, and cartan_basis. In addition, the following arrays are assigned: extsub and extsubb.

Note: Because of the internal implementation of the cartan package, it is necessary for init_cartan to be called before any expression containing the Cartan coordinates x_1, ..., x_n is parsed.

Function: del (x)

del (x) represents the differential of the variable x.

diff returns an expression containing del if an independent variable is not specified. In this case, the return value is the so-called "total differential".

See also diff, del and derivdegree.

Examples:

(%i1) diff (log (x));
                             del(x)
(%o1)                        ------
                               x
(%i2) diff (exp (x*y));
                     x y              x y
(%o2)            x %e    del(y) + y %e    del(x)
(%i3) diff (x*y*z);
(%o3)         x y del(z) + x z del(y) + y z del(x)
Function: delta (t)

The Dirac Delta function.

Currently only laplace knows about the delta function.

Example:

(%i1) laplace (delta (t - a) * sin(b*t), t, s);
Is  a  positive, negative, or zero?

p;
                                   - a s
(%o1)                   sin(a b) %e
System variable: dependencies
Function: dependencies (f_1, …, f_n)

The variable dependencies is the list of atoms which have functional dependencies, assigned by depends, the function dependencies, or gradef. The dependencies list is cumulative: each call to depends, dependencies, or gradef appends additional items. The default value of dependencies is [].

The function dependencies(f_1, …, f_n) appends f_1, …, f_n, to the dependencies list, where f_1, …, f_n are expressions of the form f(x_1, …, x_m), and x_1, …, x_m are any number of arguments.

dependencies(f(x_1, …, x_m)) is equivalent to depends(f, [x_1, …, x_m]).

See also depends and gradef.

(%i1) dependencies;
(%o1)                          []
(%i2) depends (foo, [bar, baz]);
(%o2)                    [foo(bar, baz)]
(%i3) depends ([g, h], [a, b, c]);
(%o3)               [g(a, b, c), h(a, b, c)]
(%i4) dependencies;
(%o4)        [foo(bar, baz), g(a, b, c), h(a, b, c)]
(%i5) dependencies (quux (x, y), mumble (u));
(%o5)                [quux(x, y), mumble(u)]
(%i6) dependencies;
(%o6) [foo(bar, baz), g(a, b, c), h(a, b, c), quux(x, y), 
                                                       mumble(u)]
(%i7) remove (quux, dependency);
(%o7)                         done
(%i8) dependencies;
(%o8)  [foo(bar, baz), g(a, b, c), h(a, b, c), mumble(u)]
Function: depends (f_1, x_1, …, f_n, x_n)

Declares functional dependencies among variables for the purpose of computing derivatives. In the absence of declared dependence, diff (f, x) yields zero. If depends (f, x) is declared, diff (f, x) yields a symbolic derivative (that is, a diff noun).

Each argument f_1, x_1, etc., can be the name of a variable or array, or a list of names. Every element of f_i (perhaps just a single element) is declared to depend on every element of x_i (perhaps just a single element). If some f_i is the name of an array or contains the name of an array, all elements of the array depend on x_i.

diff recognizes indirect dependencies established by depends and applies the chain rule in these cases.

remove (f, dependency) removes all dependencies declared for f.

depends returns a list of the dependencies established. The dependencies are appended to the global variable dependencies. depends evaluates its arguments.

diff is the only Maxima command which recognizes dependencies established by depends. Other functions (integrate, laplace, etc.) only recognize dependencies explicitly represented by their arguments. For example, integrate does not recognize the dependence of f on x unless explicitly represented as integrate (f(x), x).

depends(f, [x_1, …, x_n]) is equivalent to dependencies(f(x_1, …, x_n)).

See also diff, del, derivdegree and derivabbrev.

(%i1) depends ([f, g], x);
(%o1)                     [f(x), g(x)]
(%i2) depends ([r, s], [u, v, w]);
(%o2)               [r(u, v, w), s(u, v, w)]
(%i3) depends (u, t);
(%o3)                        [u(t)]
(%i4) dependencies;
(%o4)      [f(x), g(x), r(u, v, w), s(u, v, w), u(t)]
(%i5) diff (r.s, u);
                         dr           ds
(%o5)                    -- . s + r . --
                         du           du
(%i6) diff (r.s, t);
                      dr du           ds du
(%o6)                 -- -- . s + r . -- --
                      du dt           du dt
(%i7) remove (r, dependency);
(%o7)                         done
(%i8) diff (r.s, t);
                                ds du
(%o8)                       r . -- --
                                du dt
Option variable: derivabbrev

Default value: false

When derivabbrev is true, symbolic derivatives (that is, diff nouns) are displayed as subscripts. Otherwise, derivatives are displayed in the Leibniz notation dy/dx.

Function: derivdegree (expr, y, x)

Returns the highest degree of the derivative of the dependent variable y with respect to the independent variable x occurring in expr.

Example:

(%i1) 'diff (y, x, 2) + 'diff (y, z, 3) + 'diff (y, x) * x^2;
                         3     2
                        d y   d y    2 dy
(%o1)                   --- + --- + x  --
                          3     2      dx
                        dz    dx
(%i2) derivdegree (%, y, x);
(%o2)                           2
Function: derivlist (var_1, …, var_k)

Causes only differentiations with respect to the indicated variables, within the ev command.

Option variable: derivsubst

Default value: false

When derivsubst is true, a non-syntactic substitution such as subst (x, 'diff (y, t), 'diff (y, t, 2)) yields 'diff (x, t).

Function: diff
    diff (expr, x_1, n_1, …, x_m, n_m)
    diff (expr, x, n)
    diff (expr, x)
    diff (expr)

Returns the derivative or differential of expr with respect to some or all variables in expr.

diff (expr, x, n) returns the n’th derivative of expr with respect to x.

diff (expr, x_1, n_1, ..., x_m, n_m) returns the mixed partial derivative of expr with respect to x_1, …, x_m. It is equivalent to diff (... (diff (expr, x_m, n_m) ...), x_1, n_1).

diff (expr, x) returns the first derivative of expr with respect to the variable x.

diff (expr) returns the total differential of expr, that is, the sum of the derivatives of expr with respect to each its variables times the differential del of each variable. No further simplification of del is offered.

The noun form of diff is required in some contexts, such as stating a differential equation. In these cases, diff may be quoted (as 'diff) to yield the noun form instead of carrying out the differentiation.

When derivabbrev is true, derivatives are displayed as subscripts. Otherwise, derivatives are displayed in the Leibniz notation, dy/dx.

See also depends, del, derivdegree, derivabbrev, and gradef.

Examples:

(%i1) diff (exp (f(x)), x, 2);
                     2
              f(x)  d               f(x)  d         2
(%o1)       %e     (--- (f(x))) + %e     (-- (f(x)))
                      2                   dx
                    dx
(%i2) derivabbrev: true$
(%i3) 'integrate (f(x, y), y, g(x), h(x));
                         h(x)
                        /
                        [
(%o3)                   I     f(x, y) dy
                        ]
                        /
                         g(x)
(%i4) diff (%, x);
       h(x)
      /
      [
(%o4) I     f(x, y)  dy + f(x, h(x)) h(x)  - f(x, g(x)) g(x)
      ]            x                     x                  x
      /
       g(x)

For the tensor package, the following modifications have been incorporated:

(1) The derivatives of any indexed objects in expr will have the variables x_i appended as additional arguments. Then all the derivative indices will be sorted.

(2) The x_i may be integers from 1 up to the value of the variable dimension [default value: 4]. This will cause the differentiation to be carried out with respect to the x_i’th member of the list coordinates which should be set to a list of the names of the coordinates, e.g., [x, y, z, t]. If coordinates is bound to an atomic variable, then that variable subscripted by x_i will be used for the variable of differentiation. This permits an array of coordinate names or subscripted names like X[1], X[2], … to be used. If coordinates has not been assigned a value, then the variables will be treated as in (1) above.

Special symbol: diff

When diff is present as an evflag in call to ev, all differentiations indicated in expr are carried out.

Function: express (expr)

Expands differential operator nouns into expressions in terms of partial derivatives. express recognizes the operators grad, div, curl, laplacian. express also expands the cross product ~.

Symbolic derivatives (that is, diff nouns) in the return value of express may be evaluated by including diff in the ev function call or command line. In this context, diff acts as an evfun.

load ("vect") loads this function.

Examples:

(%i1) load ("vect")$
(%i2) grad (x^2 + y^2 + z^2);
                              2    2    2
(%o2)                  grad (z  + y  + x )
(%i3) express (%);
       d    2    2    2   d    2    2    2   d    2    2    2
(%o3) [-- (z  + y  + x ), -- (z  + y  + x ), -- (z  + y  + x )]
       dx                 dy                 dz
(%i4) ev (%, diff);
(%o4)                    [2 x, 2 y, 2 z]
(%i5) div ([x^2, y^2, z^2]);
                              2   2   2
(%o5)                   div [x , y , z ]
(%i6) express (%);
                   d    2    d    2    d    2
(%o6)              -- (z ) + -- (y ) + -- (x )
                   dz        dy        dx
(%i7) ev (%, diff);
(%o7)                    2 z + 2 y + 2 x
(%i8) curl ([x^2, y^2, z^2]);
                               2   2   2
(%o8)                   curl [x , y , z ]
(%i9) express (%);
       d    2    d    2   d    2    d    2   d    2    d    2
(%o9) [-- (z ) - -- (y ), -- (x ) - -- (z ), -- (y ) - -- (x )]
       dy        dz       dz        dx       dx        dy
(%i10) ev (%, diff);
(%o10)                      [0, 0, 0]
(%i11) laplacian (x^2 * y^2 * z^2);
                                  2  2  2
(%o11)                laplacian (x  y  z )
(%i12) express (%);
         2                2                2
        d     2  2  2    d     2  2  2    d     2  2  2
(%o12)  --- (x  y  z ) + --- (x  y  z ) + --- (x  y  z )
          2                2                2
        dz               dy               dx
(%i13) ev (%, diff);
                      2  2      2  2      2  2
(%o13)             2 y  z  + 2 x  z  + 2 x  y
(%i14) [a, b, c] ~ [x, y, z];
(%o14)                [a, b, c] ~ [x, y, z]
(%i15) express (%);
(%o15)          [b z - c y, c x - a z, a y - b x]
Function: gradef
    gradef (f(x_1, …, x_n), g_1, …, g_m)
    gradef (a, x, expr)

Defines the partial derivatives (i.e., the components of the gradient) of the function f or variable a.

gradef (f(x_1, ..., x_n), g_1, ..., g_m) defines df/dx_i as g_i, where g_i is an expression; g_i may be a function call, but not the name of a function. The number of partial derivatives m may be less than the number of arguments n, in which case derivatives are defined with respect to x_1 through x_m only.

gradef (a, x, expr) defines the derivative of variable a with respect to x as expr. This also establishes the dependence of a on x (via depends (a, x)).

The first argument f(x_1, ..., x_n) or a is quoted, but the remaining arguments g_1, ..., g_m are evaluated. gradef returns the function or variable for which the partial derivatives are defined.

gradef can redefine the derivatives of Maxima’s built-in functions. For example, gradef (sin(x), sqrt (1 - sin(x)^2)) redefines the derivative of sin.

gradef cannot define partial derivatives for a subscripted function.

printprops ([f_1, ..., f_n], gradef) displays the partial derivatives of the functions f_1, ..., f_n, as defined by gradef.

printprops ([a_n, ..., a_n], atomgrad) displays the partial derivatives of the variables a_n, ..., a_n, as defined by gradef.

gradefs is the list of the functions for which partial derivatives have been defined by gradef. gradefs does not include any variables for which partial derivatives have been defined by gradef.

Gradients are needed when, for example, a function is not known explicitly but its first derivatives are and it is desired to obtain higher order derivatives.

System variable: gradefs

Default value: []

gradefs is the list of the functions for which partial derivatives have been defined by gradef. gradefs does not include any variables for which partial derivatives have been defined by gradef.


Next: , Previous: Differentiation, Up: Top   [Contents][Index]

18 Integration


Next: , Previous: Integration, Up: Integration   [Contents][Index]

18.1 Introduction to Integration

Maxima has several routines for handling integration. The integrate function makes use of most of them. There is also the antid package, which handles an unspecified function (and its derivatives, of course). For numerical uses, there is a set of adaptive integrators from QUADPACK, named quad_qag, quad_qags, etc., which are described under the heading QUADPACK. Hypergeometric functions are being worked on, see specint for details. Generally speaking, Maxima only handles integrals which are integrable in terms of the "elementary functions" (rational functions, trigonometrics, logs, exponentials, radicals, etc.) and a few extensions (error function, dilogarithm). It does not handle integrals in terms of unknown functions such as g(x) and h(x).


Next: , Previous: Introduction to Integration, Up: Integration   [Contents][Index]

18.2 Functions and Variables for Integration

Function: changevar (expr, f(x,y), y, x)

Makes the change of variable given by f(x,y) = 0 in all integrals occurring in expr with integration with respect to x. The new variable is y.

The change of variable can also be written f(x) = g(y).

(%i1) assume(a > 0)$
(%i2) 'integrate (%e**sqrt(a*y), y, 0, 4);
                      4
                     /
                     [    sqrt(a) sqrt(y)
(%o2)                I  %e                dy
                     ]
                     /
                      0
(%i3) changevar (%, y-z^2/a, z, y);
                      0
                     /
                     [                abs(z)
                   2 I            z %e       dz
                     ]
                     /
                      - 2 sqrt(a)
(%o3)            - ----------------------------
                                a

An expression containing a noun form, such as the instances of 'integrate above, may be evaluated by ev with the nouns flag. For example, the expression returned by changevar above may be evaluated by ev (%o3, nouns).

changevar may also be used to make changes in the indices of a sum or product. However, it must be realized that when a change is made in a sum or product, this change must be a shift, i.e., i = j+ ..., not a higher degree function. E.g.,

(%i4) sum (a[i]*x^(i-2), i, 0, inf);
                         inf
                         ====
                         \         i - 2
(%o4)                     >    a  x
                         /      i
                         ====
                         i = 0
(%i5) changevar (%, i-2-n, n, i);
                        inf
                        ====
                        \               n
(%o5)                    >      a      x
                        /        n + 2
                        ====
                        n = - 2
Function: dblint (f, r, s, a, b)

A double-integral routine which was written in top-level Maxima and then translated and compiled to machine code. Use load ("dblint") to access this package. It uses the Simpson’s rule method in both the x and y directions to calculate

/b /s(x)
|  |
|  |    f(x,y) dy dx
|  |
/a /r(x)

The function f must be a translated or compiled function of two variables, and r and s must each be a translated or compiled function of one variable, while a and b must be floating point numbers. The routine has two global variables which determine the number of divisions of the x and y intervals: dblint_x and dblint_y, both of which are initially 10, and can be changed independently to other integer values (there are 2*dblint_x+1 points computed in the x direction, and 2*dblint_y+1 in the y direction). The routine subdivides the X axis and then for each value of X it first computes r(x) and s(x); then the Y axis between r(x) and s(x) is subdivided and the integral along the Y axis is performed using Simpson’s rule; then the integral along the X axis is done using Simpson’s rule with the function values being the Y-integrals. This procedure may be numerically unstable for a great variety of reasons, but is reasonably fast: avoid using it on highly oscillatory functions and functions with singularities (poles or branch points in the region). The Y integrals depend on how far apart r(x) and s(x) are, so if the distance s(x) - r(x) varies rapidly with X, there may be substantial errors arising from truncation with different step-sizes in the various Y integrals. One can increase dblint_x and dblint_y in an effort to improve the coverage of the region, at the expense of computation time. The function values are not saved, so if the function is very time-consuming, you will have to wait for re-computation if you change anything (sorry). It is required that the functions f, r, and s be either translated or compiled prior to calling dblint. This will result in orders of magnitude speed improvement over interpreted code in many cases!

demo ("dblint") executes a demonstration of dblint applied to an example problem.

Function: defint (expr, x, a, b)

Attempts to compute a definite integral. defint is called by integrate when limits of integration are specified, i.e., when integrate is called as integrate (expr, x, a, b). Thus from the user’s point of view, it is sufficient to call integrate.

defint returns a symbolic expression, either the computed integral or the noun form of the integral. See quad_qag and related functions for numerical approximation of definite integrals.

Option variable: erfflag

Default value: true

When erfflag is false, prevents risch from introducing the erf function in the answer if there were none in the integrand to begin with.

Function: ilt (expr, s, t)

Computes the inverse Laplace transform of expr with respect to s and parameter t. expr must be a ratio of polynomials whose denominator has only linear and quadratic factors; there is an extension of ilt, called pwilt (Piece-Wise Inverse Laplace Transform) that handles several other cases where ilt fails.

By using the functions laplace and ilt together with the solve or linsolve functions the user can solve a single differential or convolution integral equation or a set of them.

(%i1) 'integrate (sinh(a*x)*f(t-x), x, 0, t) + b*f(t) = t**2;
              t
             /
             [                                    2
(%o1)        I  f(t - x) sinh(a x) dx + b f(t) = t
             ]
             /
              0
(%i2) laplace (%, t, s);
                               a laplace(f(t), t, s)   2
(%o2)  b laplace(f(t), t, s) + --------------------- = --
                                       2    2           3
                                      s  - a           s
(%i3) linsolve ([%], ['laplace(f(t), t, s)]);
                                        2      2
                                     2 s  - 2 a
(%o3)     [laplace(f(t), t, s) = --------------------]
                                    5         2     3
                                 b s  + (a - a  b) s
(%i4) ilt (rhs (first (%)), s, t);
Is  a b (a b - 1)  positive, negative, or zero?

pos;
               sqrt(a b (a b - 1)) t
        2 cosh(---------------------)       2
                         b               a t
(%o4) - ----------------------------- + -------
              3  2      2               a b - 1
             a  b  - 2 a  b + a

                                                       2
                                             + ------------------
                                                3  2      2
                                               a  b  - 2 a  b + a
Option variable: intanalysis

Default value: true

When true, definite integration tries to find poles in the integrand in the interval of integration. If there are, then the integral is evaluated appropriately as a principal value integral. If intanalysis is false, this check is not performed and integration is done assuming there are no poles.

See also ldefint.

Examples:

Maxima can solve the following integrals, when intanalysis is set to false:

(%i1) integrate(1/(sqrt(x)+1),x,0,1);
                                1
                               /
                               [       1
(%o1)                          I  ----------- dx
                               ]  sqrt(x) + 1
                               /
                                0

(%i2) integrate(1/(sqrt(x)+1),x,0,1),intanalysis:false;
(%o2)                            2 - 2 log(2)

(%i3) integrate(cos(a)/sqrt((tan(a))^2 +1),a,-%pi/2,%pi/2);
The number 1 isn't in the domain of atanh
 -- an error. To debug this try: debugmode(true);

(%i4) intanalysis:false$
(%i5) integrate(cos(a)/sqrt((tan(a))^2+1),a,-%pi/2,%pi/2);
                                      %pi
(%o5)                                 ---
                                       2
Function: integrate
    integrate (expr, x)
    integrate (expr, x, a, b)

Attempts to symbolically compute the integral of expr with respect to x. integrate (expr, x) is an indefinite integral, while integrate (expr, x, a, b) is a definite integral, with limits of integration a and b. The limits should not contain x, although integrate does not enforce this restriction. a need not be less than b. If b is equal to a, integrate returns zero.

See quad_qag and related functions for numerical approximation of definite integrals. See residue for computation of residues (complex integration). See antid for an alternative means of computing indefinite integrals.

The integral (an expression free of integrate) is returned if integrate succeeds. Otherwise the return value is the noun form of the integral (the quoted operator 'integrate) or an expression containing one or more noun forms. The noun form of integrate is displayed with an integral sign.

In some circumstances it is useful to construct a noun form by hand, by quoting integrate with a single quote, e.g., 'integrate (expr, x). For example, the integral may depend on some parameters which are not yet computed. The noun may be applied to its arguments by ev (i, nouns) where i is the noun form of interest.

integrate handles definite integrals separately from indefinite, and employs a range of heuristics to handle each case. Special cases of definite integrals include limits of integration equal to zero or infinity (inf or minf), trigonometric functions with limits of integration equal to zero and %pi or 2 %pi, rational functions, integrals related to the definitions of the beta and psi functions, and some logarithmic and trigonometric integrals. Processing rational functions may include computation of residues. If an applicable special case is not found, an attempt will be made to compute the indefinite integral and evaluate it at the limits of integration. This may include taking a limit as a limit of integration goes to infinity or negative infinity; see also ldefint.

Special cases of indefinite integrals include trigonometric functions, exponential and logarithmic functions, and rational functions. integrate may also make use of a short table of elementary integrals.

integrate may carry out a change of variable if the integrand has the form f(g(x)) * diff(g(x), x). integrate attempts to find a subexpression g(x) such that the derivative of g(x) divides the integrand. This search may make use of derivatives defined by the gradef function. See also changevar and antid.

If none of the preceding heuristics find the indefinite integral, the Risch algorithm is executed. The flag risch may be set as an evflag, in a call to ev or on the command line, e.g., ev (integrate (expr, x), risch) or integrate (expr, x), risch. If risch is present, integrate calls the risch function without attempting heuristics first. See also risch.

integrate works only with functional relations represented explicitly with the f(x) notation. integrate does not respect implicit dependencies established by the depends function.

integrate may need to know some property of a parameter in the integrand. integrate will first consult the assume database, and, if the variable of interest is not there, integrate will ask the user. Depending on the question, suitable responses are yes; or no;, or pos;, zero;, or neg;.

integrate is not, by default, declared to be linear. See declare and linear.

integrate attempts integration by parts only in a few special cases.

Examples:

System variable: integration_constant

Default value: %c

When a constant of integration is introduced by indefinite integration of an equation, the name of the constant is constructed by concatenating integration_constant and integration_constant_counter.

integration_constant may be assigned any symbol.

Examples:

(%i1) integrate (x^2 = 1, x);
                           3
                          x
(%o1)                     -- = x + %c1
                          3
(%i2) integration_constant : 'k;
(%o2)                           k
(%i3) integrate (x^2 = 1, x);
                            3
                           x
(%o3)                      -- = x + k2
                           3
System variable: integration_constant_counter

Default value: 0

When a constant of integration is introduced by indefinite integration of an equation, the name of the constant is constructed by concatenating integration_constant and integration_constant_counter.

integration_constant_counter is incremented before constructing the next integration constant.

Examples:

(%i1) integrate (x^2 = 1, x);
                           3
                          x
(%o1)                     -- = x + %c1
                          3
(%i2) integrate (x^2 = 1, x);
                           3
                          x
(%o2)                     -- = x + %c2
                          3
(%i3) integrate (x^2 = 1, x);
                           3
                          x
(%o3)                     -- = x + %c3
                          3
(%i4) reset (integration_constant_counter);
(%o4)            [integration_constant_counter]
(%i5) integrate (x^2 = 1, x);
                           3
                          x
(%o5)                     -- = x + %c1
                          3
Option variable: integrate_use_rootsof

Default value: false

When integrate_use_rootsof is true and the denominator of a rational function cannot be factored, integrate returns the integral in a form which is a sum over the roots (not yet known) of the denominator.

For example, with integrate_use_rootsof set to false, integrate returns an unsolved integral of a rational function in noun form:

(%i1) integrate_use_rootsof: false$
(%i2) integrate (1/(1+x+x^5), x);
        /  2
        [ x  - 4 x + 5
        I ------------ dx                            2 x + 1
        ]  3    2                2            5 atan(-------)
        / x  - x  + 1       log(x  + x + 1)          sqrt(3)
(%o2)   ----------------- - --------------- + ---------------
                7                 14             7 sqrt(3)

Now we set the flag to be true and the unsolved part of the integral will be expressed as a summation over the roots of the denominator of the rational function:

(%i3) integrate_use_rootsof: true$
(%i4) integrate (1/(1+x+x^5), x);
      ====        2
      \       (%r4  - 4 %r4 + 5) log(x - %r4)
       >      -------------------------------
      /                    2
      ====            3 %r4  - 2 %r4
                        3      2
      %r4 in rootsof(%r4  - %r4  + 1, %r4)
(%o4) ----------------------------------------------------------
               7

                                                      2 x + 1
                                  2            5 atan(-------)
                             log(x  + x + 1)          sqrt(3)
                           - --------------- + ---------------
                                   14             7 sqrt(3)

Alternatively the user may compute the roots of the denominator separately, and then express the integrand in terms of these roots, e.g., 1/((x - a)*(x - b)*(x - c)) or 1/((x^2 - (a+b)*x + a*b)*(x - c)) if the denominator is a cubic polynomial. Sometimes this will help Maxima obtain a more useful result.

Function: laplace (expr, t, s)

Attempts to compute the Laplace transform of expr with respect to the variable t and transform parameter s. The Laplace transform of the function f(t) is the one-sided transform defined by $$ F(s) = \int_0^{\infty} f(t) e^{-st} dt $$

where F(s) is the transform of f(t), represented by expr.

laplace recognizes in expr the functions delta, exp, `log', sin, cos, sinh, cosh, and erf, as well as derivative, integrate, sum, and ilt. If laplace fails to find a transform the function specint is called. specint can find the laplace transform for expressions with special functions like the bessel functions bessel_j, bessel_i, … and can handle the unit_step function. See also specint.

If specint cannot find a solution too, a noun laplace is returned.

expr may also be a linear, constant coefficient differential equation in which case atvalue of the dependent variable is used. The required atvalue may be supplied either before or after the transform is computed. Since the initial conditions must be specified at zero, if one has boundary conditions imposed elsewhere he can impose these on the general solution and eliminate the constants by solving the general solution for them and substituting their values back.

laplace recognizes convolution integrals of the form $$ \int_0^t f(x) g(t-x) dx $$

Other kinds of convolutions are not recognized.

Functional relations must be explicitly represented in expr; implicit relations, established by depends, are not recognized. That is, if f depends on x and y, f (x, y) must appear in expr.

See also ilt, the inverse Laplace transform.

Examples:

(%i1) laplace (exp (2*t + a) * sin(t) * t, t, s);
                            a
                          %e  (2 s - 4)
(%o1)                    ---------------
                           2           2
                         (s  - 4 s + 5)
(%i2) laplace ('diff (f (x), x), x, s);
(%o2)             s laplace(f(x), x, s) - f(0)
(%i3) diff (diff (delta (t), t), t);
                          2
                         d
(%o3)                    --- (delta(t))
                           2
                         dt
(%i4) laplace (%, t, s);
                            !
               d            !         2
(%o4)        - -- (delta(t))!      + s  - delta(0) s
               dt           !
                            !t = 0
(%i5) assume(a>0)$
(%i6) laplace(gamma_incomplete(a,t),t,s),gamma_expand:true;
                                              - a - 1
                         gamma(a)   gamma(a) s
(%o6)                    -------- - -----------------
                            s            1     a
                                        (- + 1)
                                         s
(%i7) factor(laplace(gamma_incomplete(1/2,t),t,s));
                                              s + 1
                      sqrt(%pi) (sqrt(s) sqrt(-----) - 1)
                                                s
(%o7)                 -----------------------------------
                                3/2      s + 1
                               s    sqrt(-----)
                                           s
(%i8) assume(exp(%pi*s)>1)$
(%i9) laplace(sum((-1)^n*unit_step(t-n*%pi)*sin(t),n,0,inf),t,s),
         simpsum;
                         %i                         %i
              ------------------------ - ------------------------
                              - %pi s                    - %pi s
              (s + %i) (1 - %e       )   (s - %i) (1 - %e       )
(%o9)         ---------------------------------------------------
                                       2
(%i9) factor(%);
                                      %pi s
                                    %e
(%o9)                   -------------------------------
                                             %pi s
                        (s - %i) (s + %i) (%e      - 1)

Function: ldefint (expr, x, a, b)

Attempts to compute the definite integral of expr by using limit to evaluate the indefinite integral of expr with respect to x at the upper limit b and at the lower limit a. If it fails to compute the definite integral, ldefint returns an expression containing limits as noun forms.

ldefint is not called from integrate, so executing ldefint (expr, x, a, b) may yield a different result than integrate (expr, x, a, b). ldefint always uses the same method to evaluate the definite integral, while integrate may employ various heuristics and may recognize some special cases.

Function: pwilt (expr, s, t)

Computes the inverse Laplace transform of expr with respect to s and parameter t. Unlike ilt, pwilt is able to return piece-wise and periodic functions and can also handle some cases with polynomials of degree greater than 3 in the denominator.

Two examples where ilt fails:

(%i1) pwilt (exp(-s)*s/(s^3-2*s-s+2), s, t);
                                       t - 1       - 2 (t - 1)
                             (t - 1) %e        2 %e
(%o1)         hstep(t - 1) (--------------- - ---------------)
                                    3                 9
                                    
(%i2) pwilt ((s^2+2)/(s^2-1), s, t);
                                         t       - t
                                     3 %e    3 %e
(%o2)                    delta(t) + ----- - -------
                                       2        2
Function: potential (givengradient)

The calculation makes use of the global variable potentialzeroloc[0] which must be nonlist or of the form

[indeterminatej=expressionj, indeterminatek=expressionk, ...]

the former being equivalent to the nonlist expression for all right-hand sides in the latter. The indicated right-hand sides are used as the lower limit of integration. The success of the integrations may depend upon their values and order. potentialzeroloc is initially set to 0.

Option variable: prefer_d

Default value: false

When prefer_d is true, specint will prefer to express solutions using parabolic_cylinder_d rather than hypergeometric functions.

In the example below, the solution contains parabolic_cylinder_d when prefer_d is true.

(%i1) assume(s>0);
(%o1)                               [s > 0]
(%i2) factor(specint(ex:%e^-(t^2/8)*exp(-s*t),t));
                                         2
                                      2 s
(%o2)           - sqrt(2) sqrt(%pi) %e     (erf(sqrt(2) s) - 1)
(%i3) specint(ex,t),prefer_d=true;
                                                          2
                                                         s
                                                         --
                                                 s       8
                    parabolic_cylinder_d(- 1, -------) %e
                                              sqrt(2)
(%o3)               ---------------------------------------
                                    sqrt(2)

Function: residue (expr, z, z_0)

Computes the residue in the complex plane of the expression expr when the variable z assumes the value z_0. The residue is the coefficient of (z - z_0)^(-1) in the Laurent series for expr.

(%i1) residue (s/(s**2+a**2), s, a*%i);
                                1
(%o1)                           -
                                2
(%i2) residue (sin(a*x)/x**4, x, 0);
                                 3
                                a
(%o2)                         - --
                                6
Function: risch (expr, x)

Integrates expr with respect to x using the transcendental case of the Risch algorithm. (The algebraic case of the Risch algorithm has not been implemented.) This currently handles the cases of nested exponentials and logarithms which the main part of integrate can’t do. integrate will automatically apply risch if given these cases.

erfflag, if false, prevents risch from introducing the erf function in the answer if there were none in the integrand to begin with.

(%i1) risch (x^2*erf(x), x);
                                                        2
             3                      2                - x
        %pi x  erf(x) + (sqrt(%pi) x  + sqrt(%pi)) %e
(%o1)   -------------------------------------------------
                              3 %pi
(%i2) diff(%, x), ratsimp;
                             2
(%o2)                       x  erf(x)
Function: specint (exp(- s*t) * expr, t)

Compute the Laplace transform of expr with respect to the variable t. The integrand expr may contain special functions. The parameter s maybe be named something else; it is determined automatically, as the examples below show where p is used in some places.

The following special functions are handled by specint: incomplete gamma function, error functions (but not the error function erfi, it is easy to transform erfi e.g. to the error function erf), exponential integrals, bessel functions (including products of bessel functions), hankel functions, hermite and the laguerre polynomials.

Furthermore, specint can handle the hypergeometric function %f[p,q]([],[],z), the Whittaker function of the first kind %m[u,k](z) and of the second kind %w[u,k](z).

The result may be in terms of special functions and can include unsimplified hypergeometric functions. If variable prefer_d is true then the parabolic_cylinder_d function may be used in the result in preference to hypergeometric functions.

When laplace fails to find a Laplace transform, specint is called. Because laplace knows more general rules for Laplace transforms, it is preferable to use laplace and not specint.

demo("hypgeo") displays several examples of Laplace transforms computed by specint.

Examples:

(%i1) assume (p > 0, a > 0)$
(%i2) specint (t^(1/2) * exp(-a*t/4) * exp(-p*t), t);
                           sqrt(%pi)
(%o2)                     ------------
                                 a 3/2
                          2 (p + -)
                                 4
(%i3) specint (t^(1/2) * bessel_j(1, 2 * a^(1/2) * t^(1/2))
              * exp(-p*t), t);
                                   - a/p
                         sqrt(a) %e
(%o3)                    ---------------
                                2
                               p

Examples for exponential integrals:

(%i4) assume(s>0,a>0,s-a>0)$
(%i5) ratsimp(specint(%e^(a*t)
                      *(log(a)+expintegral_e1(a*t))*%e^(-s*t),t));
                             log(s)
(%o5)                        ------
                             s - a
(%i6) logarc:true$

(%i7) gamma_expand:true$

radcan(specint((cos(t)*expintegral_si(t)
                     -sin(t)*expintegral_ci(t))*%e^(-s*t),t));
                             log(s)
(%o8)                        ------
                              2
                             s  + 1
ratsimp(specint((2*t*log(a)+2/a*sin(a*t)
                      -2*t*expintegral_ci(a*t))*%e^(-s*t),t));
                               2    2
                          log(s  + a )
(%o9)                     ------------
                                2
                               s

Results when using the expansion of gamma_incomplete and when changing the representation to expintegral_e1:

(%i10) assume(s>0)$
(%i11) specint(1/sqrt(%pi*t)*unit_step(t-k)*%e^(-s*t),t);
                                            1
                            gamma_incomplete(-, k s)
                                            2
(%o11)                      ------------------------
                               sqrt(%pi) sqrt(s)

(%i12) gamma_expand:true$
(%i13) specint(1/sqrt(%pi*t)*unit_step(t-k)*%e^(-s*t),t);
                              erfc(sqrt(k) sqrt(s))
(%o13)                        ---------------------
                                     sqrt(s)

(%i14) expintrep:expintegral_e1$
(%i15) ratsimp(specint(1/(t+a)^2*%e^(-s*t),t));
                              a s
                        a s %e    expintegral_e1(a s) - 1
(%o15)                - ---------------------------------
                                        a
Function: tldefint (expr, x, a, b)

Equivalent to ldefint with tlimswitch set to true.


Next: , Previous: Functions and Variables for Integration, Up: Integration   [Contents][Index]

18.3 Introduction to QUADPACK

QUADPACK is a collection of functions for the numerical computation of one-dimensional definite integrals. It originated from a joint project of R. Piessens 1, E. de Doncker 2, C. Ueberhuber 3, and D. Kahaner 4.

The QUADPACK library included in Maxima is an automatic translation (via the program f2cl) of the Fortran source code of QUADPACK as it appears in the SLATEC Common Mathematical Library, Version 4.1 5. The SLATEC library is dated July 1993, but the QUADPACK functions were written some years before. There is another version of QUADPACK at Netlib 6; it is not clear how that version differs from the SLATEC version.

The QUADPACK functions included in Maxima are all automatic, in the sense that these functions attempt to compute a result to a specified accuracy, requiring an unspecified number of function evaluations. Maxima’s Lisp translation of QUADPACK also includes some non-automatic functions, but they are not exposed at the Maxima level.

Further information about QUADPACK can be found in the QUADPACK book 7.

18.3.1 Overview

quad_qag

Integration of a general function over a finite interval. quad_qag implements a simple globally adaptive integrator using the strategy of Aind (Piessens, 1973). The caller may choose among 6 pairs of Gauss-Kronrod quadrature formulae for the rule evaluation component. The high-degree rules are suitable for strongly oscillating integrands.

quad_qags

Integration of a general function over a finite interval. quad_qags implements globally adaptive interval subdivision with extrapolation (de Doncker, 1978) by the Epsilon algorithm (Wynn, 1956).

quad_qagi

Integration of a general function over an infinite or semi-infinite interval. The interval is mapped onto a finite interval and then the same strategy as in quad_qags is applied.

quad_qawo

Integration of \(\cos(\omega x) f(x)\) or \(\sin(\omega x) f(x)\) over a finite interval, where \(\omega\) is a constant. The rule evaluation component is based on the modified Clenshaw-Curtis technique. quad_qawo applies adaptive subdivision with extrapolation, similar to quad_qags.

quad_qawf

Calculates a Fourier cosine or Fourier sine transform on a semi-infinite interval. The same approach as in quad_qawo is applied on successive finite intervals, and convergence acceleration by means of the Epsilon algorithm (Wynn, 1956) is applied to the series of the integral contributions.

quad_qaws

Integration of \(w(x)f(x)\) over a finite interval [a, b], where w is a function of the form \((x-a)^\alpha (b-x)^\beta v(x)\) and v(x) is 1 or \(\log(x-a)\) or \(\log(b-x)\) or

\(\log(x-a)\log(b-x)\)

, and \(\alpha > -1\) and \(\beta > -1\).

A globally adaptive subdivision strategy is applied, with modified Clenshaw-Curtis integration on the subintervals which contain a or b.

quad_qawc

Computes the Cauchy principal value of f(x)/(x - c) over a finite interval (a, b) and specified c. The strategy is globally adaptive, and modified Clenshaw-Curtis integration is used on the subranges which contain the point x = c.

quad_qagp

Basically the same as quad_qags but points of singularity or discontinuity of the integrand must be supplied. This makes it easier for the integrator to produce a good solution.


Previous: Introduction to QUADPACK, Up: Integration   [Contents][Index]

18.4 Functions and Variables for QUADPACK

Function: quad_qag
    quad_qag (f(x), x, a, b, key, [epsrel, epsabs, limit])
    quad_qag (f, x, a, b, key, [epsrel, epsabs, limit])

Integration of a general function over a finite interval. quad_qag implements a simple globally adaptive integrator using the strategy of Aind (Piessens, 1973). The caller may choose among 6 pairs of Gauss-Kronrod quadrature formulae for the rule evaluation component. The high-degree rules are suitable for strongly oscillating integrands.

quad_qag computes the integral

$$ \int_a^b f(x)\, dx $$

The function to be integrated is f(x), with dependent variable x, and the function is to be integrated between the limits a and b. key is the integrator to be used and should be an integer between 1 and 6, inclusive. The value of key selects the order of the Gauss-Kronrod integration rule. High-order rules are suitable for strongly oscillating integrands.

The integrand may be specified as the name of a Maxima or Lisp function or operator, a Maxima lambda expression, or a general Maxima expression.

The numerical integration is done adaptively by subdividing the integration region into sub-intervals until the desired accuracy is achieved.

The keyword arguments are optional and may be specified in any order. They all take the form key=val. The keyword arguments are:

epsrel

Desired relative error of approximation. Default is 1d-8.

epsabs

Desired absolute error of approximation. Default is 0.

limit

Size of internal work array. limit is the maximum number of subintervals to use. Default is 200.

quad_qag returns a list of four elements:

The error code (fourth element of the return value) can have the values:

0

if no problems were encountered;

1

if too many sub-intervals were done;

2

if excessive roundoff error is detected;

3

if extremely bad integrand behavior occurs;

6

if the input is invalid.

Examples:

(%i1) quad_qag (x^(1/2)*log(1/x), x, 0, 1, 3, 'epsrel=5d-8);
(%o1)    [.4444444444492108, 3.1700968502883E-9, 961, 0]
(%i2) integrate (x^(1/2)*log(1/x), x, 0, 1);
                                4
(%o2)                           -
                                9
Function: quad_qags
    quad_qags (f(x), x, a, b, [epsrel, epsabs, limit])
    quad_qags (f, x, a, b, [epsrel, epsabs, limit])

Integration of a general function over a finite interval. quad_qags implements globally adaptive interval subdivision with extrapolation (de Doncker, 1978) by the Epsilon algorithm (Wynn, 1956).

quad_qags computes the integral

$$ \int_a^b f(x)\, dx $$

The function to be integrated is f(x), with dependent variable x, and the function is to be integrated between the limits a and b.

The integrand may be specified as the name of a Maxima or Lisp function or operator, a Maxima lambda expression, or a general Maxima expression.

The keyword arguments are optional and may be specified in any order. They all take the form key=val. The keyword arguments are:

epsrel

Desired relative error of approximation. Default is 1d-8.

epsabs

Desired absolute error of approximation. Default is 0.

limit

Size of internal work array. limit is the maximum number of subintervals to use. Default is 200.

quad_qags returns a list of four elements:

The error code (fourth element of the return value) can have the values:

0

no problems were encountered;

1

too many sub-intervals were done;

2

excessive roundoff error is detected;

3

extremely bad integrand behavior occurs;

4

failed to converge

5

integral is probably divergent or slowly convergent

6

if the input is invalid.

Examples:

(%i1) quad_qags (x^(1/2)*log(1/x), x, 0, 1, 'epsrel=1d-10);
(%o1)   [.4444444444444448, 1.11022302462516E-15, 315, 0]

Note that quad_qags is more accurate and efficient than quad_qag for this integrand.

Function: quad_qagi
    quad_qagi (f(x), x, a, b, [epsrel, epsabs, limit])
    quad_qagi (f, x, a, b, [epsrel, epsabs, limit])

Integration of a general function over an infinite or semi-infinite interval. The interval is mapped onto a finite interval and then the same strategy as in quad_qags is applied.

quad_qagi evaluates one of the following integrals

$$ \int_a^\infty f(x) \, dx $$ $$ \int_\infty^a f(x) \, dx $$ $$ \int_{-\infty}^\infty f(x) \, dx $$

using the Quadpack QAGI routine. The function to be integrated is f(x), with dependent variable x, and the function is to be integrated over an infinite range.

The integrand may be specified as the name of a Maxima or Lisp function or operator, a Maxima lambda expression, or a general Maxima expression.

One of the limits of integration must be infinity. If not, then quad_qagi will just return the noun form.

The keyword arguments are optional and may be specified in any order. They all take the form key=val. The keyword arguments are:

epsrel

Desired relative error of approximation. Default is 1d-8.

epsabs

Desired absolute error of approximation. Default is 0.

limit

Size of internal work array. limit is the maximum number of subintervals to use. Default is 200.

quad_qagi returns a list of four elements:

The error code (fourth element of the return value) can have the values:

0

no problems were encountered;

1

too many sub-intervals were done;

2

excessive roundoff error is detected;

3

extremely bad integrand behavior occurs;

4

failed to converge

5

integral is probably divergent or slowly convergent

6

if the input is invalid.

Examples:

(%i1) quad_qagi (x^2*exp(-4*x), x, 0, inf, 'epsrel=1d-8);
(%o1)        [0.03125, 2.95916102995002E-11, 105, 0]
(%i2) integrate (x^2*exp(-4*x), x, 0, inf);
                               1
(%o2)                          --
                               32
Function: quad_qawc
    quad_qawc (f(x), x, c, a, b, [epsrel, epsabs, limit])
    quad_qawc (f, x, c, a, b, [epsrel, epsabs, limit])

Computes the Cauchy principal value of f(x)/(x - c) over a finite interval. The strategy is globally adaptive, and modified Clenshaw-Curtis integration is used on the subranges which contain the point x = c.

quad_qawc computes the Cauchy principal value of

$$ \int_{a}^{b}{{{f\left(x\right)}\over{x-c}}\>dx} $$

using the Quadpack QAWC routine. The function to be integrated is f(x)/(x-c), with dependent variable x, and the function is to be integrated over the interval a to b.

The integrand may be specified as the name of a Maxima or Lisp function or operator, a Maxima lambda expression, or a general Maxima expression.

The keyword arguments are optional and may be specified in any order. They all take the form key=val. The keyword arguments are:

epsrel

Desired relative error of approximation. Default is 1d-8.

epsabs

Desired absolute error of approximation. Default is 0.

limit

Size of internal work array. limit is the maximum number of subintervals to use. Default is 200.

quad_qawc returns a list of four elements:

The error code (fourth element of the return value) can have the values:

0

no problems were encountered;

1

too many sub-intervals were done;

2

excessive roundoff error is detected;

3

extremely bad integrand behavior occurs;

6

if the input is invalid.

Examples:

(%i1) quad_qawc (2^(-5)*((x-1)^2+4^(-5))^(-1), x, 2, 0, 5,
                 'epsrel=1d-7);
(%o1)    [- 3.130120337415925, 1.306830140249558E-8, 495, 0]
(%i2) integrate (2^(-alpha)*(((x-1)^2 + 4^(-alpha))*(x-2))^(-1),
      x, 0, 5);
Principal Value
                       alpha
        alpha       9 4                 9
       4      log(------------- + -------------)
                      alpha           alpha
                  64 4      + 4   64 4      + 4
(%o2) (-----------------------------------------
                        alpha
                     2 4      + 2

       3 alpha                       3 alpha
       -------                       -------
          2            alpha/2          2          alpha/2
    2 4        atan(4 4       )   2 4        atan(4       )   alpha
  - --------------------------- - -------------------------)/2
              alpha                        alpha
           2 4      + 2                 2 4      + 2
(%i3) ev (%, alpha=5, numer);
(%o3)                    - 3.130120337415917
Function: quad_qawf
    quad_qawf (f(x), x, a, omega, trig, [epsabs, limit, maxp1, limlst])
    quad_qawf (f, x, a, omega, trig, [epsabs, limit, maxp1, limlst])

Calculates a Fourier cosine or Fourier sine transform on a semi-infinite interval using the Quadpack QAWF function. The same approach as in quad_qawo is applied on successive finite intervals, and convergence acceleration by means of the Epsilon algorithm (Wynn, 1956) is applied to the series of the integral contributions.

quad_qawf computes the integral

$$ \int_a^\infty f(x) \, w(x) \, dx $$

The weight function w is selected by trig:

cos
\(w(x) = \cos\omega x\)
sin
\(w(x) = \sin\omega x\)

The integrand may be specified as the name of a Maxima or Lisp function or operator, a Maxima lambda expression, or a general Maxima expression.

The keyword arguments are optional and may be specified in any order. They all take the form key=val. The keyword arguments are:

epsabs

Desired absolute error of approximation. Default is 1d-10.

limit

Size of internal work array. (limit - limlst)/2 is the maximum number of subintervals to use. Default is 200.

maxp1

Maximum number of Chebyshev moments. Must be greater than 0. Default is 100.

limlst

Upper bound on the number of cycles. Must be greater than or equal to 3. Default is 10.

quad_qawf returns a list of four elements:

The error code (fourth element of the return value) can have the values:

0

no problems were encountered;

1

too many sub-intervals were done;

2

excessive roundoff error is detected;

3

extremely bad integrand behavior occurs;

6

if the input is invalid.

Examples:

(%i1) quad_qawf (exp(-x^2), x, 0, 1, 'cos, 'epsabs=1d-9);
(%o1)   [.6901942235215714, 2.84846300257552E-11, 215, 0]
(%i2) integrate (exp(-x^2)*cos(x), x, 0, inf);
                          - 1/4
                        %e      sqrt(%pi)
(%o2)                   -----------------
                                2
(%i3) ev (%, numer);
(%o3)                   .6901942235215714
Function: quad_qawo
    quad_qawo (f(x), x, a, b, omega, trig, [epsrel, epsabs, limit, maxp1, limlst])
    quad_qawo (f, x, a, b, omega, trig, [epsrel, epsabs, limit, maxp1, limlst])

Integration of \(\cos(\omega x) f(x)\) or \(\sin(\omega x)\) over a finite interval, where \(\omega\) is a constant. The rule evaluation component is based on the modified Clenshaw-Curtis technique. quad_qawo applies adaptive subdivision with extrapolation, similar to quad_qags.

quad_qawo computes the integral using the Quadpack QAWO routine:

$$ \int_a^b f(x) \, w(x) \, dx $$

The weight function w is selected by trig:

cos
\(w(x) = \cos\omega x\)
sin
\(w(x) = \sin\omega x\)

The integrand may be specified as the name of a Maxima or Lisp function or operator, a Maxima lambda expression, or a general Maxima expression.

The keyword arguments are optional and may be specified in any order. They all take the form key=val. The keyword arguments are:

epsrel

Desired relative error of approximation. Default is 1d-8.

epsabs

Desired absolute error of approximation. Default is 0.

limit

Size of internal work array. limit/2 is the maximum number of subintervals to use. Default is 200.

maxp1

Maximum number of Chebyshev moments. Must be greater than 0. Default is 100.

limlst

Upper bound on the number of cycles. Must be greater than or equal to 3. Default is 10.

quad_qawo returns a list of four elements:

The error code (fourth element of the return value) can have the values:

0

no problems were encountered;

1

too many sub-intervals were done;

2

excessive roundoff error is detected;

3

extremely bad integrand behavior occurs;

6

if the input is invalid.

Examples:

(%i1) quad_qawo (x^(-1/2)*exp(-2^(-2)*x), x, 1d-8, 20*2^2, 1, cos);
(%o1)     [1.376043389877692, 4.72710759424899E-11, 765, 0]
(%i2) rectform (integrate (x^(-1/2)*exp(-2^(-alpha)*x) * cos(x),
      x, 0, inf));
                   alpha/2 - 1/2            2 alpha
        sqrt(%pi) 2              sqrt(sqrt(2        + 1) + 1)
(%o2)   -----------------------------------------------------
                               2 alpha
                         sqrt(2        + 1)
(%i3) ev (%, alpha=2, numer);
(%o3)                     1.376043390090716
Function: quad_qaws
    quad_qaws (f(x), x, a, b, alpha, beta, wfun, [epsrel, epsabs, limit])
    quad_qaws (f, x, a, b, alpha, beta, wfun, [epsrel, epsabs, limit])

Integration of w(x) f(x) over a finite interval, where w(x) is a certain algebraic or logarithmic function. A globally adaptive subdivision strategy is applied, with modified Clenshaw-Curtis integration on the subintervals which contain the endpoints of the interval of integration.

quad_qaws computes the integral using the Quadpack QAWS routine:

$$ \int_a^b f(x) \, w(x) \, dx $$

The weight function w is selected by wfun:

1
\(w(x) = (x - a)^\alpha (b - x)^\beta\)
2
\(w(x) = (x - a)^\alpha (b - x)^\beta \log(x - a)\)
3
\(w(x) = (x - a)^\alpha (b - x)^\beta \log(b - x)\)
4
\(w(x) = (x - a)^\alpha (b - x)^\beta \log(x - a) \log(b - x)\)

The integrand may be specified as the name of a Maxima or Lisp function or operator, a Maxima lambda expression, or a general Maxima expression.

The keyword arguments are optional and may be specified in any order. They all take the form key=val. The keyword arguments are:

epsrel

Desired relative error of approximation. Default is 1d-8.

epsabs

Desired absolute error of approximation. Default is 0.

limit

Size of internal work array. limitis the maximum number of subintervals to use. Default is 200.

quad_qaws returns a list of four elements:

The error code (fourth element of the return value) can have the values:

0

no problems were encountered;

1

too many sub-intervals were done;

2

excessive roundoff error is detected;

3

extremely bad integrand behavior occurs;

6

if the input is invalid.

Examples:

(%i1) quad_qaws (1/(x+1+2^(-4)), x, -1, 1, -0.5, -0.5, 1,
                 'epsabs=1d-9);
(%o1)     [8.750097361672832, 1.24321522715422E-10, 170, 0]
(%i2) integrate ((1-x*x)^(-1/2)/(x+1+2^(-alpha)), x, -1, 1);
       alpha
Is  4 2      - 1  positive, negative, or zero?

pos;
                          alpha         alpha
                   2 %pi 2      sqrt(2 2      + 1)
(%o2)              -------------------------------
                               alpha
                            4 2      + 2
(%i3) ev (%, alpha=4, numer);
(%o3)                     8.750097361672829
Function: quad_qagp
    quad_qagp (f(x), x, a, b, points, [epsrel, epsabs, limit])
    quad_qagp (f, x, a, b, points, [epsrel, epsabs, limit])

Integration of a general function over a finite interval. quad_qagp implements globally adaptive interval subdivision with extrapolation (de Doncker, 1978) by the Epsilon algorithm (Wynn, 1956).

quad_qagp computes the integral

$$ \int_a^b f(x) \, dx $$

The function to be integrated is f(x), with dependent variable x, and the function is to be integrated between the limits a and b.

The integrand may be specified as the name of a Maxima or Lisp function or operator, a Maxima lambda expression, or a general Maxima expression.

To help the integrator, the user must supply a list of points where the integrand is singular or discontinuous.

The keyword arguments are optional and may be specified in any order. They all take the form key=val. The keyword arguments are:

epsrel

Desired relative error of approximation. Default is 1d-8.

epsabs

Desired absolute error of approximation. Default is 0.

limit

Size of internal work array. limit is the maximum number of subintervals to use. Default is 200.

quad_qagp returns a list of four elements:

The error code (fourth element of the return value) can have the values:

0

no problems were encountered;

1

too many sub-intervals were done;

2

excessive roundoff error is detected;

3

extremely bad integrand behavior occurs;

4

failed to converge

5

integral is probably divergent or slowly convergent

6

if the input is invalid.

Examples:

(%i1) quad_qagp(x^3*log(abs((x^2-1)*(x^2-2))),x,0,3,[1,sqrt(2)]);
(%o1)   [52.74074838347143, 2.6247632689546663e-7, 1029, 0]
(%i2) quad_qags(x^3*log(abs((x^2-1)*(x^2-2))), x, 0, 3);
(%o2)   [52.74074847951494, 4.088443219529836e-7, 1869, 0]

The integrand has singularities at 1 and sqrt(2) so we supply these points to quad_qagp. We also note that quad_qagp is more accurate and more efficient that quad_qags.

Function: quad_control (parameter, [value])

Control error handling for quadpack. The parameter should be one of the following symbols:

current_error

The current error number

control

Controls if messages are printed or not. If it is set to zero or less, messages are suppressed.

max_message

The maximum number of times any message is to be printed.

If value is not given, then the current value of the parameter is returned. If value is given, the value of parameter is set to the given value.


Next: , Previous: Integration, Up: Top   [Contents][Index]

19 Equations


Previous: Equations, Up: Equations   [Contents][Index]

19.1 Functions and Variables for Equations

System variable: %rnum

Default value: 0

%rnum is the counter for the %r variables introduced in solutions by solve and algsys.. The next %r variable is numbered %rnum+1.

See also %rnum_list.

System variable: %rnum_list

Default value: []

%rnum_list is the list of variables introduced in solutions by solve and algsys. %r variables are added to %rnum_list in the order they are created. This is convenient for doing substitutions into the solution later on.

See also %rnum.

It’s recommended to use this list rather than doing concat ('%r, j).

(%i1) solve ([x + y = 3], [x,y]);
(%o1)              [[x = 3 - %r1, y = %r1]]
(%i2) %rnum_list;
(%o2)                       [%r1]
(%i3) sol : solve ([x + 2*y + 3*z = 4], [x,y,z]);
(%o3)   [[x = - 2 %r3 - 3 %r2 + 4, y = %r3, z = %r2]]
(%i4) %rnum_list;
(%o4)                     [%r2, %r3]
(%i5) for i : 1 thru length (%rnum_list) do
        sol : subst (t[i], %rnum_list[i], sol)$
(%i6) sol;
(%o6)     [[x = - 2 t  - 3 t  + 4, y = t , z = t ]]
                     2      1           2       1
Option variable: algepsilon

Default value: 10^8

algepsilon is used by algsys.

Option variable: algexact

Default value: false

algexact affects the behavior of algsys as follows:

If algexact is true, algsys always calls solve and then uses realroots on solve’s failures.

If algexact is false, solve is called only if the eliminant was not univariate, or if it was a quadratic or biquadratic.

Thus algexact: true does not guarantee only exact solutions, just that algsys will first try as hard as it can to give exact solutions, and only yield approximations when all else fails.

Function: algsys
    algsys ([expr_1, …, expr_m], [x_1, …, x_n])
    algsys ([eqn_1, …, eqn_m], [x_1, …, x_n])

Solves the simultaneous polynomials expr_1, …, expr_m or polynomial equations eqn_1, …, eqn_m for the variables x_1, …, x_n. An expression expr is equivalent to an equation expr = 0. There may be more equations than variables or vice versa.

algsys returns a list of solutions, with each solution given as a list of equations stating values of the variables x_1, …, x_n which satisfy the system of equations. If algsys cannot find a solution, an empty list [] is returned.

The symbols %r1, %r2, …, are introduced as needed to represent arbitrary parameters in the solution; these variables are also appended to the list %rnum_list.

The method is as follows:

  1. First the equations are factored and split into subsystems.
  2. For each subsystem S_i, an equation E and a variable x are selected. The variable is chosen to have lowest nonzero degree. Then the resultant of E and E_j with respect to x is computed for each of the remaining equations E_j in the subsystem S_i. This yields a new subsystem S_i’ in one fewer variables, as x has been eliminated. The process now returns to (1).
  3. Eventually, a subsystem consisting of a single equation is obtained. If the equation is multivariate and no approximations in the form of floating point numbers have been introduced, then solve is called to find an exact solution.

    In some cases, solve is not be able to find a solution, or if it does the solution may be a very large expression.

    If the equation is univariate and is either linear, quadratic, or biquadratic, then again solve is called if no approximations have been introduced. If approximations have been introduced or the equation is not univariate and neither linear, quadratic, or biquadratic, then if the switch realonly is true, the function realroots is called to find the real-valued solutions. If realonly is false, then allroots is called which looks for real and complex-valued solutions.

    If algsys produces a solution which has fewer significant digits than required, the user can change the value of algepsilon to a higher value.

    If algexact is set to true, solve will always be called.

  4. Finally, the solutions obtained in step (3) are substituted into previous levels and the solution process returns to (1).

When algsys encounters a multivariate equation which contains floating point approximations (usually due to its failing to find exact solutions at an earlier stage), then it does not attempt to apply exact methods to such equations and instead prints the message: "algsys cannot solve - system too complicated."

Interactions with radcan can produce large or complicated expressions. In that case, it may be possible to isolate parts of the result with pickapart or reveal.

Occasionally, radcan may introduce an imaginary unit %i into a solution which is actually real-valued.

Examples:

(%i1) e1: 2*x*(1 - a1) - 2*(x - 1)*a2;
(%o1)              2 (1 - a1) x - 2 a2 (x - 1)
(%i2) e2: a2 - a1; 
(%o2)                        a2 - a1
(%i3) e3: a1*(-y - x^2 + 1); 
                                   2
(%o3)                   a1 (- y - x  + 1)
(%i4) e4: a2*(y - (x - 1)^2);
                                       2
(%o4)                   a2 (y - (x - 1) )
(%i5) algsys ([e1, e2, e3, e4], [x, y, a1, a2]);
(%o5) [[x = 0, y = %r1, a1 = 0, a2 = 0], 

                                  [x = 1, y = 0, a1 = 1, a2 = 1]]
(%i6) e1: x^2 - y^2;
                              2    2
(%o6)                        x  - y
(%i7) e2: -1 - y + 2*y^2 - x + x^2;
                         2        2
(%o7)                 2 y  - y + x  - x - 1
(%i8) algsys ([e1, e2], [x, y]);
                 1            1
(%o8) [[x = - -------, y = -------], 
              sqrt(3)      sqrt(3)

        1              1             1        1
[x = -------, y = - -------], [x = - -, y = - -], [x = 1, y = 1]]
     sqrt(3)        sqrt(3)          3        3
Function: allroots
    allroots (expr)
    allroots (eqn)

Computes numerical approximations of the real and complex roots of the polynomial expr or polynomial equation eqn of one variable.

The flag polyfactor when true causes allroots to factor the polynomial over the real numbers if the polynomial is real, or over the complex numbers, if the polynomial is complex.

allroots may give inaccurate results in case of multiple roots. If the polynomial is real, allroots (%i*p) may yield more accurate approximations than allroots (p), as allroots invokes a different algorithm in that case.

allroots rejects non-polynomials. It requires that the numerator after rat’ing should be a polynomial, and it requires that the denominator be at most a complex number. As a result of this allroots will always return an equivalent (but factored) expression, if polyfactor is true.

For complex polynomials an algorithm by Jenkins and Traub is used (Algorithm 419, Comm. ACM, vol. 15, (1972), p. 97). For real polynomials the algorithm used is due to Jenkins (Algorithm 493, ACM TOMS, vol. 1, (1975), p.178).

Examples:

(%i1) eqn: (1 + 2*x)^3 = 13.5*(1 + x^5);
                            3          5
(%o1)              (2 x + 1)  = 13.5 (x  + 1)
(%i2) soln: allroots (eqn);
(%o2) [x = .8296749902129361, x = - 1.015755543828121, 

x = .9659625152196369 %i - .4069597231924075, 

x = - .9659625152196369 %i - .4069597231924075, x = 1.0]
(%i3) for e in soln
        do (e2: subst (e, eqn), disp (expand (lhs(e2) - rhs(e2))));
                      - 3.5527136788005E-15

                     - 5.32907051820075E-15

         4.44089209850063E-15 %i - 4.88498130835069E-15

        - 4.44089209850063E-15 %i - 4.88498130835069E-15

                       3.5527136788005E-15

(%o3)                         done
(%i4) polyfactor: true$
(%i5) allroots (eqn);
(%o5) - 13.5 (x - 1.0) (x - .8296749902129361)

                           2
 (x + 1.015755543828121) (x  + .8139194463848151 x

 + 1.098699797110288)
Function: bfallroots
    bfallroots (expr)
    bfallroots (eqn)

Computes numerical approximations of the real and complex roots of the polynomial expr or polynomial equation eqn of one variable.

In all respects, bfallroots is identical to allroots except that bfallroots computes the roots using bigfloats. See allroots for more information.

Option variable: backsubst

Default value: true

When backsubst is false, prevents back substitution in linsolve after the equations have been triangularized. This may be helpful in very big problems where back substitution would cause the generation of extremely large expressions.

(%i1) eq1 : x + y + z = 6$
(%i2) eq2 : x - y + z = 2$
(%i3) eq3 : x + y - z = 0$
(%i4) backsubst : false$
(%i5) linsolve ([eq1, eq2, eq3], [x,y,z]);
(%o5)             [x = z - y, y = 2, z = 3]
(%i6) backsubst : true$
(%i7) linsolve ([eq1, eq2, eq3], [x,y,z]);
(%o7)               [x = 1, y = 2, z = 3]
Option variable: breakup

Default value: true

When breakup is true, solve expresses solutions of cubic and quartic equations in terms of common subexpressions, which are assigned to intermediate expression labels (%t1, %t2, etc.). Otherwise, common subexpressions are not identified.

breakup: true has an effect only when programmode is false.

Examples:

(%i1) programmode: false$
(%i2) breakup: true$
(%i3) solve (x^3 + x^2 - 1);

                        sqrt(23)    25 1/3
(%t3)                  (--------- + --)
                        6 sqrt(3)   54
Solution:

                                      sqrt(3) %i   1
                                      ---------- - -
                sqrt(3) %i   1            2        2   1
(%t4)    x = (- ---------- - -) %t3 + -------------- - -
                    2        2            9 %t3        3

                                      sqrt(3) %i   1
                                    - ---------- - -
              sqrt(3) %i   1              2        2   1
(%t5)    x = (---------- - -) %t3 + ---------------- - -
                  2        2             9 %t3         3

                                   1     1
(%t6)                  x = %t3 + ----- - -
                                 9 %t3   3
(%o6)                    [%t4, %t5, %t6]
(%i6) breakup: false$
(%i7) solve (x^3 + x^2 - 1);
Solution:

             sqrt(3) %i   1
             ---------- - -
                 2        2        sqrt(23)    25 1/3
(%t7) x = --------------------- + (--------- + --)
             sqrt(23)    25 1/3    6 sqrt(3)   54
          9 (--------- + --)
             6 sqrt(3)   54

                                              sqrt(3) %i   1    1
                                           (- ---------- - -) - -
                                                  2        2    3
           sqrt(23)    25 1/3  sqrt(3) %i   1
(%t8) x = (--------- + --)    (---------- - -)
           6 sqrt(3)   54          2        2

                                            sqrt(3) %i   1
                                          - ---------- - -
                                                2        2      1
                                      + --------------------- - -
                                           sqrt(23)    25 1/3   3
                                        9 (--------- + --)
                                           6 sqrt(3)   54
            sqrt(23)    25 1/3             1             1
(%t9)  x = (--------- + --)    + --------------------- - -
            6 sqrt(3)   54          sqrt(23)    25 1/3   3
                                 9 (--------- + --)
                                    6 sqrt(3)   54
(%o9)                    [%t7, %t8, %t9]
Function: dimension
    dimension (eqn)
    dimension (eqn_1, …, eqn_n)

dimen is a package for dimensional analysis. load ("dimen") loads this package. demo ("dimen") displays a short demonstration.

Option variable: dispflag

Default value: true

If set to false within a block will inhibit the display of output generated by the solve functions called from within the block. Termination of the block with a dollar sign, $, sets dispflag to false.

Function: funcsolve (eqn, g(t))

Returns [g(t) = ...] or [], depending on whether or not there exists a rational function g(t) satisfying eqn, which must be a first order, linear polynomial in (for this case) g(t) and g(t+1)

(%i1) eqn: (n + 1)*f(n) - (n + 3)*f(n + 1)/(n + 1) =
      (n - 1)/(n + 2);
                            (n + 3) f(n + 1)   n - 1
(%o1)        (n + 1) f(n) - ---------------- = -----
                                 n + 1         n + 2
(%i2) funcsolve (eqn, f(n));

Dependent equations eliminated:  (4 3)
                                   n
(%o2)                f(n) = ---------------
                            (n + 1) (n + 2)

Warning: this is a very rudimentary implementation – many safety checks and obvious generalizations are missing.

Option variable: globalsolve

Default value: false

When globalsolve is true, solved-for variables are assigned the solution values found by linsolve, and by solve when solving two or more linear equations.

When globalsolve is false, solutions found by linsolve and by solve when solving two or more linear equations are expressed as equations, and the solved-for variables are not assigned.

When solving anything other than two or more linear equations, solve ignores globalsolve. Other functions which solve equations (e.g., algsys) always ignore globalsolve.

Examples:

(%i1) globalsolve: true$
(%i2) solve ([x + 3*y = 2, 2*x - y = 5], [x, y]);
Solution

                                 17
(%t2)                        x : --
                                 7

                                   1
(%t3)                        y : - -
                                   7
(%o3)                     [[%t2, %t3]]
(%i3) x;
                               17
(%o3)                          --
                               7
(%i4) y;
                                 1
(%o4)                          - -
                                 7
(%i5) globalsolve: false$
(%i6) kill (x, y)$
(%i7) solve ([x + 3*y = 2, 2*x - y = 5], [x, y]);
Solution

                                 17
(%t7)                        x = --
                                 7

                                   1
(%t8)                        y = - -
                                   7
(%o8)                     [[%t7, %t8]]
(%i8) x;
(%o8)                           x
(%i9) y;
(%o9)                           y
Function: ieqn (ie, unk, tech, n, guess)

inteqn is a package for solving integral equations. load ("inteqn") loads this package.

ie is the integral equation; unk is the unknown function; tech is the technique to be tried from those given in the lists below; (tech = first means: try the first technique which finds a solution; tech = all means: try all applicable techniques); n is the maximum number of terms to take for taylor, neumann, firstkindseries, or fredseries (it is also the maximum depth of recursion for the differentiation method); guess is the initial guess for neumann or firstkindseries.

Two types of equations are considered. A second-kind equation of the following form,

                           b(x)
                          /
                          [
        p(x) = q(x, p(x), I     w(x, u, p(x), p(u)) du)
                          ]
                          /
                           a(x)

and a first-kind equation with the form

                         b(x)
                        /
                        [
                 f(x) = I     w(x, u, p(u)) du
                        ]
                        /
                         a(x)

The different solution techniques used require particular forms of the expressions q and w. The techniques available are the following:

Second-kind equations

First-kind equations

The default values for the 2nd thru 5th parameters in the calling form are:

unk: p(x), where p is the first function encountered in an integrand which is unknown to Maxima and x is the variable which occurs as an argument to the first occurrence of p found outside of an integral in the case of secondkind equations, or is the only other variable besides the variable of integration in firstkind equations. If the attempt to search for x fails, the user will be asked to supply the independent variable. tech: first. n: 1. guess: none which will cause neumann and firstkindseries to use f(x) as an initial guess.

Examples:

(%i1) load("inteqn")$

(%i2) e: p(x) - 1 -x + cos(x) + 'integrate(cos(x-u)*p(u),u,0,x)$

(%i3) ieqn(e, p(x), 'transform);
default 4th arg, number of iterations or coll. parms.:  1 
default 5th arg, initial guess:  none 

(%t3)                           [x, transform]
(%o3)                               [%t3]
(%i4) e: 2*'integrate(p(x*sin(u)), u, 0, %pi/2) - a*x - b$

(%i5) ieqn(e, p(x), 'firstkindseries);
default 4th arg, number of iterations or coll. parms.:  1 
default 5th arg, initial guess:  none 

(%t5)          [2 a x + %pi b, firstkindseries, 1, approximate]
(%o5)                               [%t5]
Option variable: ieqnprint

Default value: true

ieqnprint governs the behavior of the result returned by the ieqn command. When ieqnprint is false, the lists returned by the ieqn function are of the form

[solution, technique used, nterms, flag]

where flag is absent if the solution is exact.

Otherwise, it is the word approximate or incomplete corresponding to an inexact or non-closed form solution, respectively. If a series method was used, nterms gives the number of terms taken (which could be less than the n given to ieqn if an error prevented generation of further terms).

Function: lhs (expr)

Returns the left-hand side (that is, the first argument) of the expression expr, when the operator of expr is one of the relational operators < <= = # equal notequal >= >, one of the assignment operators := ::= : ::, or a user-defined binary infix operator, as declared by infix.

When expr is an atom or its operator is something other than the ones listed above, lhs returns expr.

See also rhs.

Examples:

(%i1) e: aa + bb = cc;
(%o1)                     bb + aa = cc
(%i2) lhs (e);
(%o2)                        bb + aa
(%i3) rhs (e);
(%o3)                          cc
(%i4) [lhs (aa < bb), lhs (aa <= bb), lhs (aa >= bb),
       lhs (aa > bb)];
(%o4)                   [aa, aa, aa, aa]
(%i5) [lhs (aa = bb), lhs (aa # bb), lhs (equal (aa, bb)),
       lhs (notequal (aa, bb))];
(%o5)                   [aa, aa, aa, aa]
(%i6) e1: '(foo(x) := 2*x);
(%o6)                     foo(x) := 2 x
(%i7) e2: '(bar(y) ::= 3*y);
(%o7)                    bar(y) ::= 3 y
(%i8) e3: '(x : y);
(%o8)                         x : y
(%i9) e4: '(x :: y);
(%o9)                        x :: y
(%i10) [lhs (e1), lhs (e2), lhs (e3), lhs (e4)];
(%o10)               [foo(x), bar(y), x, x]
(%i11) infix ("][");
(%o11)                         ][
(%i12) lhs (aa ][ bb);
(%o12)                         aa
Function: linsolve ([expr_1, …, expr_m], [x_1, …, x_n])

Solves the list of simultaneous linear equations for the list of variables. The expressions must each be polynomials in the variables and may be equations. If the length of the list of variables doesn’t match the number of linearly-independent equations to solve the result will be an empty list.

When globalsolve is true, each solved-for variable is bound to its value in the solution of the equations.

When backsubst is false, linsolve does not carry out back substitution after the equations have been triangularized. This may be necessary in very big problems where back substitution would cause the generation of extremely large expressions.

When linsolve_params is true, linsolve also generates the %r symbols used to represent arbitrary parameters described in the manual under algsys. Otherwise, linsolve solves an under-determined system of equations with some variables expressed in terms of others.

When programmode is false, linsolve displays the solution with intermediate expression (%t) labels, and returns the list of labels.

See also algsys, eliminate. and solve.

Examples:

(%i1) e1: x + z = y;
(%o1)                       z + x = y
(%i2) e2: 2*a*x - y = 2*a^2;
                                       2
(%o2)                   2 a x - y = 2 a
(%i3) e3: y - 2*z = 2;
(%o3)                      y - 2 z = 2
(%i4) [globalsolve: false, programmode: true];
(%o4)                     [false, true]
(%i5) linsolve ([e1, e2, e3], [x, y, z]);
(%o5)            [x = a + 1, y = 2 a, z = a - 1]
(%i6) [globalsolve: false, programmode: false];
(%o6)                    [false, false]
(%i7) linsolve ([e1, e2, e3], [x, y, z]);
Solution

(%t7)                       z = a - 1

(%t8)                        y = 2 a

(%t9)                       x = a + 1
(%o9)                    [%t7, %t8, %t9]
(%i9) ''%;
(%o9)            [z = a - 1, y = 2 a, x = a + 1]
(%i10) [globalsolve: true, programmode: false];
(%o10)                    [true, false]
(%i11) linsolve ([e1, e2, e3], [x, y, z]);
Solution

(%t11)                      z : a - 1

(%t12)                       y : 2 a

(%t13)                      x : a + 1
(%o13)                 [%t11, %t12, %t13]
(%i13) ''%;
(%o13)           [z : a - 1, y : 2 a, x : a + 1]
(%i14) [x, y, z];
(%o14)                 [a + 1, 2 a, a - 1]
(%i15) [globalsolve: true, programmode: true];
(%o15)                    [true, true]
(%i16) linsolve ([e1, e2, e3], '[x, y, z]);
(%o16)           [x : a + 1, y : 2 a, z : a - 1]
(%i17) [x, y, z];
(%o17)                 [a + 1, 2 a, a - 1]
Option variable: linsolvewarn

Default value: true

When linsolvewarn is true, linsolve prints a message "Dependent equations eliminated".

Option variable: linsolve_params

Default value: true

When linsolve_params is true, linsolve also generates the %r symbols used to represent arbitrary parameters described in the manual under algsys. Otherwise, linsolve solves an under-determined system of equations with some variables expressed in terms of others.

System variable: multiplicities

Default value: not_set_yet

multiplicities is set to a list of the multiplicities of the individual solutions returned by solve or realroots.

Function: nroots (p, low, high)

Returns the number of real roots of the real univariate polynomial p in the half-open interval (low, high]. The endpoints of the interval may be minf or inf.

nroots uses the method of Sturm sequences.

(%i1) p: x^10 - 2*x^4 + 1/2$
(%i2) nroots (p, -6, 9.1);
(%o2)                           4
Function: nthroot (p, n)

where p is a polynomial with integer coefficients and n is a positive integer returns q, a polynomial over the integers, such that q^n = p or prints an error message indicating that p is not a perfect nth power. This routine is much faster than factor or even sqfr.

Option variable: polyfactor

Default value: false

The option variable polyfactor when true causes allroots and bfallroots to factor the polynomial over the real numbers if the polynomial is real, or over the complex numbers, if the polynomial is complex.

See allroots for an example.

Option variable: programmode

Default value: true

When programmode is true, solve, realroots, allroots, and linsolve return solutions as elements in a list. (Except when backsubst is set to false, in which case programmode: false is assumed.)

When programmode is false, solve, etc. create intermediate expression labels %t1, %t2, etc., and assign the solutions to them.

Option variable: realonly

Default value: false

When realonly is true, algsys returns only those solutions which are free of %i.

Function: realroots
    realroots (expr, bound)
    realroots (eqn, bound)
    realroots (expr)
    realroots (eqn)

Computes rational approximations of the real roots of the polynomial expr or polynomial equation eqn of one variable, to within a tolerance of bound. Coefficients of expr or eqn must be literal numbers; symbol constants such as %pi are rejected.

realroots assigns the multiplicities of the roots it finds to the global variable multiplicities.

realroots constructs a Sturm sequence to bracket each root, and then applies bisection to refine the approximations. All coefficients are converted to rational equivalents before searching for roots, and computations are carried out by exact rational arithmetic. Even if some coefficients are floating-point numbers, the results are rational (unless coerced to floats by the `float' or `numer' flags).

When bound is less than 1, all integer roots are found exactly. When bound is unspecified, it is assumed equal to the global variable rootsepsilon.

When the global variable programmode is true, realroots returns a list of the form [x = x_1, x = x_2, ...]. When programmode is false, realroots creates intermediate expression labels %t1, %t2, …, assigns the results to them, and returns the list of labels.

See also allroots, bfallroots, `guess_exact_value', and lhs.

Examples:

(%i1) realroots (-1 - x + x^5, 5e-6);
                               612003
(%o1)                     [x = ------]
                               524288
(%i2) ev (%[1], float);
(%o2)                 x = 1.167303085327148
(%i3) ev (-1 - x + x^5, %);
(%o3)                - 7.396496210176905E-6
(%i1) realroots (expand ((1 - x)^5 * (2 - x)^3 * (3 - x)), 1e-20);
(%o1)                 [x = 1, x = 2, x = 3]
(%i2) multiplicities;
(%o2)                       [5, 3, 1]
Function: rhs (expr)

Returns the right-hand side (that is, the second argument) of the expression expr, when the operator of expr is one of the relational operators < <= = # equal notequal >= >, one of the assignment operators := ::= : ::, or a user-defined binary infix operator, as declared by infix.

When expr is an atom or its operator is something other than the ones listed above, rhs returns 0.

See also lhs.

Examples:

(%i1) e: aa + bb = cc;
(%o1)                     bb + aa = cc
(%i2) lhs (e);
(%o2)                        bb + aa
(%i3) rhs (e);
(%o3)                          cc
(%i4) [rhs (aa < bb), rhs (aa <= bb), rhs (aa >= bb),
       rhs (aa > bb)];
(%o4)                   [bb, bb, bb, bb]
(%i5) [rhs (aa = bb), rhs (aa # bb), rhs (equal (aa, bb)),
       rhs (notequal (aa, bb))];
(%o5)                   [bb, bb, bb, bb]
(%i6) e1: '(foo(x) := 2*x);
(%o6)                     foo(x) := 2 x
(%i7) e2: '(bar(y) ::= 3*y);
(%o7)                    bar(y) ::= 3 y
(%i8) e3: '(x : y);
(%o8)                         x : y
(%i9) e4: '(x :: y);
(%o9)                        x :: y
(%i10) [rhs (e1), rhs (e2), rhs (e3), rhs (e4)];
(%o10)                  [2 x, 3 y, y, y]
(%i11) infix ("][");
(%o11)                         ][
(%i12) rhs (aa ][ bb);
(%o12)                         bb
Option variable: rootsconmode

Default value: true

rootsconmode governs the behavior of the rootscontract command. See rootscontract for details.

Function: rootscontract (expr)

Converts products of roots into roots of products. For example, rootscontract (sqrt(x)*y^(3/2)) yields sqrt(x*y^3).

When radexpand is true and domain is real, rootscontract converts abs into sqrt, e.g., rootscontract (abs(x)*sqrt(y)) yields sqrt(x^2*y).

There is an option rootsconmode affecting rootscontract as follows:

Problem            Value of        Result of applying
                  rootsconmode        rootscontract
      
x^(1/2)*y^(3/2)      false          (x*y^3)^(1/2)
x^(1/2)*y^(1/4)      false          x^(1/2)*y^(1/4)
x^(1/2)*y^(1/4)      true           (x*y^(1/2))^(1/2)
x^(1/2)*y^(1/3)      true           x^(1/2)*y^(1/3)
x^(1/2)*y^(1/4)      all            (x^2*y)^(1/4)
x^(1/2)*y^(1/3)      all            (x^3*y^2)^(1/6)

When rootsconmode is false, rootscontract contracts only with respect to rational number exponents whose denominators are the same. The key to the rootsconmode: true examples is simply that 2 divides into 4 but not into 3. rootsconmode: all involves taking the least common multiple of the denominators of the exponents.

rootscontract uses ratsimp in a manner similar to `logcontract'.

Examples:

(%i1) rootsconmode: false$
(%i2) rootscontract (x^(1/2)*y^(3/2));
                                   3
(%o2)                      sqrt(x y )
(%i3) rootscontract (x^(1/2)*y^(1/4));
                                   1/4
(%o3)                     sqrt(x) y
(%i4) rootsconmode: true$
(%i5) rootscontract (x^(1/2)*y^(1/4));
(%o5)                    sqrt(x sqrt(y))
(%i6) rootscontract (x^(1/2)*y^(1/3));
                                   1/3
(%o6)                     sqrt(x) y
(%i7) rootsconmode: all$
(%i8) rootscontract (x^(1/2)*y^(1/4));
                              2   1/4
(%o8)                       (x  y)
(%i9) rootscontract (x^(1/2)*y^(1/3));
                             3  2 1/6
(%o9)                      (x  y )
(%i10) rootsconmode: false$
(%i11) rootscontract (sqrt(sqrt(x) + sqrt(1 + x))
                    *sqrt(sqrt(1 + x) - sqrt(x)));
(%o11)                          1
(%i12) rootsconmode: true$
(%i13) rootscontract (sqrt(5+sqrt(5)) - 5^(1/4)*sqrt(1+sqrt(5)));
(%o13)                          0
Option variable: rootsepsilon

Default value: 1.0e-7

rootsepsilon is the tolerance which establishes the confidence interval for the roots found by the realroots function.

Function: solve
    solve (expr, x)
    solve (expr)
    solve ([eqn_1, …, eqn_n], [x_1, …, x_n])

Solves the algebraic equation expr for the variable x and returns a list of solution equations in x. If expr is not an equation, the equation expr = 0 is assumed in its place. x may be a function (e.g. f(x)), or other non-atomic expression except a sum or product. x may be omitted if expr contains only one variable. expr may be a rational expression, and may contain trigonometric functions, exponentials, etc.

The following method is used:

Let E be the expression and X be the variable. If E is linear in X then it is trivially solved for X. Otherwise if E is of the form A*X^N + B then the result is (-B/A)^1/N) times the N’th roots of unity.

If E is not linear in X then the gcd of the exponents of X in E (say N) is divided into the exponents and the multiplicity of the roots is multiplied by N. Then solve is called again on the result. If E factors then solve is called on each of the factors. Finally solve will use the quadratic, cubic, or quartic formulas where necessary.

In the case where E is a polynomial in some function of the variable to be solved for, say F(X), then it is first solved for F(X) (call the result C), then the equation F(X)=C can be solved for X provided the inverse of the function F is known.

breakup if false will cause solve to express the solutions of cubic or quartic equations as single expressions rather than as made up of several common subexpressions which is the default.

multiplicities - will be set to a list of the multiplicities of the individual solutions returned by solve, realroots, or allroots. Try apropos (solve) for the switches which affect solve. describe may then by used on the individual switch names if their purpose is not clear.

solve ([eqn_1, ..., eqn_n], [x_1, ..., x_n]) solves a system of simultaneous (linear or non-linear) polynomial equations by calling linsolve or algsys and returns a list of the solution lists in the variables. In the case of linsolve this list would contain a single list of solutions. It takes two lists as arguments. The first list represents the equations to be solved; the second list is a list of the unknowns to be determined. If the total number of variables in the equations is equal to the number of equations, the second argument-list may be omitted.

When programmode is false, solve displays solutions with intermediate expression (%t) labels, and returns the list of labels.

When globalsolve is true and the problem is to solve two or more linear equations, each solved-for variable is bound to its value in the solution of the equations.

Examples:

(%i1) solve (asin (cos (3*x))*(f(x) - 1), x);

solve: using arc-trig functions to get a solution.
Some solutions will be lost.
                            %pi
(%o1)                  [x = ---, f(x) = 1]
                             6
(%i2) ev (solve (5^f(x) = 125, f(x)), solveradcan);
                                log(125)
(%o2)                   [f(x) = --------]
                                 log(5)
(%i3) [4*x^2 - y^2 = 12, x*y - x = 2];
                      2    2
(%o3)             [4 x  - y  = 12, x y - x = 2]

(%i4) solve (%, [x, y]);
(%o4) [[x = 2, y = 2], [x = .5202594388652008 %i
 - .1331240357358706, y = .07678378523787788
 - 3.608003221870287 %i], [x = - .5202594388652008 %i
 - .1331240357358706, y = 3.608003221870287 %i
 + .07678378523787788], [x = - 1.733751846381093, 
y = - .1535675710019696]]

(%i5) solve (1 + a*x + x^3, x);

                                       3
              sqrt(3) %i   1   sqrt(4 a  + 27)   1 1/3
(%o5) [x = (- ---------- - -) (--------------- - -)
                  2        2      6 sqrt(3)      2

        sqrt(3) %i   1
       (---------- - -) a
            2        2
 - --------------------------, x = 
              3
      sqrt(4 a  + 27)   1 1/3
   3 (--------------- - -)
         6 sqrt(3)      2

                          3
 sqrt(3) %i   1   sqrt(4 a  + 27)   1 1/3
(---------- - -) (--------------- - -)
     2        2      6 sqrt(3)      2

         sqrt(3) %i   1
      (- ---------- - -) a
             2        2
 - --------------------------, x = 
              3
      sqrt(4 a  + 27)   1 1/3
   3 (--------------- - -)
         6 sqrt(3)      2

         3
 sqrt(4 a  + 27)   1 1/3               a
(--------------- - -)    - --------------------------]
    6 sqrt(3)      2                  3
                              sqrt(4 a  + 27)   1 1/3
                           3 (--------------- - -)
                                 6 sqrt(3)      2
(%i6) solve (x^3 - 1);
             sqrt(3) %i - 1        sqrt(3) %i + 1
(%o6)   [x = --------------, x = - --------------, x = 1]
                   2                     2
(%i7) solve (x^6 - 1);
           sqrt(3) %i + 1      sqrt(3) %i - 1
(%o7) [x = --------------, x = --------------, x = - 1, 
                 2                   2

                     sqrt(3) %i + 1        sqrt(3) %i - 1
               x = - --------------, x = - --------------, x = 1]
                           2                     2
(%i8) ev (x^6 - 1, %[1]);
                                      6
                      (sqrt(3) %i + 1)
(%o8)                 ----------------- - 1
                             64
(%i9) expand (%);
(%o9)                           0
(%i10) x^2 - 1;
                              2
(%o10)                       x  - 1
(%i11) solve (%, x);
(%o11)                  [x = - 1, x = 1]
(%i12) ev (%th(2), %[1]);
(%o12)                          0

The symbols %r are used to denote arbitrary constants in a solution.

(%i1) solve([x+y=1,2*x+2*y=2],[x,y]);

solve: dependent equations eliminated: (2)
(%o1)                      [[x = 1 - %r1, y = %r1]]

See algsys and %rnum_list for more information.

Option variable: solvedecomposes

Default value: true

When solvedecomposes is true, solve calls polydecomp if asked to solve polynomials.

Option variable: solveexplicit

Default value: false

When solveexplicit is true, inhibits solve from returning implicit solutions, that is, solutions of the form F(x) = 0 where F is some function.

Option variable: solvefactors

Default value: true

When solvefactors is false, solve does not try to factor the expression. The false setting may be desired in some cases where factoring is not necessary.

Option variable: solvenullwarn

Default value: true

When solvenullwarn is true, solve prints a warning message if called with either a null equation list or a null variable list. For example, solve ([], []) would print two warning messages and return [].

Option variable: solveradcan

Default value: false

When solveradcan is true, solve calls radcan which makes solve slower but will allow certain problems containing exponentials and logarithms to be solved.

Option variable: solvetrigwarn

Default value: true

When solvetrigwarn is true, solve may print a message saying that it is using inverse trigonometric functions to solve the equation, and thereby losing solutions.


Next: , Previous: Equations, Up: Top   [Contents][Index]

20 Дифференциальные уравнения


Next: , Previous: Дифференциальные уравнения, Up: Дифференциальные уравнения   [Contents][Index]

20.1 Дифференциальные уравнения в Maxima

Этот раздел описывает функции Maxima для аналитического решения некоторых типов дифференциальных уравнений первого и второго порядка. Для получения численного решения системы дифференциальных уравнений используйте дополнительный пакет dynamics, для графического представления в фазовом пространстве - пакет plotdf.


Previous: Дифференциальные уравнения в Maxima, Up: Дифференциальные уравнения   [Contents][Index]

20.2 Функции и переменные для дифференциальных уравнений

Функция: bc2 (solution, xval1, yval1, xval2, yval2)

Решает краевую задачу для дифференциального уравнения второго порядка. Здесь solution - общее решение уравнения, полученное ode2; xval1 задает значение независимой переменной в начальной точке в виде x = x1 и yval1 задает значение зависимой переменной в этой точке в виде y = y1. Выражения xval2 и yval2 определяют значения для этих переменных во второй точке, используя ту же запись.

Пример использования см. в ode2.

Функция: desolve (eqn, x)
Функция: desolve ([eqn_1, ..., eqn_n], [x_1, ..., x_n])

Функция desolve решает линейные системы обыкновенных дифференциальных уравнений при помощи преобразования Лапласа. Здесь eqn - дифференциальные уравнения со связанными переменными x_1, ..., x_n. Функциональная зависимость между x_1, ..., x_n или от независимой переменной, например, x, должна явно задаваться в переменных и их производных. Например, следующее определение двух уравнений неверно:

eqn_1: 'diff(f,x,2) = sin(x) + 'diff(g,x);
eqn_2: 'diff(f,x) + x^2 - f = 2*'diff(g,x,2);

Правильная запись -

eqn_1: 'diff(f(x),x,2) = sin(x) + 'diff(g(x),x);
eqn_2: 'diff(f(x),x) + x^2 - f(x) = 2*'diff(g(x),x,2);

Тогда вызов функции desolve будет иметь вид

desolve([eqn_1, eqn_2], [f(x),g(x)]);

Если известны начальные условия в x=0, то при помощи atvalue их можно дополнительно определить до вызова desolve.

(%i1) 'diff(f(x),x)='diff(g(x),x)+sin(x);
                 d           d
(%o1)            -- (f(x)) = -- (g(x)) + sin(x)
                 dx          dx
(%i2) 'diff(g(x),x,2)='diff(f(x),x)-cos(x);
                  2
                 d            d
(%o2)            --- (g(x)) = -- (f(x)) - cos(x)
                   2          dx
                 dx
(%i3) atvalue('diff(g(x),x),x=0,a);
(%o3)                           a
(%i4) atvalue(f(x),x=0,1);
(%o4)                           1
(%i5) desolve([%o1,%o2],[f(x),g(x)]);
                  x
(%o5) [f(x) = a %e  - a + 1, g(x) = 

                                                x
                                   cos(x) + a %e  - a + g(0) - 1]
(%i6) [%o1,%o2],%o5,diff;
             x       x      x                x
(%o6)   [a %e  = a %e , a %e  - cos(x) = a %e  - cos(x)]

Если desolve не может получить решение, возвращается false.

Функция: ic1 (solution, xval, yval)

Решает задачи с начальными условиями для дифференциальных уравнений первого порядка. Здесь solution - общее решение уравнения, полученное ode2; xval задает начальное значение независимой переменной в виде x = x0, и yval задает начальное значение зависимой переменной в виде y = y0.

Пример использования см. в ode2.

Функция: ic2 (solution, xval, yval, dval)

Решает задачи с начальными условиями для дифференциальных уравнений второго порядка. Здесь solution - общее решение уравнения, полученное ode2; xval задает начальное значение независимой переменной в виде x = x0, yval задает начальное значение зависимой переменной в виде y = y0, и dval задает начальное значение для первой производной зависимой переменной по независимой в виде diff(y,x) = dy0 (перед diff не нужно ставить кавычку).

Пример использования см. в ode2.

Функция: ode2 (eqn, dvar, ivar)

Функция ode2 решает обыкновенное дифференциальное уравнение (ОДУ) первого или второго порядка. Она принимает три аргумента: ОДУ eqn, зависимую переменную dvar и независимую переменную ivar. При удачном результате возвращается явное или неявное решение относительно зависимой переменной. %c используется для представления константы интегрирования в случае уравнений первого порядка; %k1 и %k2 - константы в решениях уравнений второго порядка. Зависимость зависимой переменной от независимой не требуется указывать явно, как в случае с desolve, но независимая переменная должна всегда указываться в качестве третьего аргумента.

Если по каким-то причинам ode2 не может получить решение, возвращается false, и, возможно, печатается сообщение об ошибке. Методы решения уравнений первого порядка (в том порядке, в каком Maxima пытается их применять): линейный, разделение переменных, явный - возможно, используется интегрирующий множитель, однородное уравнение, уравнение Бернулли и обобщенный однородный метод.

Типы решаемых уравнений второго порядка: уравнение с постоянными коэффициентами, явное, линейное однородное с непостоянными коэффициентами, преобразующимися к постоянным, уравнение Эйлера (или равноразмерное), уравнения, решаемые методом вариации переменных, а также уравнения без независимой или зависимой переменной, сводимые для последующего решения к линейным уравнениям первого порядка.

В ходе решения ОДУ чисто для справки устанавливается несколько переменных: method указывает на использованный метод решения (например, linear), intfactor - использованный интегрирующий множитель, odeindex - коэффициент, примененный в методе Бернулли или обобщенном однородном методе, а yp - частное решение для метода вариации переменных.

Для решения задач с начальными условиями для уравнений первого и второго порядка доступны функции ic1 и ic2, а для решения краевых задач может использоваться функция bc2.

Пример:

(%i1) x^2*'diff(y,x) + 3*y*x = sin(x)/x;
                      2 dy           sin(x)
(%o1)                x  -- + 3 x y = ------
                        dx             x
(%i2) ode2(%,y,x);
                             %c - cos(x)
(%o2)                    y = -----------
                                  3
                                 x
(%i3) ic1(%o2,x=%pi,y=0);
                              cos(x) + 1
(%o3)                   y = - ----------
                                   3
                                  x
(%i4) 'diff(y,x,2) + y*'diff(y,x)^3 = 0;
                         2
                        d y      dy 3
(%o4)                   --- + y (--)  = 0
                          2      dx
                        dx
(%i5) ode2(%,y,x);
                      3
                     y  + 6 %k1 y
(%o5)                ------------ = x + %k2
                          6
(%i6) ratsimp(ic2(%o5,x=0,y=0,'diff(y,x)=2));
                             3
                          2 y  - 3 y
(%o6)                   - ---------- = x
                              6
(%i7) bc2(%o5,x=0,y=1,x=1,y=3);
                         3
                        y  - 10 y       3
(%o7)                   --------- = x - -
                            6           2


Next: , Previous: Дифференциальные уравнения, Up: Top   [Contents][Index]

21 Numerical


Next: , Up: Numerical   [Contents][Index]

21.1 Introduction to fast Fourier transform

The fft package comprises functions for the numerical (not symbolic) computation of the fast Fourier transform. This is limited to sequences whit length that is a power of two. For more general lengths, consider the fftpack5 package that supports sequences of any length, but is most efficient if the length is a product of small primes.


Next: , Previous: Introduction to fast Fourier transform, Up: Numerical   [Contents][Index]

21.2 Functions and Variables for fft

Function: polartorect (r, t)

Translates complex values of the form r %e^(%i t) to the form a + b %i, where r is the magnitude and t is the phase. r and t are 1-dimensional arrays of the same size. The array size need not be a power of 2.

The original values of the input arrays are replaced by the real and imaginary parts, a and b, on return. The outputs are calculated as

a = r cos(t)
b = r sin(t)

polartorect is the inverse function of recttopolar.

load("fft") loads this function. See also fft.

Function: recttopolar (a, b)

Translates complex values of the form a + b %i to the form r %e^(%i t), where a is the real part and b is the imaginary part. a and b are 1-dimensional arrays of the same size. The array size need not be a power of 2.

The original values of the input arrays are replaced by the magnitude and angle, r and t, on return. The outputs are calculated as

r = sqrt(a^2 + b^2)
t = atan2(b, a)

The computed angle is in the range -%pi to %pi.

recttopolar is the inverse function of polartorect.

load("fft") loads this function. See also fft.

Function: inverse_fft (y)

Computes the inverse complex fast Fourier transform. y is a list or array (named or unnamed) which contains the data to transform. The number of elements must be a power of 2. The elements must be literal numbers (integers, rationals, floats, or bigfloats) or symbolic constants, or expressions a + b*%i where a and b are literal numbers or symbolic constants.

inverse_fft returns a new object of the same type as y, which is not modified. Results are always computed as floats or expressions a + b*%i where a and b are floats. If bigfloat precision is needed the function bf_inverse_fft can be used instead as a drop-in replacement of inverse_fft that is slower, but supports bfloats.

The inverse discrete Fourier transform is defined as follows. Let x be the output of the inverse transform. Then for j from 0 through n - 1,

x[j] = sum(y[k] exp(-2 %i %pi j k / n), k, 0, n - 1)

As there are various sign and normalization conventions possible, this definition of the transform may differ from that used by other mathematical software.

load("fft") loads this function.

See also fft (forward transform), recttopolar, and polartorect.

Examples:

Real data.

(%i1) load ("fft") $
(%i2) fpprintprec : 4 $
(%i3) L : [1, 2, 3, 4, -1, -2, -3, -4] $
(%i4) L1 : inverse_fft (L);
(%o4) [0.0, 14.49 %i - .8284, 0.0, 2.485 %i + 4.828, 0.0, 
                       4.828 - 2.485 %i, 0.0, - 14.49 %i - .8284]
(%i5) L2 : fft (L1);
(%o5) [1.0, 2.0 - 2.168L-19 %i, 3.0 - 7.525L-20 %i, 
4.0 - 4.256L-19 %i, - 1.0, 2.168L-19 %i - 2.0, 
7.525L-20 %i - 3.0, 4.256L-19 %i - 4.0]
(%i6) lmax (abs (L2 - L));
(%o6)                       3.545L-16

Complex data.

(%i1) load ("fft") $
(%i2) fpprintprec : 4 $                 
(%i3) L : [1, 1 + %i, 1 - %i, -1, -1, 1 - %i, 1 + %i, 1] $
(%i4) L1 : inverse_fft (L);
(%o4) [4.0, 2.711L-19 %i + 4.0, 2.0 %i - 2.0, 
- 2.828 %i - 2.828, 0.0, 5.421L-20 %i + 4.0, - 2.0 %i - 2.0, 
2.828 %i + 2.828]
(%i5) L2 : fft (L1);
(%o5) [4.066E-20 %i + 1.0, 1.0 %i + 1.0, 1.0 - 1.0 %i, 
1.55L-19 %i - 1.0, - 4.066E-20 %i - 1.0, 1.0 - 1.0 %i, 
1.0 %i + 1.0, 1.0 - 7.368L-20 %i]
(%i6) lmax (abs (L2 - L));                    
(%o6)                       6.841L-17
Function: fft (x)

Computes the complex fast Fourier transform. x is a list or array (named or unnamed) which contains the data to transform. The number of elements must be a power of 2. The elements must be literal numbers (integers, rationals, floats, or bigfloats) or symbolic constants, or expressions a + b*%i where a and b are literal numbers or symbolic constants.

fft returns a new object of the same type as x, which is not modified. Results are always computed as floats or expressions a + b*%i where a and b are floats. If bigfloat precision is needed the function bf_fft can be used instead as a drop-in replacement of fft that is slower, but supports bfloats. In addition if it is known that the input consists of only real values (no imaginary parts), real_fft can be used which is potentially faster.

The discrete Fourier transform is defined as follows. Let y be the output of the transform. Then for k from 0 through n - 1,

y[k] = (1/n) sum(x[j] exp(+2 %i %pi j k / n), j, 0, n - 1)

As there are various sign and normalization conventions possible, this definition of the transform may differ from that used by other mathematical software.

When the data x are real, real coefficients a and b can be computed such that

x[j] = sum(a[k]*cos(2*%pi*j*k/n)+b[k]*sin(2*%pi*j*k/n), k, 0, n/2)

with

a[0] = realpart (y[0])
b[0] = 0

and, for k from 1 through n/2 - 1,

a[k] = realpart (y[k] + y[n - k])
b[k] = imagpart (y[n - k] - y[k])

and

a[n/2] = realpart (y[n/2])
b[n/2] = 0

load("fft") loads this function.

See also inverse_fft (inverse transform), recttopolar, and polartorect.. See real_fft for FFTs of a real-valued input, and bf_fft and bf_real_fft for operations on bigfloat values. Finally, for transforms of any size (but limited to float values), see fftpack5_fft and fftpack5_real_fft.

Examples:

Real data.

(%i1) load ("fft") $
(%i2) fpprintprec : 4 $
(%i3) L : [1, 2, 3, 4, -1, -2, -3, -4] $
(%i4) L1 : fft (L);
(%o4) [0.0, 1.811 %i - .1036, 0.0, 0.3107 %i + .6036, 0.0, 
                         0.6036 - 0.3107 %i, 0.0, (- 1.811 %i) - 0.1036]
(%i5) L2 : inverse_fft (L1);
(%o5) [1.0, 2.168L-19 %i + 2.0, 7.525L-20 %i + 3.0, 
4.256L-19 %i + 4.0, - 1.0, - 2.168L-19 %i - 2.0, 
- 7.525L-20 %i - 3.0, - 4.256L-19 %i - 4.0]
(%i6) lmax (abs (L2 - L));
(%o6)                       3.545L-16

Complex data.

(%i1) load ("fft") $
(%i2) fpprintprec : 4 $
(%i3) L : [1, 1 + %i, 1 - %i, -1, -1, 1 - %i, 1 + %i, 1] $
(%i4) L1 : fft (L);
(%o4) [0.5, 0.5, 0.25 %i - 0.25, (- 0.3536 %i) - 0.3536, 0.0, 0.5, 
                                        (- 0.25 %i) - 0.25, 0.3536 %i + 0.3536]
(%i5) L2 : inverse_fft (L1);
(%o5) [1.0, 1.0 %i + 1.0, 1.0 - 1.0 %i, - 1.0, - 1.0, 1.0 - 1.0 %i, 
                                                             1.0 %i + 1.0, 1.0]
(%i6) lmax (abs (L2 - L));
(%o6)                       0.0

Computation of sine and cosine coefficients.

(%i1) load ("fft") $
(%i2) fpprintprec : 4 $
(%i3) L : [1, 2, 3, 4, 5, 6, 7, 8] $
(%i4) n : length (L) $
(%i5) x : make_array (any, n) $
(%i6) fillarray (x, L) $
(%i7) y : fft (x) $
(%i8) a : make_array (any, n/2 + 1) $
(%i9) b : make_array (any, n/2 + 1) $
(%i10) a[0] : realpart (y[0]) $
(%i11) b[0] : 0 $
(%i12) for k : 1 thru n/2 - 1 do
   (a[k] : realpart (y[k] + y[n - k]),
    b[k] : imagpart (y[n - k] - y[k]));
(%o12)                        done
(%i13) a[n/2] : y[n/2] $
(%i14) b[n/2] : 0 $
(%i15) listarray (a);
(%o15)          [4.5, - 1.0, - 1.0, - 1.0, - 0.5]
(%i16) listarray (b);
(%o16)           [0, - 2.414, - 1.0, - .4142, 0]
(%i17) f(j) := sum (a[k]*cos(2*%pi*j*k/n) + b[k]*sin(2*%pi*j*k/n), 
                    k, 0, n/2) $
(%i18) makelist (float (f (j)), j, 0, n - 1);
(%o18)      [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]
Function: real_fft (x)

Computes the fast Fourier transform of a real-valued sequence x. This is equivalent to performing fft(x), except that only the first N/2+1 results are returned, where N is the length of x. N must be power of two.

No check is made that x contains only real values.

The symmetry properties of the Fourier transform of real sequences to reduce he complexity. In particular the first and last output values of real_fft are purely real. For larger sequences, real_fft may be computed more quickly than fft.

Since the output length is short, the normal inverse_fft cannot be directly used. Use inverse_real_fft to compute the inverse.

Function: inverse_real_fft (y)

Computes the inverse Fourier transform of y, which must have a length of N/2+1 where N is a power of two. That is, the input x is expected to be the output of real_fft.

No check is made to ensure that the input has the correct format. (The first and last elements must be purely real.)

Function: bf_inverse_fft (y)

Computes the inverse complex fast Fourier transform. This is the bigfloat version of inverse_fft that converts the input to bigfloats and returns a bigfloat result.

Function: bf_fft (y)

Computes the forward complex fast Fourier transform. This is the bigfloat version of fft that converts the input to bigfloats and returns a bigfloat result.

Function: bf_real_fft (x)

Computes the forward fast Fourier transform of a real-valued input returning a bigfloat result. This is the bigfloat version of real_fft.

Function: bf_inverse_real_fft (y)

Computes the inverse fast Fourier transform with a real-valued bigfloat output. This is the bigfloat version of inverse_real_fft.


Next: , Previous: Functions and Variables for fast Fourier transform, Up: Numerical   [Contents][Index]

21.3 Functions and Variables for FFTPACK5

FFTPACK5 provides several routines to compute Fourier transforms for both real and complex sequences and their inverses. The forward transform is defined the same as for fft. The major difference is the length of the sequence is not constrained to be a power of two. In fact, any length is supported, but it is most efficient when the length has the form 2^r*3^s*5^t.

load("fftpack5") loads this function.

Function: fftpack5_fft (x)

Like fft (fft), this computes the fast Fourier transform of a complex sequence. However, the length of x is not limited to a power of 2.

load("fftpack5") loads this function.

Examples:

Real data.

(%i1) load("fftpack5") $
(%i2) fpprintprec : 4 $
(%i3) L : [1, 2, 3, 4, -1, -2 ,-3, -4] $
(%i4) L1 : fftpack5_fft(L);
(%o4) [0.0, 1.811 %i - 0.1036, 0.0, 0.3107 %i + 0.6036, 0.0, 
                                0.6036 - 0.3107 %i, 0.0, (- 1.811 %i) - 0.1036]
(%i5) L2 : fftpack5_inverse_fft(L1);
(%o5) [1.0, 4.441e-16 %i + 2.0, 1.837e-16 %i + 3.0, 4.0 - 4.441e-16 %i, 
     - 1.0, (- 4.441e-16 %i) - 2.0, (- 1.837e-16 %i) - 3.0, 4.441e-16
       %i - 4.0]
(%i6) lmax (abs (L2-L));
(%o6)                       4.441e-16
(%i7) L : [1, 2, 3, 4, 5, 6]$
(%i8) L1 : fftpack5_fft(L);
(%o8) [3.5, (- 0.866 %i) - 0.5, (- 0.2887 %i) - 0.5, (- 1.48e-16 %i) - 0.5, 
                                               0.2887 %i - 0.5, 0.866
                                                      %%i - 0.5]
(%i9) L2 : fftpack5_inverse_fft (L1);
(%o9) [1.0 - 1.48e-16 %i, 3.701e-17 %i + 2.0, 3.0 - 1.48e-16 %i, 
                     4.0 - 1.811e-16 %i, 5.0 - 1.48e-16 %i, 5.881e-16
                           %i + 6.0]
(%i10) lmax (abs (L2-L));
(%o10)                             9.064e-16

Complex data.

(%i1) load("fftpack5") $
(%i2) fpprintprec : 4 $
(%i3) L : [1, 1 + %i, 1 - %i, -1, -1, 1 - %i, 1 + %i, 1] $
(%i4) L1 : fftpack5_inverse_fft (L);
(%o4) [4.0, 2.828 %i + 2.828, (- 2.0 %i) - 2.0, 4.0, 0.0, 
                                       (- 2.828 %i) - 2.828, 2.0 %i - 2.0, 4.0]
(%i5) L2 : fftpack5_fft(L1);
(%o5) [1.0, 1.0 %i + 1.0, 1.0 - 1.0 %i, (- 2.776e-17 %i) - 1.0, - 1.0, 
                                1.0 - 1.0 %i, 1.0 %i + 1.0, 1.0 -
                                          %2.776e-17 %i]
(%i6) lmax(abs(L2-L));
(%o6)                              1.11e-16
Function: fftpack5_inverse_fft (y)

Computes the inverse complex Fourier transform, like inverse_fft, but is not constrained to be a power of two.

Function: fftpack5_real_fft (x)

Computes the fast Fourier transform of a real-valued sequence x, just like real_fft, except the length is not constrained to be a power of two.

Examples:

(%i1) fpprintprec : 4 $
(%i2) L : [1, 2, 3, 4, 5, 6] $
(%i3) L1 : fftpack5_real_fft(L);
(%o3)       [3.5, (- 0.866 %i) - 0.5, (- 0.2887 %i) - 0.5, - 0.5]
(%i4) L2 : fftpack5_inverse_real_fft(L1, 6);
(%o4)                  [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
(%i5) lmax(abs(L2-L));
(%o5)                            1.332e-15
(%i6) fftpack5_inverse_real_fft(L1, 7);
(%o6)            [0.5, 2.083, 2.562, 3.7, 4.3, 5.438, 5.917] 

The last example shows how important it to set the length correctly for fftpack5_inverse_real_fft.

Function: fftpack5_inverse_real_fft (y, n)

Computes the inverse Fourier transform of y, which must have a length of floor(n/2) + 1. The length of sequence produced by the inverse transform must be specified by n. This is required because the length of y does not uniquely determine n. The last element of y is always real if n is even, but it can be complex when n is odd.


Next: , Previous: Functions and Variables for FFTPACK5, Up: Numerical   [Contents][Index]

21.4 Functions for numerical solution of equations

Function: horner
    horner (expr, x)
    horner (expr)

Returns a rearranged representation of expr as in Horner’s rule, using x as the main variable if it is specified. x may be omitted in which case the main variable of the canonical rational expression form of expr is used.

horner sometimes improves stability if expr is to be numerically evaluated. It is also useful if Maxima is used to generate programs to be run in Fortran. See also stringout.

(%i1) expr: 1e-155*x^2 - 5.5*x + 5.2e155;
                           2
(%o1)             1.e-155 x  - 5.5 x + 5.2e+155
(%i2) expr2: horner (%, x), keepfloat: true;
(%o2)         1.0 ((1.e-155 x - 5.5) x + 5.2e+155)
(%i3) ev (expr, x=1e155);
Maxima encountered a Lisp error:

 arithmetic error FLOATING-POINT-OVERFLOW signalled

Automatically continuing.
To enable the Lisp debugger set *debugger-hook* to nil.
(%i4) ev (expr2, x=1e155);
(%o4)                 7.00000000000001e+154
Function: find_root (expr, x, a, b, [abserr, relerr])
Function: find_root (f, a, b, [abserr, relerr])
Function: bf_find_root (expr, x, a, b, [abserr, relerr])
Function: bf_find_root (f, a, b, [abserr, relerr])
Option variable: find_root_error
Option variable: find_root_abs
Option variable: find_root_rel

Finds a root of the expression expr or the function f over the closed interval [a, b]. The expression expr may be an equation, in which case find_root seeks a root of lhs(expr) - rhs(expr).

Given that Maxima can evaluate expr or f over [a, b] and that expr or f is continuous, find_root is guaranteed to find the root, or one of the roots if there is more than one.

find_root initially applies binary search. If the function in question appears to be smooth enough, find_root applies linear interpolation instead.

bf_find_root is a bigfloat version of find_root. The function is computed using bigfloat arithmetic and a bigfloat result is returned. Otherwise, bf_find_root is identical to find_root, and the following description is equally applicable to bf_find_root.

The accuracy of find_root is governed by abserr and relerr, which are optional keyword arguments to find_root. These keyword arguments take the form key=val. The keyword arguments are

abserr

Desired absolute error of function value at root. Default is find_root_abs.

relerr

Desired relative error of root. Default is find_root_rel.

find_root stops when the function in question evaluates to something less than or equal to abserr, or if successive approximants x_0, x_1 differ by no more than relerr * max(abs(x_0), abs(x_1)). The default values of find_root_abs and find_root_rel are both zero.

find_root expects the function in question to have a different sign at the endpoints of the search interval. When the function evaluates to a number at both endpoints and these numbers have the same sign, the behavior of find_root is governed by find_root_error. When find_root_error is true, find_root prints an error message. Otherwise find_root returns the value of find_root_error. The default value of find_root_error is true.

If f evaluates to something other than a number at any step in the search algorithm, find_root returns a partially-evaluated find_root expression.

The order of a and b is ignored; the region in which a root is sought is [min(a, b), max(a, b)].

Examples:

(%i1) f(x) := sin(x) - x/2;
                                        x
(%o1)                  f(x) := sin(x) - -
                                        2
(%i2) find_root (sin(x) - x/2, x, 0.1, %pi);
(%o2)                   1.895494267033981
(%i3) find_root (sin(x) = x/2, x, 0.1, %pi);
(%o3)                   1.895494267033981
(%i4) find_root (f(x), x, 0.1, %pi);
(%o4)                   1.895494267033981
(%i5) find_root (f, 0.1, %pi);
(%o5)                   1.895494267033981
(%i6) find_root (exp(x) = y, x, 0, 100);
                            x
(%o6)           find_root(%e  = y, x, 0.0, 100.0)
(%i7) find_root (exp(x) = y, x, 0, 100), y = 10;
(%o7)                   2.302585092994046
(%i8) log (10.0);
(%o8)                   2.302585092994046
(%i9) fpprec:32;
(%o9)                           32
(%i10) bf_find_root (exp(x) = y, x, 0, 100), y = 10;
(%o10)                  2.3025850929940456840179914546844b0
(%i11) log(10b0);
(%o11)                  2.3025850929940456840179914546844b0
Function: newton (expr, x, x_0, eps)

Returns an approximate solution of expr = 0 by Newton’s method, considering expr to be a function of one variable, x. The search begins with x = x_0 and proceeds until abs(expr) < eps (with expr evaluated at the current value of x).

newton allows undefined variables to appear in expr, so long as the termination test abs(expr) < eps evaluates to true or false. Thus it is not necessary that expr evaluate to a number.

load("newton1") loads this function.

See also realroots, allroots, find_root and mnewton.

Examples:

(%i1) load ("newton1");
(%o1)  /maxima/share/numeric/newton1.mac
(%i2) newton (cos (u), u, 1, 1/100);
(%o2)                   1.570675277161251
(%i3) ev (cos (u), u = %);
(%o3)                 1.2104963335033529e-4
(%i4) assume (a > 0);
(%o4)                        [a > 0]
(%i5) newton (x^2 - a^2, x, a/2, a^2/100);
(%o5)                  1.00030487804878 a
(%i6) ev (x^2 - a^2, x = %);
                                           2
(%o6)                6.098490481853958e-4 a

Next: , Previous: Functions for numerical solution of equations, Up: Numerical   [Contents][Index]

21.5 Introduction to numerical solution of differential equations

The Ordinary Differential Equations (ODE) solved by the functions in this section should have the form,

       dy
       -- = F(x,y)
       dx

which is a first-order ODE. Higher order differential equations of order n must be written as a system of n first-order equations of that kind. For instance, a second-order ODE should be written as a system of two equations

       dx               dy
       -- = G(x,y,t)    -- = F(x,y,t) 
       dt               dt

The first argument in the functions will be a list with the expressions on the right-side of the ODE’s. The variables whose derivatives are represented by those expressions should be given in a second list. In the case above those variables are x and y. The independent variable, t in the examples above, might be given in a separated option. If the expressions given do not depend on that independent variable, the system is called autonomous.


Previous: Introduction to numerical solution of differential equations, Up: Numerical   [Contents][Index]

21.6 Functions for numerical solution of differential equations

Function: plotdf
    plotdf (dydx, options…)
    plotdf (dvdu, [u,v], options…)
    plotdf ([dxdt,cdydt], options…)
    plotdf ([dudt,cdvdt], [u,cv], options…)

The function plotdf creates a two-dimensional plot of the direction field (also called slope field) for a first-order Ordinary Differential Equation (ODE) or a system of two autonomous first-order ODE’s.

Plotdf requires Xmaxima, even if its run from a Maxima session in a console, since the plot will be created by the Tk scripts in Xmaxima. If Xmaxima is not installed plotdf will not work.

dydx, dxdt and dydt are expressions that depend on x and y. dvdu, dudt and dvdt are expressions that depend on u and v. In addition to those two variables, the expressions can also depend on a set of parameters, with numerical values given with the parameters option (the option syntax is given below), or with a range of allowed values specified by a sliders option.

Several other options can be given within the command, or selected in the menu. Integral curves can be obtained by clicking on the plot, or with the option trajectory_at. The direction of the integration can be controlled with the direction option, which can have values of forward, backward or both. The number of integration steps is given by nsteps; at each integration step the time increment will be adjusted automatically to produce displacements much smaller than the size of the plot window. The numerical method used is 4th order Runge-Kutta with variable time steps.

Plot window menu:

The menu bar of the plot window has the following seven icons:

An X. Can be used to close the plot window.

A wrench and a screwdriver. Opens the configuration menu with several fields that show the ODE(s) in use and various other settings. If a pair of coordinates are entered in the field Trajectory at and the enter key is pressed, a new integral curve will be shown, in addition to the ones already shown.

Two arrows following a circle. Replots the direction field with the new settings defined in the configuration menu and replots only the last integral curve that was previously plotted.

Hard disk drive with an arrow. Used to save a copy of the plot, in Postscript format, in the file specified in a field of the box that appears when that icon is clicked.

Magnifying glass with a plus sign. Zooms in the plot.

Magnifying glass with a minus sign. Zooms out the plot. The plot can be displaced by holding down the right mouse button while the mouse is moved.

Icon of a plot. Opens another window with a plot of the two variables in terms of time, for the last integral curve that was plotted.

Plot options:

Options can also be given within the plotdf itself, each one being a list of two or more elements. The first element in each option is the name of the option, and the remainder is the value or values assigned to the option.

The options which are recognized by plotdf are the following:

Examples:

Function: ploteq (exp, ...options...)

Plots equipotential curves for exp, which should be an expression depending on two variables. The curves are obtained by integrating the differential equation that define the orthogonal trajectories to the solutions of the autonomous system obtained from the gradient of the expression given. The plot can also show the integral curves for that gradient system (option fieldlines).

This program also requires Xmaxima, even if its run from a Maxima session in a console, since the plot will be created by the Tk scripts in Xmaxima. By default, the plot region will be empty until the user clicks in a point (or gives its coordinate with in the set-up menu or via the trajectory_at option).

Most options accepted by plotdf can also be used for ploteq and the plot interface is the same that was described in plotdf.

Example:

(%i1) V: 900/((x+1)^2+y^2)^(1/2)-900/((x-1)^2+y^2)^(1/2)$
(%i2) ploteq(V,[x,-2,2],[y,-2,2],[fieldlines,"blue"])$

Clicking on a point will plot the equipotential curve that passes by that point (in red) and the orthogonal trajectory (in blue).

Function: rk
    rk (ODE, var, initial, domain)
    rk ([ODE1, …, ODEm], [v1, …, vm], [init1, …, initm], domain)

The first form solves numerically one first-order ordinary differential equation, and the second form solves a system of m of those equations, using the 4th order Runge-Kutta method. var represents the dependent variable. ODE must be an expression that depends only on the independent and dependent variables and defines the derivative of the dependent variable with respect to the independent variable.

The independent variable is specified with domain, which must be a list of four elements as, for instance:

[t, 0, 10, 0.1]

the first element of the list identifies the independent variable, the second and third elements are the initial and final values for that variable, and the last element sets the increments that should be used within that interval.

If m equations are going to be solved, there should be m dependent variables v1, v2, ..., vm. The initial values for those variables will be init1, init2, ..., initm. There will still be just one independent variable defined by domain, as in the previous case. ODE1, ..., ODEm are the expressions that define the derivatives of each dependent variable in terms of the independent variable. The only variables that may appear in those expressions are the independent variable and any of the dependent variables. It is important to give the derivatives ODE1, ..., ODEm in the list in exactly the same order used for the dependent variables; for instance, the third element in the list will be interpreted as the derivative of the third dependent variable.

The program will try to integrate the equations from the initial value of the independent variable until its last value, using constant increments. If at some step one of the dependent variables takes an absolute value too large, the integration will be interrupted at that point. The result will be a list with as many elements as the number of iterations made. Each element in the results list is itself another list with m+1 elements: the value of the independent variable, followed by the values of the dependent variables corresponding to that point.

See also `drawdf', desolve and ode2.

Examples:

To solve numerically the differential equation

          dx/dt = t - x^2

With initial value x(t=0) = 1, in the interval of t from 0 to 8 and with increments of 0.1 for t, use:

(%i1) results: rk(t-x^2,x,1,[t,0,8,0.1])$
(%i2) plot2d ([discrete, results])$

the results will be saved in the list results and the plot will show the solution obtained, with t on the horizontal axis and x on the vertical axis.

To solve numerically the system:

        dx/dt = 4-x^2-4*y^2     dy/dt = y^2-x^2+1

for t between 0 and 4, and with values of -1.25 and 0.75 for x and y at t=0:

(%i1) sol: rk([4-x^2-4*y^2, y^2-x^2+1], [x, y], [-1.25, 0.75],
              [t, 0, 4, 0.02])$
(%i2) plot2d([discrete, makelist([p[1], p[3]], p, sol)], [xlabel, "t"],
             [ylabel, "y"])$

The plot will show the solution for variable y as a function of t.


Next: , Previous: Numerical, Up: Top   [Contents][Index]

22 Массивы


Previous: Массивы, Up: Массивы   [Contents][Index]

22.1 Функции и переменные для работы с массивами

Функция: array (name, dim_1, ..., dim_n)
Функция: array (name, type, dim_1, ..., dim_n)
Функция: array ([name_1, ..., name_m], dim_1, ..., dim_n)

Создает n-мерный массив. Значение n должно быть меньше или равно 5. i-й индекс может принимать целочисленное значение от 0 до dim_i.

array (name, dim_1, ..., dim_n) – создает массив общего вида.

array (name, type, dim_1, ..., dim_n) – создает массив, элементы которого имеют определенный тип. type может быть fixnum для целых чисел ограниченной точности и flonum для чисел с плавающей точкой.

array ([name_1, ..., name_m], dim_1, ..., dim_n) – создает m массивов одинаковой размерности.

Если пользователь присваивает значение переменной с индексом до того, как соответствующий массив объявлен, тогда создается необъявленный массив. Необъявленные массивы, также известные как хеш-массивы (т.к. для хранения элементов применяется хеширование), являются более общими чем объявленные массивы. Пользователь не определяет их максимальный размер, и они растут динамически по мере присваивания значений их элементам. Индексы необъявленных массивов даже не обязаны быть целочисленными. Однако, за исключением случая когда массив сильно разряжен, объявленный массив, обычно, более эффективен чем необъявленный. Функция array может преобразовать необъявленный массив в объявленный.

Функция: arrayapply (A, [i_1, ..., i_n])

Вычисляет значение A [i_1, ..., i_n], где A – массив, а i_1, ..., i_n целые числа.

Данная функция похожа на apply, только первый аргумент является массивом а не функцией.

Функция: arrayinfo (A)

Возвращает информацию о массиве A. Аргумент A может быть объявленным массивом, необъявленным (хеш-) массивом, функцией-массивом или функцией с индексом.

Для объявленного массива arrayinfo возвращает список состоящий из атома declared, размерности массива и размера каждого из измерений. Элементы массива, как имеющие значение, так и не имеющие значения, возвращаются функцией listarray.

Для необъявленных массивов (хеш-массивов) arrayinfo возвращает список состоящий из атома hashed, числа индексов и индексов всех элементов, которые имеют значение. Значения массива возвращаются функцией listarray.

Для функций-массивов arrayinfo возвращает список состоящий из атома hashed, числа индексов и индексов всех элементов, которые содержат функциональные значения. Функциональные значения возвращаются функцией listarray.

Для функций с индексом arrayinfo возвращает список состоящий из атома hashed, числа индексов и индексов всех элементов, которые содержат лямбда-выражения. Лямбда-выражения возвращаются функцией listarray.

Примеры:

arrayinfo и listarray примененные к объявленному массиву.

(%i1) array (aa, 2, 3);
(%o1)                          aa
(%i2) aa [2, 3] : %pi;
(%o2)                          %pi
(%i3) aa [1, 2] : %e;
(%o3)                          %e
(%i4) arrayinfo (aa);
(%o4)                 [declared, 2, [2, 3]]
(%i5) listarray (aa);
(%o5) [#####, #####, #####, #####, #####, #####, %e, #####, 
                                        #####, #####, #####, %pi]

arrayinfo и listarray примененные к необъявленному (хеш) массиву.

(%i1) bb [FOO] : (a + b)^2;
                                   2
(%o1)                       (b + a)
(%i2) bb [BAR] : (c - d)^3;
                                   3
(%o2)                       (c - d)
(%i3) arrayinfo (bb);
(%o3)               [hashed, 1, [BAR], [FOO]]
(%i4) listarray (bb);
                              3         2
(%o4)                 [(c - d) , (b + a) ]

arrayinfo и listarray примененные к функции-массиву.

(%i1) cc [x, y] := y / x;
                                     y
(%o1)                      cc     := -
                             x, y    x
(%i2) cc [u, v];
                                v
(%o2)                           -
                                u
(%i3) cc [4, z];
                                z
(%o3)                           -
                                4
(%i4) arrayinfo (cc);
(%o4)              [hashed, 2, [4, z], [u, v]]
(%i5) listarray (cc);
                              z  v
(%o5)                        [-, -]
                              4  u

arrayinfo и listarray примененные к функции с индексом.

(%i1) dd [x] (y) := y ^ x;
                                     x
(%o1)                     dd (y) := y
                            x
(%i2) dd [a + b];
                                    b + a
(%o2)                  lambda([y], y     )
(%i3) dd [v - u];
                                    v - u
(%o3)                  lambda([y], y     )
(%i4) arrayinfo (dd);
(%o4)             [hashed, 1, [b + a], [v - u]]
(%i5) listarray (dd);
                         b + a                v - u
(%o5)      [lambda([y], y     ), lambda([y], y     )]
Функция: arraymake (A, [i_1, ..., i_n])

Возвращает выражение A[i_1, ..., i_n]. Этот результат является не вычисленной ссылкой на элемент массива.

Функция arraymake похожа на funmake, за исключеним того, что возвращает не вычисленный элемент массива вместо от не вычисленного вызова функции.

Примеры:

(%i1) arraymake (A, [1]);
(%o1)                          A
                                1
(%i2) arraymake (A, [k]);
(%o2)                          A
                                k
(%i3) arraymake (A, [i, j, 3]);
(%o3)                       A
                             i, j, 3
(%i4) array (A, fixnum, 10);
(%o4)                           A
(%i5) fillarray (A, makelist (i^2, i, 1, 11));
(%o5)                           A
(%i6) arraymake (A, [5]); 
(%o6)                          A
                                5
(%i7) ''%;
(%o7)                          36
(%i8) L : [a, b, c, d, e];
(%o8)                    [a, b, c, d, e]
(%i9) arraymake ('L, [n]);
(%o9)                          L
                                n
(%i10) ''%, n = 3;
(%o10)                          c
(%i11) A2 : make_array (fixnum, 10);
(%o11)          {Array:  #(0 0 0 0 0 0 0 0 0 0)}
(%i12) fillarray (A2, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
(%o12)          {Array:  #(1 2 3 4 5 6 7 8 9 10)}
(%i13) arraymake ('A2, [8]);
(%o13)                         A2
                                 8
(%i14) ''%;
(%o14)                          9
Системная переменная: arrays

Значение по умолчанию: []

Список arrays содержит всех существующих массивов. Что составляет: массивы, объявленные при помощи array; хеш-массивы, созданные при помощи неявных определение (присваиванием чего-либо элементу массива); функции-массивы, определенные с помощью := и define. Массивы, созданные при помощи make_array, в список не включаются.

См. также array, arrayapply, arrayinfo, arraymake, fillarray, listarray, and rearray.

Примеры:

(%i1) array (aa, 5, 7);
(%o1)                          aa
(%i2) bb [FOO] : (a + b)^2;
                                   2
(%o2)                       (b + a)
(%i3) cc [x] := x/100;
                                   x
(%o3)                      cc  := ---
                             x    100
(%i4) dd : make_array ('any, 7);
(%o4)       {Array:  #(NIL NIL NIL NIL NIL NIL NIL)}
(%i5) arrays;
(%o5)                     [aa, bb, cc]
Функция: bashindices (expr)

Преобразует выражение expr присваивая каждому суммированию или произведению уникальный индекс. Индекс имеет форму jnumber. Величина number определяется значением переменной gensumnum, которое может быть установлено пользователем. Например gensumnum:0$, инициализирует эту переменную.

Функция: fillarray (A, B)

Заполняет массив A элементами из B, являющимся списком или массивом.

Если для массива A в момент создания был задан тип элементов, то он может быть заполнен только элементами данного типа и попытка заполнения элементами другого типа является ошибкой.

Если размерность массивов не совпадает, тогда A заполняется построчно. Если число элементов B недостаточно, то последний элемент используется для заполнения остатка A. Если число элементов B слишком велико, тогда излишние отбрасываются.

fillarray возвращает свой первый аргумент.

Примеры:

Создается массив из 9 элементов и заполняется из списка.

(%i1) array (a1, fixnum, 8);
(%o1)                          a1
(%i2) listarray (a1);
(%o2)              [0, 0, 0, 0, 0, 0, 0, 0, 0]
(%i3) fillarray (a1, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
(%o3)                          a1
(%i4) listarray (a1);
(%o4)              [1, 2, 3, 4, 5, 6, 7, 8, 9]

Если недостаточно элементов для заполнения массива, то последний элемент повторяется. Если элементов слишком много, то излишние элементы игнорируются.

(%i1) a2 : make_array (fixnum, 8);
(%o1)             {Array:  #(0 0 0 0 0 0 0 0)}
(%i2) fillarray (a2, [1, 2, 3, 4, 5]);
(%o2)             {Array:  #(1 2 3 4 5 5 5 5)}
(%i3) fillarray (a2, [4]);
(%o3)             {Array:  #(4 4 4 4 4 4 4 4)}
(%i4) fillarray (a2, makelist (i, i, 1, 100));
(%o4)             {Array:  #(1 2 3 4 5 6 7 8)}

Многомерные массивы заполняются построчно.

(%i1) a3 : make_array (fixnum, 2, 5);
(%o1)        {Array:  #2A((0 0 0 0 0) (0 0 0 0 0))}
(%i2) fillarray (a3, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
(%o2)        {Array:  #2A((1 2 3 4 5) (6 7 8 9 10))}
(%i3) a4 : make_array (fixnum, 5, 2);
(%o3)     {Array:  #2A((0 0) (0 0) (0 0) (0 0) (0 0))}
(%i4) fillarray (a4, a3);
(%o4)     {Array:  #2A((1 2) (3 4) (5 6) (7 8) (9 10))}
Функция: listarray (A)

Возвращает список элементов массива A. Аргумент A должен быть объявленным массивом, необъявленным (хеш) массивом, функцией-массивом или функцией с индексами.

Элементы помещаются в список построчно. Т.е. сначала помещаются элементы по первому индексу, затем по второму и т.д. Порядок значений индексов тот же, что установлен при помощи orderless.

Для необъявленных массивов, функций-массивов и функций с индексом, возвращаются элементы соответствующие индексам возвращаемым функцией arrayinfo.

Для объявленных массивов общего типа (т.е не fixnum или flonum) элементы не имеющие значения возвращаются как #####. Не присвоенные элементы объявленных fixnum или flonum массивов возвращаются как 0 или 0.0 соответственно. Не присвоенные элементы необъявленных массивов, функций-массивов и функций с индексом не возвращаются.

Примеры:

listarray и arrayinfo примененные к объявленному массиву.

(%i1) array (aa, 2, 3);
(%o1)                          aa
(%i2) aa [2, 3] : %pi;
(%o2)                          %pi
(%i3) aa [1, 2] : %e;
(%o3)                          %e
(%i4) listarray (aa);
(%o4) [#####, #####, #####, #####, #####, #####, %e, #####, 
                                        #####, #####, #####, %pi]
(%i5) arrayinfo (aa);
(%o5)                 [declared, 2, [2, 3]]

arrayinfo и listarray примененные к необъявленному (хеш) массиву.

(%i1) bb [FOO] : (a + b)^2;
                                   2
(%o1)                       (b + a)
(%i2) bb [BAR] : (c - d)^3;
                                   3
(%o2)                       (c - d)
(%i3) listarray (bb);
                              3         2
(%o3)                 [(c - d) , (b + a) ]
(%i4) arrayinfo (bb);
(%o4)               [hashed, 1, [BAR], [FOO]]

arrayinfo и listarray примененные к функции-массиву.

(%i1) cc [x, y] := y / x;
                                     y
(%o1)                      cc     := -
                             x, y    x
(%i2) cc [u, v];
                                v
(%o2)                           -
                                u
(%i3) cc [4, z];
                                z
(%o3)                           -
                                4
(%i4) listarray (cc);
                              z  v
(%o4)                        [-, -]
                              4  u
(%i5) arrayinfo (cc);
(%o5)              [hashed, 2, [4, z], [u, v]]

arrayinfo и listarray примененные к функции с индексом.

(%i1) dd [x] (y) := y ^ x;
                                     x
(%o1)                     dd (y) := y
                            x
(%i2) dd [a + b];
                                    b + a
(%o2)                  lambda([y], y     )
(%i3) dd [v - u];
                                    v - u
(%o3)                  lambda([y], y     )
(%i4) listarray (dd);
                         b + a                v - u
(%o4)      [lambda([y], y     ), lambda([y], y     )]
(%i5) arrayinfo (dd);
(%o5)             [hashed, 1, [b + a], [v - u]]
Функция: make_array (type, dim_1, ..., dim_n)

Создает и возвращает Lisp-массив. type может быть any, flonum, fixnum, hashed или functional.

Массив имеет n индексов, i-й индекс может принимать значение от 0 до dim_i-1.

Преимущество make_array по сравнению с array состоит в том, что возвращаемый Lisp-массив не имеет имени. И как только ссылка на него исчезает, занимаемое им место освобождается. Например, если y: make_array (...), тогда y ссылается на объект (массив), занимающий место в памяти. Но после присваивания y: false, y больше не ссылается на данный массив и занимаемое им место будет освобождено при сборке мусора.

Примеры:

(%i1) A1 : make_array (fixnum, 10);
(%o1)           {Array:  #(0 0 0 0 0 0 0 0 0 0)}
(%i2) A1 [8] : 1729;
(%o2)                         1729
(%i3) A1;
(%o3)          {Array:  #(0 0 0 0 0 0 0 0 1729 0)}
(%i4) A2 : make_array (flonum, 10);
(%o4) {Array:  #(0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0)}
(%i5) A2 [2] : 2.718281828;
(%o5)                      2.718281828
(%i6) A2;
(%o6) 
     {Array:  #(0.0 0.0 2.718281828 0.0 0.0 0.0 0.0 0.0 0.0 0.0)}
(%i7) A3 : make_array (any, 10);
(%o7) {Array:  #(NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL)}
(%i8) A3 [4] : x - y - z;
(%o8)                      - z - y + x
(%i9) A3;
(%o9) {Array:  #(NIL NIL NIL NIL ((MPLUS SIMP) $X ((MTIMES SIMP)\
 -1 $Y) ((MTIMES SIMP) -1 $Z))
  NIL NIL NIL NIL NIL)}
(%i10) A4 : make_array (fixnum, 2, 3, 5);
(%o10) {Array:  #3A(((0 0 0 0 0) (0 0 0 0 0) (0 0 0 0 0)) ((0 0 \
0 0 0) (0 0 0 0 0) (0 0 0 0 0)))}
(%i11) fillarray (A4, makelist (i, i, 1, 2*3*5));
(%o11) {Array:  #3A(((1 2 3 4 5) (6 7 8 9 10) (11 12 13 14 15))
    ((16 17 18 19 20) (21 22 23 24 25) (26 27 28 29 30)))}
(%i12) A4 [0, 2, 1];
(%o12)                         12
Функция: rearray (A, dim_1, ..., dim_n)

Изменяет размерность массива. Новый массив будет заполнен элементами старого построчно. Если исходный массив слишком мал, тогда остаток заполняется false, 0.0 или 0, в зависимости от типа массива. Тип массива не может быть изменен.

Функция: remarray (A_1, ..., A_n)
Функция: remarray (all)

Удаляет массив, все ассоциированные с ним функции и освобождает занимаемую им память. Аргументы должны быть: объявленными массивами, необъявленными (хеш) массивами, функциями-массивами или функциями с индексом.

remarray (all) удаляет все элементы в глобальном списке arrays.

Использование remarray может требоваться если необходимо переопределить значения элементов необъявленного (хеш) массива.

remarray возвращает список удаленных массивов.

Функция: subvar (x, i)

Вычисляет выражение с индексом x[i].

subvar вычисляет свои аргументы.

arraymake (x, [i] составляет выражение x[i], но не вычисляет его.

Примеры:

(%i1) x : foo $

(%i2) i : 3 $

(%i3) subvar (x, i);
(%o3)                         foo
                                 3
(%i4) foo : [aa, bb, cc, dd, ee]$

(%i5) subvar (x, i);
(%o5)                          cc
(%i6) arraymake (x, [i]);
(%o6)                         foo
                                 3
(%i7) ''%;
(%o7)                          cc
Управляющая переменная: use_fast_arrays

– если true, тогда используются только два типа массивов.

1) Art-q массивы (t в Common Lisp), которые имеют несколько целочисленных индексов, и могут содержать любые Lisp или Maxima объекты. Для создания таких массивов используется функция make_array. Например a:make_array(any,3,4);. Значение a – массив из 12 элементов. Отсчет индексов ведется с 0.

2) Hash_table массивы, создающиеся по умолчанию если выполняется присваивания b[x+1]:y^2 если b еще пока не является массивом, списком или матрицей (во всех этих случаях должна возникнуть ошибка т.к. x+1 в общем случае не является допустимым индексом для art-q массива, списка или матрицы). Индексом такого массива (также называется ключем) может быть произвольный объект. Используется только один ключ одновременно, так в b[x+1,u]:y игнорирует u а соответствие устанавливается по b[x+1] ==> y^2. Разумеется ключ может быть списком, например b[[x+1,u]]:y вполне допустимо. Это не совместимо со старыми хешируемыми массивами, но экономит память.

Преимущество хранения массивов в значении переменной состоит в том, что в этом случае массивы следуют обычным соглашениям о локальных переменных. Кроме того Hash_table массивы более эффективны и используют меньше памяти, чем старые хешируемые массивы. Для одинакового поведения в интерпретируемом и компилируемом коде необходимо установить значение translate_fast_arrays равным true.


Next: , Previous: Массивы, Up: Top   [Contents][Index]

23 Matrices and Linear Algebra


Next: , Previous: Matrices and Linear Algebra, Up: Matrices and Linear Algebra   [Contents][Index]

23.1 Introduction to Matrices and Linear Algebra


Next: , Previous: Introduction to Matrices and Linear Algebra, Up: Introduction to Matrices and Linear Algebra   [Contents][Index]

23.1.1 Dot

The operator . represents noncommutative multiplication and scalar product. When the operands are 1-column or 1-row matrices a and b, the expression a.b is equivalent to sum (a[i]*b[i], i, 1, length(a)). If a and b are not complex, this is the scalar product, also called the inner product or dot product, of a and b. The scalar product is defined as conjugate(a).b when a and b are complex; innerproduct in the eigen package provides the complex scalar product.

When the operands are more general matrices, the product is the matrix product a and b. The number of rows of b must equal the number of columns of a, and the result has number of rows equal to the number of rows of a and number of columns equal to the number of columns of b.

To distinguish . as an arithmetic operator from the decimal point in a floating point number, it may be necessary to leave spaces on either side. For example, 5.e3 is 5000.0 but 5 . e3 is 5 times e3.

There are several flags which govern the simplification of expressions involving ., namely dot0nscsimp, dot0simp, dot1simp, dotassoc, dotconstrules, dotdistrib, dotexptsimp, dotident, and dotscrules.


Next: , Previous: Dot, Up: Introduction to Matrices and Linear Algebra   [Contents][Index]

23.1.2 Matrices

Matrices are handled with speed and memory-efficiency in mind. This means that assigning a matrix to a variable will create a reference to, not a copy of the matrix. If the matrix is modified all references to the matrix point to the modified object (See copymatrix for a way of avoiding this):

(%i1) M1: matrix([0,0],[0,0]);
                            [ 0  0 ]
(%o1)                       [      ]
                            [ 0  0 ]
(%i2) M2: M1;
                            [ 0  0 ]
(%o2)                       [      ]
                            [ 0  0 ]
(%i3) M1[1][1]: 2;
(%o3)                           2
(%i4) M2;
                            [ 2  0 ]
(%o4)                       [      ]
                            [ 0  0 ]

Converting a matrix to nested lists and vice versa works the following way:

(%i1) l: [[1,2],[3,4]];
(%o1)                   [[1, 2], [3, 4]]
(%i2) M1: apply('matrix,l);
                            [ 1  2 ]
(%o2)                       [      ]
                            [ 3  4 ]
(%i3) M2: transpose(M1);
                            [ 1  3 ]
(%o3)                       [      ]
                            [ 2  4 ]
(%i4) args(M2);
(%o4)                   [[1, 3], [2, 4]]

Next: , Previous: Matrices, Up: Introduction to Matrices and Linear Algebra   [Contents][Index]

23.1.3 Vectors

vect is a package of functions for vector analysis. load ("vect") loads this package, and demo ("vect") displays a demonstration.

The vector analysis package can combine and simplify symbolic expressions including dot products and cross products, together with the gradient, divergence, curl, and Laplacian operators. The distribution of these operators over sums or products is governed by several flags, as are various other expansions, including expansion into components in any specific orthogonal coordinate systems. There are also functions for deriving the scalar or vector potential of a field.

The vect package contains these functions: vectorsimp, scalefactors, express, potential, and vectorpotential.

By default the vect package does not declare the dot operator to be a commutative operator. To get a commutative dot operator ., the command declare(".", commutative) must be executed.


Previous: Vectors, Up: Introduction to Matrices and Linear Algebra   [Contents][Index]

23.1.4 eigen

The package eigen contains several functions devoted to the symbolic computation of eigenvalues and eigenvectors. Maxima loads the package automatically if one of the functions eigenvalues or eigenvectors is invoked. The package may be loaded explicitly as load ("eigen").

demo ("eigen") displays a demonstration of the capabilities of this package. batch ("eigen") executes the same demonstration, but without the user prompt between successive computations.

The functions in the eigen package are:
innerproduct, unitvector, columnvector, gramschmidt, eigenvalues,
eigenvectors, uniteigenvectors, and similaritytransform.


Previous: Introduction to Matrices and Linear Algebra, Up: Matrices and Linear Algebra   [Contents][Index]

23.2 Functions and Variables for Matrices and Linear Algebra

Function: addcol (M, list_1, …, list_n)

Appends the column(s) given by the one or more lists (or matrices) onto the matrix M.

See also addrow and append.

Function: addrow (M, list_1, …, list_n)

Appends the row(s) given by the one or more lists (or matrices) onto the matrix M.

See also addcol and append.

Function: adjoint (M)

Returns the adjoint of the matrix M. The adjoint matrix is the transpose of the matrix of cofactors of M.

Function: augcoefmatrix ([eqn_1, …, eqn_m], [x_1, …, x_n])

Returns the augmented coefficient matrix for the variables x_1, …, x_n of the system of linear equations eqn_1, …, eqn_m. This is the coefficient matrix with a column adjoined for the constant terms in each equation (i.e., those terms not dependent upon x_1, …, x_n).

(%i1) m: [2*x - (a - 1)*y = 5*b, c + b*y + a*x = 0]$
(%i2) augcoefmatrix (m, [x, y]);
                       [ 2  1 - a  - 5 b ]
(%o2)                  [                 ]
                       [ a    b      c   ]
Function: cauchy_matrix
    cauchy_matrix ([x_1, x_2, …, x_m], [y_1, y_2, …, y_n])
    cauchy_matrix ([x_1, x_2, …, x_n])

Returns a n by m Cauchy matrix with the elements a[i,j] = 1/(x_i+y_i). The second argument of cauchy_matrix is optional. For this case the elements of the Cauchy matrix are a[i,j] = 1/(x_i+x_j).

Remark: In the literature the Cauchy matrix can be found defined in two forms. A second definition is a[i,j] = 1/(x_i-y_i).

Examples:

(%i1) cauchy_matrix([x1, x2], [y1, y2]);
                      [    1        1    ]
                      [ -------  ------- ]
                      [ y1 + x1  y2 + x1 ]
(%o1)                 [                  ]
                      [    1        1    ]
                      [ -------  ------- ]
                      [ y1 + x2  y2 + x2 ]
(%i2) cauchy_matrix([x1, x2]);
                      [   1         1    ]
                      [  ----    ------- ]
                      [  2 x1    x2 + x1 ]
(%o2)                 [                  ]
                      [    1       1     ]
                      [ -------   ----   ]
                      [ x2 + x1   2 x2   ]
Function: charpoly (M, x)

Returns the characteristic polynomial for the matrix M with respect to variable x. That is, determinant (M - diagmatrix (length (M), x)).

(%i1) a: matrix ([3, 1], [2, 4]);
                            [ 3  1 ]
(%o1)                       [      ]
                            [ 2  4 ]
(%i2) expand (charpoly (a, lambda));
                           2
(%o2)                lambda  - 7 lambda + 10
(%i3) (programmode: true, solve (%));
(%o3)               [lambda = 5, lambda = 2]
(%i4) matrix ([x1], [x2]);
                             [ x1 ]
(%o4)                        [    ]
                             [ x2 ]
(%i5) ev (a . % - lambda*%, %th(2)[1]);
                          [ x2 - 2 x1 ]
(%o5)                     [           ]
                          [ 2 x1 - x2 ]
(%i6) %[1, 1] = 0;
(%o6)                     x2 - 2 x1 = 0
(%i7) x2^2 + x1^2 = 1;
                            2     2
(%o7)                     x2  + x1  = 1
(%i8) solve ([%th(2), %], [x1, x2]);
                  1               2
(%o8) [[x1 = - -------, x2 = - -------], 
               sqrt(5)         sqrt(5)

                                             1             2
                                    [x1 = -------, x2 = -------]]
                                          sqrt(5)       sqrt(5)
Function: coefmatrix ([eqn_1, …, eqn_m], [x_1, …, x_n])

Returns the coefficient matrix for the variables x_1, …, x_n of the system of linear equations eqn_1, …, eqn_m.

(%i1) coefmatrix([2*x-(a-1)*y+5*b = 0, b*y+a*x = 3], [x,y]);
                                 [ 2  1 - a ]
(%o1)                            [          ]
                                 [ a    b   ]
Function: col (M, i)

Returns the i’th column of the matrix M. The return value is a matrix.

Function: columnvector (L)
Function: covect (L)

Returns a matrix of one column and length (L) rows, containing the elements of the list L.

covect is a synonym for columnvector.

load ("eigen") loads this function.

This is useful if you want to use parts of the outputs of the functions in this package in matrix calculations.

Example:

(%i1) load ("eigen")$
Warning - you are redefining the Macsyma function eigenvalues
Warning - you are redefining the Macsyma function eigenvectors
(%i2) columnvector ([aa, bb, cc, dd]);
                             [ aa ]
                             [    ]
                             [ bb ]
(%o2)                        [    ]
                             [ cc ]
                             [    ]
                             [ dd ]
Function: copymatrix (M)

Returns a copy of the matrix M. This is the only way to make a copy aside from copying M element by element.

Note that an assignment of one matrix to another, as in m2: m1, does not copy m1. An assignment m2 [i,j]: x or setelmx(x, i, j, m2) also modifies m1 [i,j]. Creating a copy with copymatrix and then using assignment creates a separate, modified copy.

Function: determinant (M)

Computes the determinant of M by a method similar to Gaussian elimination.

The form of the result depends upon the setting of the switch ratmx.

There is a special routine for computing sparse determinants which is called when the switches ratmx and sparse are both true.

Option variable: detout

Default value: false

When detout is true, the determinant of a matrix whose inverse is computed is factored out of the inverse.

For this switch to have an effect doallmxops and doscmxops should be false (see their descriptions). Alternatively this switch can be given to ev which causes the other two to be set correctly.

Example:

(%i1) m: matrix ([a, b], [c, d]);
                            [ a  b ]
(%o1)                       [      ]
                            [ c  d ]
(%i2) detout: true$
(%i3) doallmxops: false$
(%i4) doscmxops: false$
(%i5) invert (m);
                          [  d   - b ]
                          [          ]
                          [ - c   a  ]
(%o5)                     ------------
                           a d - b c
Function: diagmatrix (n, x)

Returns a diagonal matrix of size n by n with the diagonal elements all equal to x. diagmatrix (n, 1) returns an identity matrix (same as ident (n)).

n must evaluate to an integer, otherwise diagmatrix complains with an error message.

x can be any kind of expression, including another matrix. If x is a matrix, it is not copied; all diagonal elements refer to the same instance, x.

Option variable: doallmxops

Default value: true

When doallmxops is true, all operations relating to matrices are carried out. When it is false then the setting of the individual dot switches govern which operations are performed.

Option variable: domxexpt

Default value: true

When domxexpt is true, a matrix exponential, exp (M) where M is a matrix, is interpreted as a matrix with element [i,j] equal to exp (m[i,j]). Otherwise exp (M) evaluates to exp (ev(M)).

domxexpt affects all expressions of the form base^power where base is an expression assumed scalar or constant, and power is a list or matrix.

Example:

(%i1) m: matrix ([1, %i], [a+b, %pi]);
                         [   1    %i  ]
(%o1)                    [            ]
                         [ b + a  %pi ]
(%i2) domxexpt: false$
(%i3) (1 - c)^m;
                             [   1    %i  ]
                             [            ]
                             [ b + a  %pi ]
(%o3)                 (1 - c)
(%i4) domxexpt: true$
(%i5) (1 - c)^m;
                  [                      %i  ]
                  [    1 - c      (1 - c)    ]
(%o5)             [                          ]
                  [        b + a         %pi ]
                  [ (1 - c)       (1 - c)    ]
Option variable: domxmxops

Default value: true

When domxmxops is true, all matrix-matrix or matrix-list operations are carried out (but not scalar-matrix operations); if this switch is false such operations are not carried out.

Option variable: domxnctimes

Default value: false

When domxnctimes is true, non-commutative products of matrices are carried out.

Option variable: dontfactor

Default value: []

dontfactor may be set to a list of variables with respect to which factoring is not to occur. (The list is initially empty.) Factoring also will not take place with respect to any variables which are less important, according the variable ordering assumed for canonical rational expression (CRE) form, than those on the dontfactor list.

Option variable: doscmxops

Default value: false

When doscmxops is true, scalar-matrix operations are carried out.

Option variable: doscmxplus

Default value: false

When doscmxplus is true, scalar-matrix operations yield a matrix result. This switch is not subsumed under doallmxops.

Option variable: dot0nscsimp

Default value: true

When dot0nscsimp is true, a non-commutative product of zero and a nonscalar term is simplified to a commutative product.

Option variable: dot0simp

Default value: true

When dot0simp is true, a non-commutative product of zero and a scalar term is simplified to a commutative product.

Option variable: dot1simp

Default value: true

When dot1simp is true, a non-commutative product of one and another term is simplified to a commutative product.

Option variable: dotassoc

Default value: true

When dotassoc is true, an expression (A.B).C simplifies to A.(B.C).

Option variable: dotconstrules

Default value: true

When dotconstrules is true, a non-commutative product of a constant and another term is simplified to a commutative product. Turning on this flag effectively turns on dot0simp, dot0nscsimp, and dot1simp as well.

Option variable: dotdistrib

Default value: false

When dotdistrib is true, an expression A.(B + C) simplifies to A.B + A.C.

Option variable: dotexptsimp

Default value: true

When dotexptsimp is true, an expression A.A simplifies to A^^2.

Option variable: dotident

Default value: 1

dotident is the value returned by X^^0.

Option variable: dotscrules

Default value: false

When dotscrules is true, an expression A.SC or SC.A simplifies to SC*A and A.(SC*B) simplifies to SC*(A.B).

Function: echelon (M)

Returns the echelon form of the matrix M, as produced by Gaussian elimination. The echelon form is computed from M by elementary row operations such that the first non-zero element in each row in the resulting matrix is one and the column elements under the first one in each row are all zero.

triangularize also carries out Gaussian elimination, but it does not normalize the leading non-zero element in each row.

lu_factor and cholesky are other functions which yield triangularized matrices.

(%i1) M: matrix ([3, 7, aa, bb], [-1, 8, 5, 2], [9, 2, 11, 4]);
                       [  3   7  aa  bb ]
                       [                ]
(%o1)                  [ - 1  8  5   2  ]
                       [                ]
                       [  9   2  11  4  ]
(%i2) echelon (M);
                  [ 1  - 8  - 5      - 2     ]
                  [                          ]
                  [         28       11      ]
                  [ 0   1   --       --      ]
(%o2)             [         37       37      ]
                  [                          ]
                  [              37 bb - 119 ]
                  [ 0   0    1   ----------- ]
                  [              37 aa - 313 ]
Function: eigenvalues (M)
Function: eivals (M)

Returns a list of two lists containing the eigenvalues of the matrix M. The first sublist of the return value is the list of eigenvalues of the matrix, and the second sublist is the list of the multiplicities of the eigenvalues in the corresponding order.

eivals is a synonym for eigenvalues.

eigenvalues calls the function solve to find the roots of the characteristic polynomial of the matrix. Sometimes solve may not be able to find the roots of the polynomial; in that case some other functions in this package (except innerproduct, unitvector, columnvector and gramschmidt) will not work. Sometimes solve may find only a subset of the roots of the polynomial. This may happen when the factoring of the polynomial contains polynomials of degree 5 or more. In such cases a warning message is displayed and the only the roots found and their corresponding multiplicities are returned.

In some cases the eigenvalues found by solve may be complicated expressions. (This may happen when solve returns a not-so-obviously real expression for an eigenvalue which is known to be real.) It may be possible to simplify the eigenvalues using some other functions.

The package eigen.mac is loaded automatically when eigenvalues or eigenvectors is referenced. If eigen.mac is not already loaded, load ("eigen") loads it. After loading, all functions and variables in the package are available.

Function: eigenvectors (M)
Function: eivects (M)

Computes eigenvectors of the matrix M. The return value is a list of two elements. The first is a list of the eigenvalues of M and a list of the multiplicities of the eigenvalues. The second is a list of lists of eigenvectors. There is one list of eigenvectors for each eigenvalue. There may be one or more eigenvectors in each list.

eivects is a synonym for eigenvectors.

The package eigen.mac is loaded automatically when eigenvalues or eigenvectors is referenced. If eigen.mac is not already loaded, load ("eigen") loads it. After loading, all functions and variables in the package are available.

Note that eigenvectors internally calls eigenvalues to obtain eigenvalues. So, when eigenvalues returns a subset of all the eigenvalues, the eigenvectors returns the corresponding subset of the all the eigenvectors, with the same warning displayed as eigenvalues.

The flags that affect this function are:

nondiagonalizable is set to true or false depending on whether the matrix is nondiagonalizable or diagonalizable after eigenvectors returns.

hermitianmatrix when true, causes the degenerate eigenvectors of the Hermitian matrix to be orthogonalized using the Gram-Schmidt algorithm.

knowneigvals when true causes the eigen package to assume the eigenvalues of the matrix are known to the user and stored under the global name listeigvals. listeigvals should be set to a list similar to the output eigenvalues.

The function algsys is used here to solve for the eigenvectors. Sometimes if the eigenvalues are messy, algsys may not be able to find a solution. In some cases, it may be possible to simplify the eigenvalues by first finding them using eigenvalues command and then using other functions to reduce them to something simpler. Following simplification, eigenvectors can be called again with the knowneigvals flag set to true.

See also eigenvalues.

Examples:

A matrix which has just one eigenvector per eigenvalue.

(%i1) M1: matrix ([11, -1], [1, 7]);
                           [ 11  - 1 ]
(%o1)                      [         ]
                           [ 1    7  ]
(%i2) [vals, vecs] : eigenvectors (M1);
(%o2) [[[9 - sqrt(3), sqrt(3) + 9], [1, 1]], 
                        [[[1, sqrt(3) + 2]], [[1, 2 - sqrt(3)]]]]
(%i3) for i thru length (vals[1]) do disp (val[i] = vals[1][i],
  mult[i] = vals[2][i], vec[i] = vecs[i]);
                       val  = 9 - sqrt(3)
                          1

                            mult  = 1
                                1

                    vec  = [[1, sqrt(3) + 2]]
                       1

                       val  = sqrt(3) + 9
                          2

                            mult  = 1
                                2

                    vec  = [[1, 2 - sqrt(3)]]
                       2

(%o3)                         done

A matrix which has two eigenvectors for one eigenvalue (namely 2).

(%i1) M1: matrix ([0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 2, 0],
                  [0, 0, 0, 2]);
                        [ 0  1  0  0 ]
                        [            ]
                        [ 0  0  0  0 ]
(%o1)                   [            ]
                        [ 0  0  2  0 ]
                        [            ]
                        [ 0  0  0  2 ]
(%i2) [vals, vecs]: eigenvectors (M1);
(%o2) [[[0, 2], [2, 2]], [[[1, 0, 0, 0]], 
                                   [[0, 0, 1, 0], [0, 0, 0, 1]]]]
(%i3) for i thru length (vals[1]) do disp (val[i] = vals[1][i],
  mult[i] = vals[2][i], vec[i] = vecs[i]);
                            val  = 0
                               1

                            mult  = 2
                                1

                      vec  = [[1, 0, 0, 0]]
                         1

                            val  = 2
                               2

                            mult  = 2
                                2

               vec  = [[0, 0, 1, 0], [0, 0, 0, 1]]
                  2

(%o3)                         done
Function: ematrix (m, n, x, i, j)

Returns an m by n matrix, all elements of which are zero except for the [i, j] element which is x.

Function: entermatrix (m, n)

Returns an m by n matrix, reading the elements interactively.

If n is equal to m, Maxima prompts for the type of the matrix (diagonal, symmetric, antisymmetric, or general) and for each element. Each response is terminated by a semicolon ; or dollar sign $.

If n is not equal to m, Maxima prompts for each element.

The elements may be any expressions, which are evaluated. entermatrix evaluates its arguments.

(%i1) n: 3$
(%i2) m: entermatrix (n, n)$

Is the matrix  1. Diagonal  2. Symmetric  3. Antisymmetric 
4. General
Answer 1, 2, 3 or 4 : 
1$
Row 1 Column 1: 
(a+b)^n$
Row 2 Column 2: 
(a+b)^(n+1)$
Row 3 Column 3: 
(a+b)^(n+2)$

Matrix entered.
(%i3) m;
                [        3                     ]
                [ (b + a)      0         0     ]
                [                              ]
(%o3)           [                  4           ]
                [    0      (b + a)      0     ]
                [                              ]
                [                            5 ]
                [    0         0      (b + a)  ]
Function: genmatrix
    genmatrix (a, i_2, j_2, i_1, j_1)
    genmatrix (a, i_2, j_2, i_1)
    genmatrix (a, i_2, j_2)

Returns a matrix generated from a, taking element a[i_1, j_1] as the upper-left element and a[i_2, j_2] as the lower-right element of the matrix. Here a is a declared array (created by array but not by make_array) or a `hashed array', or a `memoizing function', or a lambda expression of two arguments. (A `memoizing function' is created like other functions with := or define, but arguments are enclosed in square brackets instead of parentheses.)

If j_1 is omitted, it is assumed equal to i_1. If both j_1 and i_1 are omitted, both are assumed equal to 1.

If a selected element i,j of the array is undefined, the matrix will contain a symbolic element a[i,j].

Examples:

(%i1) h [i, j] := 1 / (i + j - 1);
                                    1
(%o1)                  h     := ---------
                        i, j    i + j - 1
(%i2) genmatrix (h, 3, 3);
                           [    1  1 ]
                           [ 1  -  - ]
                           [    2  3 ]
                           [         ]
                           [ 1  1  1 ]
(%o2)                      [ -  -  - ]
                           [ 2  3  4 ]
                           [         ]
                           [ 1  1  1 ]
                           [ -  -  - ]
                           [ 3  4  5 ]
(%i3) array (a, fixnum, 2, 2);
(%o3)                           a
(%i4) a [1, 1] : %e;
(%o4)                          %e
(%i5) a [2, 2] : %pi;
(%o5)                          %pi
(%i6) genmatrix (a, 2, 2);
                           [ %e   0  ]
(%o6)                      [         ]
                           [ 0   %pi ]
(%i7) genmatrix (lambda ([i, j], j - i), 3, 3);
                         [  0    1   2 ]
                         [             ]
(%o7)                    [ - 1   0   1 ]
                         [             ]
                         [ - 2  - 1  0 ]
(%i8) genmatrix (B, 2, 2);
                        [ B      B     ]
                        [  1, 1   1, 2 ]
(%o8)                   [              ]
                        [ B      B     ]
                        [  2, 1   2, 2 ]
Function: gramschmidt
    gramschmidt (x)
    gramschmidt (x, F)

Carries out the Gram-Schmidt orthogonalization algorithm on x, which is either a matrix or a list of lists. x is not modified by gramschmidt. The inner product employed by gramschmidt is F, if present, otherwise the inner product is the function innerproduct.

If x is a matrix, the algorithm is applied to the rows of x. If x is a list of lists, the algorithm is applied to the sublists, which must have equal numbers of elements. In either case, the return value is a list of lists, the sublists of which are orthogonal and span the same space as x. If the dimension of the span of x is less than the number of rows or sublists, some sublists of the return value are zero.

factor is called at each stage of the algorithm to simplify intermediate results. As a consequence, the return value may contain factored integers.

load("eigen") loads this function.

Example:

Gram-Schmidt algorithm using default inner product function.

(%i1) load ("eigen")$
(%i2) x: matrix ([1, 2, 3], [9, 18, 30], [12, 48, 60]);
                         [ 1   2   3  ]
                         [            ]
(%o2)                    [ 9   18  30 ]
                         [            ]
                         [ 12  48  60 ]
(%i3) y: gramschmidt (x);
                       2      2            4     3
                      3      3   3 5      2  3  2  3
(%o3)  [[1, 2, 3], [- ---, - --, ---], [- ----, ----, 0]]
                      2 7    7   2 7       5     5
(%i4) map (innerproduct, [y[1], y[2], y[3]], [y[2], y[3], y[1]]);
(%o4)                       [0, 0, 0]

Gram-Schmidt algorithm using a specified inner product function.

(%i1) load ("eigen")$
(%i2) ip (f, g) := integrate (f * g, u, a, b);
(%o2)          ip(f, g) := integrate(f g, u, a, b)
(%i3) y: gramschmidt ([1, sin(u), cos(u)], ip), a=-%pi/2, b=%pi/2;
                               %pi cos(u) - 2
(%o3)              [1, sin(u), --------------]
                                    %pi
(%i4) map (ip, [y[1], y[2], y[3]], [y[2], y[3], y[1]]), a=-%pi/2,
         b=%pi/2;
(%o4)                       [0, 0, 0]
Function: ident (n)

Returns an n by n identity matrix.

Function: innerproduct (x, y)
Function: inprod (x, y)

Returns the inner product (also called the scalar product or dot product) of x and y, which are lists of equal length, or both 1-column or 1-row matrices of equal length. The return value is conjugate (x) . y, where . is the noncommutative multiplication operator.

load ("eigen") loads this function.

inprod is a synonym for innerproduct.

Function: invert_by_adjoint (M)

Returns the inverse of the matrix M. The inverse is computed by the adjoint method.

invert_by_adjoint honors the ratmx and detout flags, the same as invert.

Function: invert (M)

Returns the inverse of the matrix M. The inverse is computed via the LU decomposition.

When ratmx is true, elements of M are converted to canonical rational expressions (CRE), and the elements of the return value are also CRE.

When ratmx is false, elements of M are not converted to a common representation. In particular, float and bigfloat elements are not converted to rationals.

When detout is true, the determinant is factored out of the inverse. The global flags doallmxops and doscmxops must be false to prevent the determinant from being absorbed into the inverse. xthru can multiply the determinant into the inverse.

invert does not apply any simplifications to the elements of the inverse apart from the default arithmetic simplifications. ratsimp and expand can apply additional simplifications. In particular, when M has polynomial elements, expand(invert(M)) might be preferable.

invert(M) is equivalent to M^^-1.

Function: list_matrix_entries (M)

Returns a list containing the elements of the matrix M.

Example:

(%i1) list_matrix_entries(matrix([a,b],[c,d]));
(%o1)                     [a, b, c, d]
Option variable: lmxchar

Default value: [

lmxchar is the character displayed as the left delimiter of a matrix. See also rmxchar.

Example:

(%i1) lmxchar: "|"$
(%i2) matrix ([a, b, c], [d, e, f], [g, h, i]);
                           | a  b  c ]
                           |         ]
(%o2)                      | d  e  f ]
                           |         ]
                           | g  h  i ]
Function: matrix (row_1, …, row_n)

Returns a rectangular matrix which has the rows row_1, …, row_n. Each row is a list of expressions. All rows must be the same length.

The operations + (addition), - (subtraction), * (multiplication), and / (division), are carried out element by element when the operands are two matrices, a scalar and a matrix, or a matrix and a scalar. The operation ^ (exponentiation, equivalently **) is carried out element by element if the operands are a scalar and a matrix or a matrix and a scalar, but not if the operands are two matrices. All operations are normally carried out in full, including . (noncommutative multiplication).

Matrix multiplication is represented by the noncommutative multiplication operator .. The corresponding noncommutative exponentiation operator is ^^. For a matrix A, A.A = A^^2 and A^^-1 is the inverse of A, if it exists. A^^-1 is equivalent to invert(A).

There are switches for controlling simplification of expressions involving dot and matrix-list operations. These are doallmxops, domxexpt, domxmxops, doscmxops, and doscmxplus.

There are additional options which are related to matrices. These are: lmxchar, rmxchar, ratmx, listarith, detout, scalarmatrix and sparse.

There are a number of functions which take matrices as arguments or yield matrices as return values. See eigenvalues, eigenvectors, determinant, charpoly, genmatrix, addcol, addrow, copymatrix, transpose, echelon, and rank.

Examples:

(%i1) x: matrix ([17, 3], [-8, 11]);
                           [ 17   3  ]
(%o1)                      [         ]
                           [ - 8  11 ]
(%i2) y: matrix ([%pi, %e], [a, b]);
                           [ %pi  %e ]
(%o2)                      [         ]
                           [  a   b  ]
(%i3) x + y;
                      [ %pi + 17  %e + 3 ]
(%o3)                 [                  ]
                      [  a - 8    b + 11 ]
(%i4) x - y;
                      [ 17 - %pi  3 - %e ]
(%o4)                 [                  ]
                      [ - a - 8   11 - b ]
(%i5) x * y;
                        [ 17 %pi  3 %e ]
(%o5)                   [              ]
                        [ - 8 a   11 b ]
(%i6) x / y;
                        [ 17       - 1 ]
                        [ ---  3 %e    ]
                        [ %pi          ]
(%o6)                   [              ]
                        [   8    11    ]
                        [ - -    --    ]
                        [   a    b     ]
(%i7) x ^ 3;
                         [ 4913    27  ]
(%o7)                    [             ]
                         [ - 512  1331 ]
(%i8) exp(y); 
                         [   %pi    %e ]
                         [ %e     %e   ]
(%o8)                    [             ]
                         [    a     b  ]
                         [  %e    %e   ]
(%i9) x ^ y;
                                [ %pi  %e ]
                                [         ]
                                [  a   b  ]
                     [ 17   3  ]
(%o9)                [         ]
                     [ - 8  11 ]
(%i10) x . y;
                  [ 3 a + 17 %pi  3 b + 17 %e ]
(%o10)            [                           ]
                  [ 11 a - 8 %pi  11 b - 8 %e ]
(%i11) y . x;
                [ 17 %pi - 8 %e  3 %pi + 11 %e ]
(%o11)          [                              ]
                [  17 a - 8 b     11 b + 3 a   ]
(%i12) x ^^ 3;
                        [  3833   1719 ]
(%o12)                  [              ]
                        [ - 4584  395  ]
(%i13) %e ^^ y;
                         [   %pi    %e ]
                         [ %e     %e   ]
(%o13)                   [             ]
                         [    a     b  ]
                         [  %e    %e   ]
(%i14) x ^^ -1;
                         [ 11      3  ]
                         [ ---  - --- ]
                         [ 211    211 ]
(%o14)                   [            ]
                         [  8    17   ]
                         [ ---   ---  ]
                         [ 211   211  ]
(%i15) x . (x ^^ -1);
                            [ 1  0 ]
(%o15)                      [      ]
                            [ 0  1 ]
Function: matrixexp
    matrixexp (M)
    matrixexp (M, n)
    matrixexp (M, V)

Calculates the matrix exponential

\(e^{M\cdot V}\)

. Instead of the vector V a number n can be specified as the second argument. If this argument is omitted matrixexp replaces it by 1.

The matrix exponential of a matrix M can be expressed as a power series: $$ e^M=\sum_{k=0}^\infty{\left(\frac{M^k}{k!}\right)} $$

Function: matrixmap (f, M)

Returns a matrix with element i,j equal to f(M[i,j]).

See also map, fullmap, fullmapl, and apply.

Function: matrixp (expr)

Returns true if expr is a matrix, otherwise false.

Option variable: matrix_element_add

Default value: +

matrix_element_add is the operation invoked in place of addition in a matrix multiplication. matrix_element_add can be assigned any n-ary operator (that is, a function which handles any number of arguments). The assigned value may be the name of an operator enclosed in quote marks, the name of a function, or a lambda expression.

See also matrix_element_mult and matrix_element_transpose.

Example:

(%i1) matrix_element_add: "*"$
(%i2) matrix_element_mult: "^"$
(%i3) aa: matrix ([a, b, c], [d, e, f]);
                           [ a  b  c ]
(%o3)                      [         ]
                           [ d  e  f ]
(%i4) bb: matrix ([u, v, w], [x, y, z]);
                           [ u  v  w ]
(%o4)                      [         ]
                           [ x  y  z ]
(%i5) aa . transpose (bb);
                     [  u  v  w   x  y  z ]
                     [ a  b  c   a  b  c  ]
(%o5)                [                    ]
                     [  u  v  w   x  y  z ]
                     [ d  e  f   d  e  f  ]
Option variable: matrix_element_mult

Default value: *

matrix_element_mult is the operation invoked in place of multiplication in a matrix multiplication. matrix_element_mult can be assigned any binary operator. The assigned value may be the name of an operator enclosed in quote marks, the name of a function, or a lambda expression.

The dot operator . is a useful choice in some contexts.

See also matrix_element_add and matrix_element_transpose.

Example:

(%i1) matrix_element_add: lambda ([[x]], sqrt (apply ("+", x)))$
(%i2) matrix_element_mult: lambda ([x, y], (x - y)^2)$
(%i3) [a, b, c] . [x, y, z];
                          2          2          2
(%o3)         sqrt((c - z)  + (b - y)  + (a - x) )
(%i4) aa: matrix ([a, b, c], [d, e, f]);
                           [ a  b  c ]
(%o4)                      [         ]
                           [ d  e  f ]
(%i5) bb: matrix ([u, v, w], [x, y, z]);
                           [ u  v  w ]
(%o5)                      [         ]
                           [ x  y  z ]
(%i6) aa . transpose (bb);
               [             2          2          2  ]
               [ sqrt((c - w)  + (b - v)  + (a - u) ) ]
(%o6)  Col 1 = [                                      ]
               [             2          2          2  ]
               [ sqrt((f - w)  + (e - v)  + (d - u) ) ]

                         [             2          2          2  ]
                         [ sqrt((c - z)  + (b - y)  + (a - x) ) ]
                 Col 2 = [                                      ]
                         [             2          2          2  ]
                         [ sqrt((f - z)  + (e - y)  + (d - x) ) ]
Option variable: matrix_element_transpose

Default value: false

matrix_element_transpose is the operation applied to each element of a matrix when it is transposed. matrix_element_mult can be assigned any unary operator. The assigned value may be the name of an operator enclosed in quote marks, the name of a function, or a lambda expression.

When matrix_element_transpose equals transpose, the transpose function is applied to every element. When matrix_element_transpose equals nonscalars, the transpose function is applied to every nonscalar element. If some element is an atom, the nonscalars option applies transpose only if the atom is declared nonscalar, while the transpose option always applies transpose.

The default value, false, means no operation is applied.

See also matrix_element_add and matrix_element_mult.

Examples:

(%i1) declare (a, nonscalar)$
(%i2) transpose ([a, b]);
                        [ transpose(a) ]
(%o2)                   [              ]
                        [      b       ]
(%i3) matrix_element_transpose: nonscalars$
(%i4) transpose ([a, b]);
                        [ transpose(a) ]
(%o4)                   [              ]
                        [      b       ]
(%i5) matrix_element_transpose: transpose$
(%i6) transpose ([a, b]);
                        [ transpose(a) ]
(%o6)                   [              ]
                        [ transpose(b) ]
(%i7) matrix_element_transpose: lambda ([x], realpart(x)
      - %i*imagpart(x))$
(%i8) m: matrix ([1 + 5*%i, 3 - 2*%i], [7*%i, 11]);
                     [ 5 %i + 1  3 - 2 %i ]
(%o8)                [                    ]
                     [   7 %i       11    ]
(%i9) transpose (m);
                      [ 1 - 5 %i  - 7 %i ]
(%o9)                 [                  ]
                      [ 2 %i + 3    11   ]
Function: mattrace (M)

Returns the trace (that is, the sum of the elements on the main diagonal) of the square matrix M.

mattrace is called by ncharpoly, an alternative to Maxima’s charpoly.

load ("nchrpl") loads this function.

Function: minor (M, i, j)

Returns the i, j minor of the matrix M. That is, M with row i and column j removed.

Function: ncharpoly (M, x)

Returns the characteristic polynomial of the matrix M with respect to x. This is an alternative to Maxima’s charpoly.

ncharpoly works by computing traces of powers of the given matrix, which are known to be equal to sums of powers of the roots of the characteristic polynomial. From these quantities the symmetric functions of the roots can be calculated, which are nothing more than the coefficients of the characteristic polynomial. charpoly works by forming the determinant of x * ident [n] - a. Thus ncharpoly wins, for example, in the case of large dense matrices filled with integers, since it avoids polynomial arithmetic altogether.

load ("nchrpl") loads this file.

Function: newdet (M)

Computes the determinant of the matrix M by the Johnson-Gentleman tree minor algorithm. newdet returns the result in CRE form.

Function: permanent (M)

Computes the permanent of the matrix M by the Johnson-Gentleman tree minor algorithm. A permanent is like a determinant but with no sign changes. permanent returns the result in CRE form.

See also newdet.

Function: rank (M)

Computes the rank of the matrix M. That is, the order of the largest non-singular subdeterminant of M.

rank may return the wrong answer if it cannot determine that a matrix element that is equivalent to zero is indeed so.

Option variable: ratmx

Default value: false

When ratmx is false, determinant and matrix addition, subtraction, and multiplication are performed in the representation of the matrix elements and cause the result of matrix inversion to be left in general representation.

When ratmx is true, the 4 operations mentioned above are performed in CRE form and the result of matrix inverse is in CRE form. Note that this may cause the elements to be expanded (depending on the setting of ratfac) which might not always be desired.

Function: row (M, i)

Returns the i’th row of the matrix M. The return value is a matrix.

Option variable: rmxchar

Default value: ]

rmxchar is the character drawn on the right-hand side of a matrix.

See also lmxchar.

Option variable: scalarmatrixp

Default value: true

When scalarmatrixp is true, then whenever a 1 x 1 matrix is produced as a result of computing the dot product of matrices it is simplified to a scalar, namely the sole element of the matrix.

When scalarmatrixp is all, then all 1 x 1 matrices are simplified to scalars.

When scalarmatrixp is false, 1 x 1 matrices are not simplified to scalars.

Function: scalefactors (coordinatetransform)

Here the argument coordinatetransform evaluates to the form [[expression1, expression2, ...], indeterminate1, indeterminat2, ...], where the variables indeterminate1, indeterminate2, etc. are the curvilinear coordinate variables and where a set of rectangular Cartesian components is given in terms of the curvilinear coordinates by [expression1, expression2, ...]. coordinates is set to the vector [indeterminate1, indeterminate2,...], and dimension is set to the length of this vector. SF[1], SF[2], …, SF[DIMENSION] are set to the coordinate scale factors, and sfprod is set to the product of these scale factors. Initially, coordinates is [X, Y, Z], dimension is 3, and SF[1]=SF[2]=SF[3]=SFPROD=1, corresponding to 3-dimensional rectangular Cartesian coordinates. To expand an expression into physical components in the current coordinate system, there is a function with usage of the form

Function: setelmx (x, i, j, M)

Assigns x to the (i, j)’th element of the matrix M, and returns the altered matrix.

M [i, j]: x has the same effect, but returns x instead of M.

Function: similaritytransform (M)
Function: simtran (M)

similaritytransform computes a similarity transform of the matrix M. It returns a list which is the output of the uniteigenvectors command. In addition if the flag nondiagonalizable is false two global matrices leftmatrix and rightmatrix are computed. These matrices have the property that leftmatrix . M . rightmatrix is a diagonal matrix with the eigenvalues of M on the diagonal. If nondiagonalizable is true the left and right matrices are not computed.

If the flag hermitianmatrix is true then leftmatrix is the complex conjugate of the transpose of rightmatrix. Otherwise leftmatrix is the inverse of rightmatrix.

rightmatrix is the matrix the columns of which are the unit eigenvectors of M. The other flags (see eigenvalues and eigenvectors) have the same effects since similaritytransform calls the other functions in the package in order to be able to form rightmatrix.

load ("eigen") loads this function.

simtran is a synonym for similaritytransform.

Option variable: sparse

Default value: false

When sparse is true, and if ratmx is true, then determinant will use special routines for computing sparse determinants.

Function: submatrix
    submatrix (i_1, …, i_m, M, j_1, …, j_n)
    submatrix (i_1, …, i_m, M)
    submatrix (M, j_1, …, j_n)

Returns a new matrix composed of the matrix M with rows i_1, …, i_m deleted, and columns j_1, …, j_n deleted.

Function: transpose (M)

Returns the transpose of M.

If M is a matrix, the return value is another matrix N such that N[i,j] = M[j,i].

If M is a list, the return value is a matrix N of length (m) rows and 1 column, such that N[i,1] = M[i].

Otherwise M is a symbol, and the return value is a noun expression 'transpose (M).

Function: triangularize (M)

Returns the upper triangular form of the matrix M, as produced by Gaussian elimination. The return value is the same as echelon, except that the leading nonzero coefficient in each row is not normalized to 1.

lu_factor and cholesky are other functions which yield triangularized matrices.

(%i1) M: matrix ([3, 7, aa, bb], [-1, 8, 5, 2], [9, 2, 11, 4]);
                       [  3   7  aa  bb ]
                       [                ]
(%o1)                  [ - 1  8  5   2  ]
                       [                ]
                       [  9   2  11  4  ]
(%i2) triangularize (M);
             [ - 1   8         5            2      ]
             [                                     ]
(%o2)        [  0   - 74     - 56         - 22     ]
             [                                     ]
             [  0    0    626 - 74 aa  238 - 74 bb ]
Function: uniteigenvectors (M)
Function: ueivects (M)

Computes unit eigenvectors of the matrix M. The return value is a list of lists, the first sublist of which is the output of the eigenvalues command, and the other sublists of which are the unit eigenvectors of the matrix corresponding to those eigenvalues respectively.

The flags mentioned in the description of the eigenvectors command have the same effects in this one as well.

When knowneigvects is true, the eigen package assumes that the eigenvectors of the matrix are known to the user and are stored under the global name listeigvects. listeigvects should be set to a list similar to the output of the eigenvectors command.

If knowneigvects is set to true and the list of eigenvectors is given the setting of the flag nondiagonalizable may not be correct. If that is the case please set it to the correct value. The author assumes that the user knows what he is doing and will not try to diagonalize a matrix the eigenvectors of which do not span the vector space of the appropriate dimension.

load ("eigen") loads this function.

ueivects is a synonym for uniteigenvectors.

Function: unitvector (x)
Function: uvect (x)

Returns x/norm(x); this is a unit vector in the same direction as x.

load ("eigen") loads this function.

uvect is a synonym for unitvector.

Function: vectorpotential (givencurl)

Returns the vector potential of a given curl vector, in the current coordinate system. potentialzeroloc has a similar role as for potential, but the order of the left-hand sides of the equations must be a cyclic permutation of the coordinate variables.

Function: vectorsimp (expr)

Applies simplifications and expansions according to the following global flags:

expandall, expanddot, expanddotplus, expandcross, expandcrossplus, expandcrosscross, expandgrad, expandgradplus, expandgradprod, expanddiv, expanddivplus, expanddivprod, expandcurl, expandcurlplus, expandcurlcurl, expandlaplacian, expandlaplacianplus, and expandlaplacianprod.

All these flags have default value false. The plus suffix refers to employing additivity or distributivity. The prod suffix refers to the expansion for an operand that is any kind of product.

expandcrosscross

Simplifies \(p \sim (q \sim r)\) to \((p . r)q - (p . q)r\).

expandcurlcurl

Simplifies \({\rm curl}\; {\rm curl}\; p\) to \({\rm grad}\; {\rm div}\; p + {\rm div}\; {\rm grad}\; p\).

expandlaplaciantodivgrad

Simplifies \({\rm laplacian}\; p\) to \({\rm div}\; {\rm grad}\; p\).

expandcross

Enables expandcrossplus and expandcrosscross.

expandplus

Enables expanddotplus, expandcrossplus, expandgradplus, expanddivplus, expandcurlplus, and expandlaplacianplus.

expandprod

Enables expandgradprod, expanddivprod, and expandlaplacianprod.

These flags have all been declared evflag.

Option variable: vect_cross

Default value: false

When vect_cross is true, it allows DIFF(X~Y,T) to work where ~ is defined in SHARE;VECT (where VECT_CROSS is set to true, anyway.)

Function: zeromatrix (m, n)

Returns an m by n matrix, all elements of which are zero.


Next: , Previous: Matrices and Linear Algebra, Up: Top   [Contents][Index]

24 Пакет affine


Next: , Previous: Пакет affine, Up: Пакет affine   [Contents][Index]

24.1 Введение в пакет affine

Пакет affine предназначен для работы с группами многочленов.


Previous: Введение в пакет affine, Up: Пакет affine   [Contents][Index]

24.2 Функции и переменные пакета affine

Функция: fast_linsolve ([expr_1, ..., expr_m], [x_1, ..., x_n])

Решает систему линейных уравнений expr_1, ..., expr_m относительно переменных x_1, ..., x_n. Каждый аргумент expr_i может быть уравнением или произвольным выражением. В последнем случае выражение трактуется как уравнение вида expr_i = 0.

Возвращаемое значение является списком вида [x_1 = a_1, ..., x_n = a_n], где a_1, ..., a_n не зависят от переменных x_1, ..., x_n.

fast_linsolve более быстрый чем linsolve для разреженных систем.

Команда load("affine") загружает эту функцию.

Функция: grobner_basis ([expr_1, ..., expr_m])

Возвращает базис Гребнера для уравнений expr_1, ..., expr_m. После этого функция polysimp может быть использована для упрощения других выражений по функций относительно данной системы уравнений.

grobner_basis ([3*x^2+1, y*x])$

polysimp (y^2*x + x^3*9 + 2) ==> -3*x + 2

polysimp(f) возвращает 0 тогда и только тогда, когда f принадлежит идеалу уравнений expr_1, ..., expr_m. Иными словами, тогда и только тогда, когда f является полиномиальной комбинацией элементов expr_1, ..., expr_m.

Команда load("affine") загружает эту функцию.

Функция: set_up_dot_simplifications (eqns, check_through_degree)
Функция: set_up_dot_simplifications (eqns)

Уравнения eqns являются полиномиальными уравнениями относительно некоммутативных переменных. Значение current_variables есть список переменных, используемых для вычисления степеней. Уравнения должны быть однородными по степеням, для того, чтобы процедура сходилась.

Если перекрывающиеся упрощения в dot_simplifications проверены до степени выше степени f, тогда верно следующее: dotsimp(f) дает 0 тогда и только тогда, когда f принадлежит идеалу уравнений, т.е., тогда и только тогда, когда f является полиномиальной комбинацией уравнений.

Здесь степень определяется с помощью nc_degree и зависит от весов отдельных переменных.

Команда load("affine") загружает эту функцию.

Функция: declare_weights (x_1, w_1, ..., x_n, w_n)

Присваивает веса w_1, ..., w_n переменным x_1, ..., x_n. Эти веса используются при вычислении nc_degree.

Команда load("affine") загружает эту функцию.

Функция: nc_degree (p)

Возвращает степень некоммутативного полинома p. См. также declare_weights.

Команда load("affine") загружает эту функцию.

Функция: dotsimp (f)

Возвращает 0 тогда и только тогда, когда f принадлежит идеалу уравнений, т.е., тогда и только тогда, когда f является полиномиальной комбинацией элементов уравнений.

Команда load("affine") загружает эту функцию.

Функция: fast_central_elements ([x_1, ..., x_n], n)

Если set_up_dot_simplifications было уже выполнено, тогда данная функция возвращает центральные полиномы степени n по переменным x_1, ..., x_n.

Например:

set_up_dot_simplifications ([y.x + x.y], 3);
fast_central_elements ([x, y], 2);
[y.y, x.x];

Команда load("affine") загружает эту функцию.

Функция: check_overlaps (n, add_to_simps)

Проверяет перекрытия до степени n, чтобы убедиться, что имеется достаточно правил упрощения для каждой степени чтобы dotsimp работало правильно. Этот процесс может быть ускорен если заранее известна размерность пространства мономов. Если размерность конечная и глобальная, тогда следует использовать hilbert. Если мономиальная размерность неизвестна, то не следут задавать rank_function. Необязательный третий аргумент reset, false означает – не следует спрашивать о переопределении объектов.

Команда load("affine") загружает эту функцию.

Функция: mono ([x_1, ..., x_n], n)

Возвращает список независимых мономов по отношению к текущим упрощениям степени n по переменным x_1, ..., x_n.

Команда load("affine") загружает эту функцию.

Функция: monomial_dimensions (n)

Вычисляет ряд Гильберта до степени n для текущей алгебры.

Команда load("affine") загружает эту функцию.

Функция: extract_linear_equations ([p_1, ..., p_n], [m_1, ..., m_n])

Возвращает список коэффициентов некоммутативных полиномов p_1, ..., p_n некоммутативных мономов m_1, ..., m_n. Коэффициенты должны быть скалярными. Для получения списка мономов используется list_nc_monomials.

Команда load("affine") загружает эту функцию.

Функция: list_nc_monomials ([p_1, ..., p_n])
Функция: list_nc_monomials (p)

Возвращает список некоммутативных мономов полинома p или списка полиномов p_1, ..., p_n.

Команда load("affine") загружает эту функцию.

Управляющая переменная: all_dotsimp_denoms

Значение по умолчанию: false

Когда all_dotsimp_denoms является списком,то знаменатели, встречающиеся при работе dotsimp, добавляются к этому списку. all_dotsimp_denoms может быть инициализировано пустым списком [] перед вызовом dotsimp.

По умолчанию dotsimp не собирает числители.


Next: , Previous: Пакет affine, Up: Top   [Contents][Index]

25 Пакет itensor


Next: , Previous: Пакет itensor, Up: Пакет itensor   [Contents][Index]

25.1 Введение в пакет itensor

В Maxima реализованы два различных типа операций над тензорами: операции над компонентами – пакет ctensor и операции с индексами – пакет itensor.

ВАЖНОЕ ЗАМЕЧАНИЕ: Пожалуйста, ниже, обратите внимание на нововведения в системе индексных обозначений для тензоров.

При операциях с компонентами тензорный объект рассматривается, как многомерный массив или матрица. Операции свертки и ковариантного дифференцирования над такими объектами фактически сводятся к дифференцированию элементов матрицы и суммированию по повторяющимся индексам при помощи команды do. Полученный результат операций над компонентами тензора хранится в форме массива или матрицы.

При операциях с индексами, тензор рассматривается как функция своих индексов (ковариантных, контравариантных и индексов производной). В этом случае результат тензорных операций, например, таких как свертка или ковариантное дифференцирование, достигается только с помощью соответствующих манипуляций с индексами, а не с компонентами, которым они соответствуют.

Оба подхода к рассмотрению дифференциальных, алгебраических и аналитических проблем в контексте Римановой геометрии имеют и преимущества, и недостатки, которые выявляются при рассмотрении конкретных задач. Необходимо иметь ввиду следующие специфические свойства каждого из методов:

i) Представление тензоров в явном виде через их компоненты делает ctensor алгоритмически простым в использовании. Вычисления метрики, производных тензоров и инвариантов реализуются непосредственно по определению. Однако, несмотря на вычислительную мощь Maxima, в случае достаточно сложной метрики, внутренние функциональные связи и координатные зависимости компонент метрики легко могут привести к чрезвычайно громоздким выражениям, со скрытой структурой.

ii) В силу специфики способа, при котором тензора и операции над ними рассматриваются в терминах символьных операций над их индексами, выражения, вычисления которых в компонентном представлении выглядели бы громоздко, могут быть иногда сильно упрощены при помощи использования симметрий тензоров и специальных функций пакета itensor, использующих симметрии. В тоже время, индексное представление тензоров в этом пакете создает определенные трудности при определении метрики, функций и вычислении дифференцируемых объектов.

25.1.1 Новые соглашения для обозначения тензорных индексов

До настоящего времени, в пакете itensor были приняты обозначения, которые не сохраняли порядок индексов при операциях свертки, например:

(%i2) imetric(g);
(%o2)                                done
(%i3) ishow(g([],[j,k])*g([],[i,l])*a([i,j],[]))$
                                 i l  j k
(%t3)                           g    g    a
                                           i j
(%i4) ishow(contract(%))$
                                      k l
(%t4)                                a

Этот результат не верен за исключением случая когда тензор a симметричен. Порядок следования индекса теряется при свертке, несмотря на то, что itensor сохраняет порядок индексов внутри каждого набора ковариантных и контравариантных индексов (в соответствии со свойствами симметрии).

Для того, чтобы избежать данной проблемы была предложена новая система обозначений, которая совместима с существующей. В данном случае контравариантные индексы могут быть вставлены в нужную позицию в наборе ковариантных, но со знаком минус. Функции типа contract() и ishow() были модифицированы таким образом, чтобы понимать новые обозначения.

В данных обозначениях вычисление предыдущего примера дает:

(%i5) ishow(g([-j,-k],[])*g([-i,-l],[])*a([i,j],[]))$
                                 i l       j k
(%t5)                           g    a    g
                                      i j
(%i6) ishow(contract(%))$
                                      l k
(%t6)                                a

В настоящий момент, единственной функцией, где новые обозначения играют существенную роль является lc2kdt. Благодаря этому удается получить корректный результат для тензорного произведения символов Леви-Чивита, применяя метрический тензор не прибегая к пересортировке численных индексов обобщенных символов Кронекера.

Поскольку данные нововведения сделаны относительно недавно, можно ожидать присутствие ошибок. Код был достаточно тщательно протестирован, чтобы убедиться, что ничего не нарушается при использовании старых обозначений. В тоже время при работе в новых обозначения шанс получения ошибки довольно значителен. Для исправления замеченных ошибок обращайтесь к разработчикам.

25.1.2 Манипулирование тензорными индексами

Пакет манипулирования тензорными индексами загружается в Maxima командой load("itensor"). Доступен ряд демонстрационных программ, которые загружаются командой demo(tensor).

В этом пакете тензор рассматривается, как функция индексов и их списков. Список ковариантных индексов – это первый аргумент индексного объекта. Далее идет список контравариантных индексов и индексы производной. Списки могут быть пустыми – []. Это говорит об отсутствии ковариантный или контравариантных индексов тензора. Таким образом, g([a,b],[c]) представляет тензор g, который имеет 2 ковариантных индекса (a,b), один контравариантный – (c) и не имеет индексов производной.

Если есть индексы производной, то они добавляются в качестве дополнительных аргументов после списка контравариантных индексов. Они могут быть либо определены пользователем в явном виде, либо получены в процессе дифференцирования тензора. Поскольку обычная производная – это коммутативная операция, то индексы производной по умолчанию сортируются в алфавитном порядке если флаг iframe_flag не равен true, указывая на то, что используется тетрадная метрика. Такой принцип сортировки делает возможным для Maxima распознать что, например, t([a],[b],i,j) есть тоже самое что и t([a],[b],j,i). Дифференцирование индексных объектов в отношении координат, индексы которых не являются аргументом этого объекта, в обычной ситуации давало бы ноль, потому, что по-умолчанию Maxima не знает, что тензор, представляемый в виде функции по индексам, может неявно зависеть от соответствующей координаты. Модификация существующей функции diff в пакете itensor приводит к тому, что любой индексный объект зависит от любой переменной дифференцирования пока не объявлено обратное. Это делает возможным распространить известное правило суммирования по немым индексам на индексы производных. Необходимо отметить, что itensor не заложена возможность для подъема индексов производных и поэтому они всегда рассматриваются как ковариантные.

В настоящий момент, все функции направленные на упрощение тензорных выражений предполагают, что по умолчанию тензор не обладает какими-либо свойствами симметрии. Это условие может быть переопределено путем замены значения флага allsym:false на true. В этом случае функции манипулирования индексами будут рассматривать все индексные объекты, как полностью симметричные по спискам ковариантных и контравариантных индексов.

Пакет itensor рассматривает тензора, как функциональные объекты. При манипулировании тензорными уравнениями используются алгебраические правила, свойства симметрии и свертки. Кроме того, в itensor определены операции ковариантного дифференцирования, а также кривизна и кручение. Вычисления могут проводится также и с учетом метрики подвижных базисов (тетрады) если значение переменной iframe_flag равно true.

В примере ниже показано как загрузить пакет itensor, задать имя метрики и выполнить простые вычисления.

(%i1) load("itensor");
(%o1)      /share/tensor/itensor.lisp
(%i2) imetric(g);
(%o2)                                done
(%i3) components(g([i,j],[]),p([i,j],[])*e([],[]))$
(%i4) ishow(g([k,l],[]))$
(%t4)                               e p
                                       k l
(%i5) ishow(diff(v([i],[]),t))$
(%t5)                                  0
(%i6) depends(v,t);
(%o6)                               [v(t)]
(%i7) ishow(diff(v([i],[]),t))$
                                    d
(%t7)                               -- (v )
                                    dt   i
(%i8) ishow(idiff(v([i],[]),j))$
(%t8)                                v
                                      i,j
(%i9) ishow(extdiff(v([i],[]),j))$
(%t9)                             v    - v
                                   j,i    i,j
                                  -----------
                                       2
(%i10) ishow(liediff(v,w([i],[])))$
                               %3          %3
(%t10)                        v   w     + v   w
                                   i,%3    ,i  %3
(%i11) ishow(covdiff(v([i],[]),j))$
                                              %4
(%t11)                        v    - v   ichr2
                               i,j    %4      i j
(%i12) ishow(ev(%,ichr2))$
               %4 %5
(%t12) v    - g      v   (e p       + e   p     - e p       - e    p
        i,j           %4     j %5,i    ,i  j %5      i j,%5    ,%5  i j

                                         + e p       + e   p    )/2
                                              i %5,j    ,j  i %5
(%i13) iframe_flag:true;
(%o13)                               true
(%i14) ishow(covdiff(v([i],[]),j))$
                                             %6
(%t14)                        v    - v   icc2
                               i,j    %6     i j
(%i15) ishow(ev(%,icc2))$
                                             %6
(%t15)                        v    - v   ifc2
                               i,j    %6     i j
(%i16) ishow(radcan(ev(%,ifc2,ifc1)))$
             %6 %8                    %6 %8
(%t16) - (ifg      v   ifb       + ifg      v   ifb       - 2 v
                    %6    j %8 i             %6    i j %8      i,j

                                             %6 %8
                                        - ifg      v   ifb      )/2
                                                    %6    %8 i j
(%i17) ishow(canform(s([i,j],[])-s([j,i])))$
(%t17)                            s    - s
                                   i j    j i
(%i18) decsym(s,2,0,[sym(all)],[]);
(%o18)                               done
(%i19) ishow(canform(s([i,j],[])-s([j,i])))$
(%t19)                                 0
(%i20) ishow(canform(a([i,j],[])+a([j,i])))$
(%t20)                            a    + a
                                   j i    i j
(%i21) decsym(a,2,0,[anti(all)],[]);
(%o21)                               done
(%i22) ishow(canform(a([i,j],[])+a([j,i])))$
(%t22)                                 0

Previous: Введение в пакет itensor, Up: Пакет itensor   [Contents][Index]

25.2 Функции и переменные пакета itensor

25.2.1 Манипулирование индексными объектами

Функция: entertensor (name)

это интерактивная функция, которая позволяет создать индексный объект с именем name, содержащий заданные пользователем списки ковариантных и контравариантных индексов и индексы производных. Отдельный индекс или список индексов (возможно пустой) считаются допустимым вводом (см. пример в секции covdiff).

Функция: changename (old, new, expr)

заменяет имя тензора со старого old на новое new в выражении expr. old может быть как простым символом, так и списком в форме [name, m, n]. В последнем случае переименовываются только индексные объекты с именем name с m ковариантным и n контравариантным индексами.

Функция: listoftens (expr)

в качестве результата возвращает список всех тензоров выражения expr. Например,

(%i6) ishow(a([i,j],[k])*b([u],[],v)+c([x,y],[])*d([],[])*e)$
                                         k
(%t6)                        d e c    + a    b
                                  x y    i j  u,v
(%i7) ishow(listoftens(%))$
                               k
(%t7)                        [a   , b   , c   , d]
                               i j   u,v   x y

Функция: ishow (expr)

печатает выражение expr, содержащее индексные объекты, в виде, где ковариантные индексы изображены в нижней позиции, а контравариантные в верхней. Индексы производной изображаются после ковариантных индексов и отделены запятой (примеры вывода данной функции можно найти практически в любой части этого документа).

Функция: indices (expr)

Возвращает список из двух элементов. Первый – список свободных индексов, не участвующих в свертке, в expr. Второй – список немых индексов, участвующих в свертках. Например,

(%i1) load("itensor");
(%o1)      /share/tensor/itensor.lisp
(%i2) ishow(a([i,j],[k,l],m,n)*b([k,o],[j,m,p],q,r))$
                                k l      j m p
(%t2)                          a        b
                                i j,m n  k o,q r
(%i3) indices(%);
(%o3)                 [[l, p, i, n, o, q, r], [k, j, m]]

Тензорное произведение в котором один и тот же немой индекс встречается более чем два раза является синтаксически неправильным. При работе с ним Maxima выдаст ошибку.

Функция: rename (expr)
Функция: rename (expr, count)

Возвращает выражение эквивалентное исходному expr, но в котором все немые индексы переименованы и пронумерованы. Имена берутся из списка [%1, %2, ...]. В качестве опции можно задать номер count с которого начинается список пронумерованных индексов. По умолчанию немые индексы нумеруются от текущей величины count. Все немые индексы в произведении встречаются ровно 2 раза. В случае ошибки пользователя, когда в исходном выражении одно и тоже имя немого индекса встречается более двух раз, Maxima выдаст ошибку и остановит вычисления. Для суммы тензорных произведений, rename применяется к каждому члену суммы при этом счетчик count каждый раз обнуляется при переходе к следующему слагаемому. В этом случае функция rename может служить для упрощения тензорных выражений. Кроме того, если allsym равно true, то индексы сортируются в алфавитном порядке. Если значение flipflag равно false, то переименование и сортировка осуществляется относительно порядка контравариантных индексов. В случае если значение flipflag равно true переименование и сортировка производится относительно порядка ковариантных индексов. Часто бывает, что комбинированный эффект двух применений rename с переменой значения флага flipflag позволяет существенно упростить исходное выражение. Например,

(%i1) load("itensor");
(%o1)      /share/tensor/itensor.lisp
(%i2) allsym:true;
(%o2)                                true
(%i3) g([],[%4,%5])*g([],[%6,%7])*ichr2([%1,%4],[%3])*
ichr2([%2,%3],[u])*ichr2([%5,%6],[%1])*ichr2([%7,r],[%2])-
g([],[%4,%5])*g([],[%6,%7])*ichr2([%1,%2],[u])*
ichr2([%3,%5],[%1])*ichr2([%4,%6],[%3])*ichr2([%7,r],[%2]),noeval$
(%i4) expr:ishow(%)$

       %4 %5  %6 %7      %3         u          %1         %2
(%t4) g      g      ichr2      ichr2      ichr2      ichr2
                         %1 %4      %2 %3      %5 %6      %7 r

        %4 %5  %6 %7      u          %1         %3         %2
     - g      g      ichr2      ichr2      ichr2      ichr2
                          %1 %2      %3 %5      %4 %6      %7 r
(%i5) flipflag:true;
(%o5)                                true
(%i6) ishow(rename(expr))$
       %2 %5  %6 %7      %4         u          %1         %3
(%t6) g      g      ichr2      ichr2      ichr2      ichr2
                         %1 %2      %3 %4      %5 %6      %7 r

        %4 %5  %6 %7      u          %1         %3         %2
     - g      g      ichr2      ichr2      ichr2      ichr2
                          %1 %2      %3 %4      %5 %6      %7 r
(%i7) flipflag:false;
(%o7)                                false
(%i8) rename(%th(2));
(%o8)                                  0
(%i9) ishow(rename(expr))$
       %1 %2  %3 %4      %5         %6         %7        u
(%t9) g      g      ichr2      ichr2      ichr2     ichr2
                         %1 %6      %2 %3      %4 r      %5 %7

        %1 %2  %3 %4      %6         %5         %7        u
     - g      g      ichr2      ichr2      ichr2     ichr2
                          %1 %3      %2 %6      %4 r      %5 %7
Управляющая переменная: flipflag

Значение по умолчанию: false

Если значение flipflag равно false, то сортировка и переименование индексов осуществляется относительно порядка контравариантных индексов, в противном случае – относительно порядка ковариантных индексов. Значение флага flipflag влияет на результат применения функции rename() следующим образом: если flipflag равно false то rename формирует список немых индексов по списку контравариантных индексов, по мере поступления, слева направо (если значение флага равно true, тогда используется список ковариантных индексов). Первый немой индекс в списке переименовывается в %1, следующий в %2 и т.д.). Затем индексы сортируются (см. пример в rename()).

Функция: defcon (tensor_1)
Функция: defcon (tensor_1, tensor_2, tensor_3)

задает свойства тензорной свертки тензора tensor_1 с tensor_3 так, что в результате получается tensor_3 с соответствующими индексами. Если задан единственный аргумент, tensor_1, тогда свертка любого другого тензора (скажем my_tensor) с tensor_1 дает тот же тензор (my_tensor), но с новым набором индексов в соответствии с операцией свертки. В этом случае, tensor_1 может быть использован для подъема или опускания индексов.

Например, пусть imetric:g, тогда путем defcon(g) можно реализовать подъем и опускание индексов тензора, сворачивая его с метрическим тензором.

Для одного и того же индексного объекта может быть задано более одного правила свертки. В этом случае, для одинаковых объектов используется правило свертки заданное последним. contractions содержит список индексных объектов с заданными, посредством defcon, правилами свертки.

Функция: remcon (tensor_1 , ..., tensor_n)

удаляет все правила свертки для объектов tensor_i. remcon(all) удаляет все правила свертки для всех индексных объектов.

Функция: contract (expr)

Выполняет свертку тензорного выражения expr, которое само по себе может быть произвольной комбинацией сумм и произведений тензоров. Правила свертки должны быть предварительно заданы с помощью defcon. Для наилучших результатов, в выражении expr, необходимо раскрыть все скобки. Если коэффициенты при тензорах в expr не содержат дробей, то наиболее эффективный и быстрый способ раскрытия скобок в expr состоит в применении функции ratexpand. При этом, флаг gcd можно положить равным false, чтобы программа не пыталась искать сокращение множителей, используя GCD алгоритмы.

Функция: indexed_tensor (tensor)

Данная операция необходима всяких раз, когда пользователь собирается присвоить новые индексные выражения компонентам тензора tensor, для которого в системе уже предусмотрено свое индексное представление. Примером могут служить символы Кристоффеля 1-го и 2-го рода ichr1, ichr2, выраженные через компоненты метрики, или тензор кривизны Римана icurvature. См. пример в пункте icurvature.

Функция: components (tensor, expr)

Данная функция присваивает тензору tensor индексное выражение expr. Это приводит к тому, что при последующих вычислениях индексные выражения tensor автоматически заменяются на соответствующие expr. tensor должен иметь вид t([...],[...]), где каждый из списков может быть пустым. expr может быть любым индексным выражением имеющим тот же набор свободных индексов (не участвующих в свертке), что и tensor. Если expr содержит свертки, то необходимо быть внимательным в выборе значений немых индексов, чтобы избежать повторных немых индексов. В этом случае можно рекомендовать другой способ присваивания компонент, заключающийся в использовании конструкций defrule (см. пример ниже). Функция remcomps очищает использованное ранее определение компонент тензора.

Важно понимать, что для components важна только валентность тензора а не порядок индексов. Присваивание значения x([i,-j],[]), x([-j,i],[]) или x([i],[j]) приводит к одному результату – значение присваивается тензору с именем x и валентностью (1,1).

Любому индексному выражению можно присвоить любое другое индексное представление и компоненты 4-мя различными способами, 2 способа включают использование, рассмотренной выше функции components:

1) Присваивание одного индексного выражения другому:

(%i2) components(g([],[i,j]),e([],[i])*p([],[j]))$
(%i3) ishow(g([],[i,j]))$
                                      i  j
(%t3)                                e  p

2) В виде матрицы компонент:

(%i6) components(g([i,j],[]),lg);
(%o6)                                done
(%i7) ishow(g([i,j],[]))$
(%t7)                                g
                                      i j
(%i8) g([3,3],[]);
(%o8)                                  1
(%i9) g([4,4],[]);
(%o9)                                 - 1

3) Путем определения функции. В примере ниже, тензор h равен kdelta если h имеет одинаковое количество ковариантных и контравариантных индексов, а индексы производной отсутствуют. В любом другом случае, тензор h равен тензору g:

(%i4) h(l1,l2,[l3]):=if length(l1)=length(l2) and length(l3)=0
  then kdelta(l1,l2) else apply(g,append([l1,l2], l3))$
(%i5) ishow(h([i],[j]))$
                                          j
(%t5)                               kdelta
                                          i
(%i6) ishow(h([i,j],[k],l))$
                                     k
(%t6)                               g
                                     i j,l

4) Последний пример связан с использованием конструкций типа defrule.

(%i1) load("itensor");
(%o1)      /share/tensor/itensor.lisp
(%i2) matchdeclare(l1,listp);
(%o2)                                done
(%i3) defrule(r1,m(l1,[]),(i1:idummy(),
      g([l1[1],l1[2]],[])*q([i1],[])*e([],[i1])))$

(%i4) defrule(r2,m([],l1),(i1:idummy(),
      w([],[l1[1],l1[2]])*e([i1],[])*q([],[i1])))$

(%i5) ishow(m([i,n],[])*m([],[i,m]))$
                                    i m
(%t5)                              m    m
                                         i n
(%i6) ishow(rename(applyb1(%,r1,r2)))$
                           %1  %2  %3 m
(%t6)                     e   q   w     q   e   g
                                         %1  %2  %3 n


Функция: remcomps (tensor)

Удаляет из системы значения компонент тензора tensor, присвоенных при помощи функции components.

Функция: showcomps (tensor)

Печатает значение компонент тензора, которые были присвоены с помощью components. Данная функция особенно полезна в случае, когда компоненты тензора были заданы с помощью матрицы, как в данном примере:

(%i1) load("ctensor");
(%o1)       /share/tensor/ctensor.mac
(%i2) load("itensor");
(%o2)      /share/tensor/itensor.lisp
(%i3) lg:matrix([sqrt(r/(r-2*m)),0,0,0],[0,r,0,0],
                [0,0,sin(theta)*r,0],[0,0,0,sqrt((r-2*m)/r)]);
               [         r                                     ]
               [ sqrt(-------)  0       0              0       ]
               [      r - 2 m                                  ]
               [                                               ]
               [       0        r       0              0       ]
(%o3)          [                                               ]
               [       0        0  r sin(theta)        0       ]
               [                                               ]
               [                                      r - 2 m  ]
               [       0        0       0        sqrt(-------) ]
               [                                         r     ]
(%i4) components(g([i,j],[]),lg);
(%o4)                                done
(%i5) showcomps(g([i,j],[]));
                  [         r                                     ]
                  [ sqrt(-------)  0       0              0       ]
                  [      r - 2 m                                  ]
                  [                                               ]
                  [       0        r       0              0       ]
(%t5)      g    = [                                               ]
            i j   [       0        0  r sin(theta)        0       ]
                  [                                               ]
                  [                                      r - 2 m  ]
                  [       0        0       0        sqrt(-------) ]
                  [                                         r     ]
(%o5)                                false

Функция showcomps может также печатать компоненты тензоров ранга выше чем 2.

Функция: idummy ()

Увеличивает значение счетчика icounter немых индексов на 1 и возвращает значение индекса в форме %n, где n это положительное целое число. Применение idummy гарантирует, что немые индексы, встречающиеся в текущем выражении? не будут конфликтовать с уже использованными (см. пример в секции indices).

Управляющая переменная: idummyx

Значение по умолчанию: %

Данная переменная задает приставку (префикс) для генерируемых немых индексов (см. пример в секции indices).

Управляющая переменная: icounter

Значение по умолчанию: 1

Определяет численный суффикс для генерируемого немого индекса. Приставка (префикс) определяется переменной idummyx

Функция: kdelta (l1, l2)

Обобщенный символ Кронекера, где l1 и l2 – списки ковариантных и контравариантных индексов соответственно. kdelta([i],[j]) возвращает обычный дельта-символ Кронекера. Команда ev(expr,kdelta) вычисляет expr, заменяя все конструкции вида kdelta([],[]) (след kdelta) на размерность многообразия.

itensor также позволяет использование в kdelta() c двумя ковариантными или двумя контравариантными индексами. Эта дает возможность задать единичную ко(нтра)-вариантную матрицу. Данная конструкция предусмотрена только для целей программирования. Следует помнить, что в itensor kdelta([i,j],[]) не является разрешенным тензорным объектом. Будьте готовы,что при операциях с kdelta([i,j],[]) Maxima может пожаловаться на неправильный индексный объект и отказаться от дальнейших вычислений.

Функция: kdels (l1, l2)

Симметризованная версия обобщенного дельта-символа Кронекера. Введена для удобства вычислений. Свертка выражения с этим тензором приводит к его симметризации. Примеры:

(%i1) load("itensor");
(%o1)      /share/tensor/itensor.lisp
(%i2) kdelta([1,2],[2,1]);
(%o2)                                 - 1
(%i3) kdels([1,2],[2,1]);
(%o3)                                  1
(%i4) ishow(kdelta([a,b],[c,d]))$
                             c       d         d       c
(%t4)                  kdelta  kdelta  - kdelta  kdelta
                             a       b         a       b
(%i4) ishow(kdels([a,b],[c,d]))$
                             c       d         d       c
(%t4)                  kdelta  kdelta  + kdelta  kdelta
                             a       b         a       b

Функция: levi_civita (l)

Перестановочный тензор Леви-Чивита, который дает 1 если список l является четной перестановкой целых чисел, -1 для нечетной перестановки, и 0 когда встречаются повторяющиеся индексы.

Функция: lc2kdt (expr)

Приводит к упрощению выражений содержащих символы Леви-Чивита (произведения этих символов заменяются на соответствующие дельта-символы Кронекера). Основная разница между действием данной функции и непосредственным вычислением перестановочного тензора состоит в том, что прямое вычисление тензора Леви-Чивита часто приводит к выражениям содержащим дельта-символы с целочисленными значения индексов, что затрудняет дальнейшие операции. Применение функции lc2kdt позволяет избежать этих проблем.

(%i1) load("itensor");
(%o1)      /share/tensor/itensor.lisp
(%i2) expr:ishow('levi_civita([],[i,j])
                 *'levi_civita([k,l],[])*a([j],[k]))$
                                  i j  k
(%t2)                  levi_civita    a  levi_civita
                                       j            k l
(%i3) ishow(ev(expr,levi_civita))$
                                  i j  k       1 2
(%t3)                       kdelta    a  kdelta
                                  1 2  j       k l
(%i4) ishow(ev(%,kdelta))$
             i       j         j       i   k
(%t4) (kdelta  kdelta  - kdelta  kdelta ) a
             1       2         1       2   j

                               1       2         2       1
                        (kdelta  kdelta  - kdelta  kdelta )
                               k       l         k       l
(%i5) ishow(lc2kdt(expr))$
                     k       i       j    k       j       i
(%t5)               a  kdelta  kdelta  - a  kdelta  kdelta
                     j       k       l    j       k       l
(%i6) ishow(contract(expand(%)))$
                                 i           i
(%t6)                           a  - a kdelta
                                 l           l

Для использования lc2kdt() необходимо задать метрический тензор (для случая когда, встречаются произведения перестановочных тензоров одинакового ранга и типа). Если метрика не была задана заранее (с помощью imetric), то можно столкнуться с ошибкой.

(%i7) expr:ishow('levi_civita([],[i,j])
                 *'levi_civita([],[k,l])*a([j,k],[]))$
                                 i j            k l
(%t7)                 levi_civita    levi_civita    a
                                                     j k
(%i8) ishow(lc2kdt(expr))$
Maxima encountered a Lisp error:

 Error in $IMETRIC [or a callee]:
 $IMETRIC [or a callee] requires less than two arguments.

Automatically continuing.
To reenable the Lisp debugger set *debugger-hook* to nil.
(%i9) imetric(g);
(%o9)                                done
(%i10) ishow(lc2kdt(expr))$
         %3 i       k   %4 j       l     %3 i       l   %4 j
(%t10) (g     kdelta   g     kdelta   - g     kdelta   g    
                    %3             %4               %3
              k
        kdelta  ) a
              %4   j k
(%i11) ishow(contract(expand(%)))$
                                  l i      l i
(%t11)                           a    - a g

Функция: lc_l

Правило упрощения выражений содержащих индексные символы Леви-Чивита (levi_civita). Данное правило преобразования использует свойства антисимметрии перестановочного тензора. Например:

(%i1) load("itensor");
(%o1)      /share/tensor/itensor.lisp
(%i2)  el1:ishow('levi_civita([i,j,k],[])*a([],[i])*a([],[j]))$
                             i  j
(%t2)                       a  a  levi_civita
                                             i j k
(%i3) el2:ishow('levi_civita([],[i,j,k])*a([i])*a([j]))$
                                       i j k
(%t3)                       levi_civita      a  a
                                              i  j
(%i4) ishow(canform(contract(expand(applyb1(el1,lc_l,lc_u)))))$
(%t4)                                  0
(%i5) ishow(canform(contract(expand(applyb1(el2,lc_l,lc_u)))))$
(%t5)                                  0

Функция: lc_u

Правило упрощения выражений содержащих индексные символы Леви-Чивита (levi_civita), аналогично lc_l, данное правило преобразования использует свойства антисимметрии перестановочного тензора (см. пример в секции lc_l).

Функция: canten (expr)

Функция предназначена для упрощения тензорных выражений путем переименования и перестановки немых индексов. Область применения canten ограничена. Данная функция применима только для сумм тензорных произведений в которых отсутствуют индексы производной и не встречаются символы Леви-Чивита. Ввиду этих ограничений, следует избегать ее использования. Вместо нее рекомендуется применять canform.

Функция: concan (expr)

Аналогична canten но дополнительно производит свертку индексов.

25.2.2 Симметрии тензоров

Управляющая переменная: allsym

Значение по умолчанию: false

Если данной переменной присвоить true, тогда все индексные объекты будут считаться симметричными по всем ковариантным и контравариантным индексам. Если allsym равно false, все тензора не имеют никаких свойств симметрии априори, пока симметрии не будут объявлены. Индексы производной предполагаются симметричными, до тех пор пока не объявлено, что iframe_flag равен true.

Функция: decsym (tensor, m, n, [cov_1, cov_2, ...], [contr_1, contr_2, ...])

Объявляет свойства симметрии тензора tensor по m ковариантному и n контравариантным индексам, где cov_i и contr_i – псевдофункции, выражающие соотношения перестановочных симметрий по ковариантным и контравариантным индексам соответственно. Данные псевдофункции записываются в форме symoper(index_1, index_2, ...), где переменная symoper принимает одно из следующих: sym, anti или cyc, которые означают соответственно, симметрию, антисимметрию или цикличность индексов. Переменная index_i принимает целочисленные значения и указывает на позицию индекса в tensor, для которого объявляются свойства симметрии. Определения вида symoper(all) также дозволены, означая, что все индексы удовлетворяют выбранному свойству симметрии. Например, рассмотрим тензорный объект b с 5-ю ковариантными индексами. Команда decsym(b,5,3,[sym(1,2),anti(3,4)],[cyc(all)]) объявляет b симметричным по первому и второму индексу, антисимметричным по 3 и 4 ковариантным индексам и циклическим по всем контравариантным индексам. Список декларирующий симметрии может быть пустым. Функция canform использует декларированные свойства симметрии для упрощения тензорных выражений. Примеры даны ниже.

(%i1) load("itensor");
(%o1)      /share/tensor/itensor.lisp
(%i2) expr:contract( expand( a([i1, j1, k1], [])
           *kdels([i, j, k], [i1, j1, k1])))$
(%i3) ishow(expr)$
(%t3)         a      + a      + a      + a      + a      + a
               k j i    k i j    j k i    j i k    i k j    i j k
(%i4) decsym(a,3,0,[sym(all)],[]);
(%o4)                                done
(%i5) ishow(canform(expr))$
(%t5)                              6 a
                                      i j k
(%i6) remsym(a,3,0);
(%o6)                                done
(%i7) decsym(a,3,0,[anti(all)],[]);
(%o7)                                done
(%i8) ishow(canform(expr))$
(%t8)                                  0
(%i9) remsym(a,3,0);
(%o9)                                done
(%i10) decsym(a,3,0,[cyc(all)],[]);
(%o10)                               done
(%i11) ishow(canform(expr))$
(%t11)                        3 a      + 3 a
                                 i k j      i j k
(%i12) dispsym(a,3,0);
(%o12)                     [[cyc, [[1, 2, 3]], []]]

Функция: remsym (tensor, m, n)

Удаляет все свойства симметрии тензора tensor, имеющего m ковариантных и n контравариантных индексов.

Функция: canform (expr)
Функция: canform (expr, rename)

Упрощает выражение expr, используя переименование немых индексов и сортировку всех индексов с учетом объявленных свойств симметрии. Если allsym равен true, тогда все индексные выражения подразумеваются симметричными по всем индексам. В противном случае используется свойства , объявленные при помощи decsym. Немые индексы переименовываются таким же образом, как и при использовании rename. Следует иметь ввиду, что упрощение громоздких выражений может потребовать значительного количества вычислительного времени и ресурсов памяти. Иногда затраты на вычисления можно уменьшить если сначала переименовать индексы при помощи rename. См. примеры в пункте decsym. Заметим, что canform не всегда приводит выражение к простейшей форме. В тоже время canform всегда возвращает математически корректный результат.

Если значение второго необязательного параметра rename равно false, то переименование не производится.

25.2.3 Операции над индексами тензоров

Функция: diff (expr, v_1, [n_1, [v_2, n_2] ...])

Стандартная функция дифференцирования Maxima, которая в пакете itensor имеет дополнительные свойства. Данная конструкция означает взятие производной выражения expr по переменной v_1, n_1 раз, по v_2, n_2раз и т.д. В применении к тензорным объектам, функция дифференцирования модифицирована таким образом, что v_i может иметь целочисленные значения от 1 до dim. В этом случае дифференцирование выполняется по отношению к v_i-ому элементу списка vect_coords. Если vect_coords является атомом, тогда переменная индексированная именем v_i будет использована как переменная для дифференцирования. Это допускает использование массива имен координат или индексированных имен типа x[1], x[2], в качестве переменных дифференцирования.

Функция: idiff (expr, v_1, [n_1, [v_2, n_2] ...])

Индексное дифференцирование. В отличие от функции diff, которая дифференцирует в отношении некоторой независимой переменной, idiff может быть использован при дифференцировании по координате. Для индексного объекта, такое дифференцирование добавляет v_i к индексам производной (он добавляется последовательно к ковариантным индексам после запятой). В дальнейшем индексы производной могут сортироваться если переменная iframe_flag не равна true.

idiff можно использовать при дифференцировании детерминанта метрического тензора. Таким образом, если метрика imetric обозначена через g, тогда idiff(determinant(g),k) возвращает 2*determinant(g)*ichr2([%i,k],[%i]), где немой индекс %i пробегает соответствующие значения.

Функция: liediff (v, tensor)

Вычисляет производную Ли от тензорного выражения tensor в отношении векторного поля v. tensor может быть произвольным тензорным объектом, а v – имя векторного поля (без индексов). Например:

(%i1) load("itensor");
(%o1)      /share/tensor/itensor.lisp
(%i2) ishow(liediff(v,a([i,j],[])*b([],[k],l)))$
       k    %2            %2          %2
(%t2) b   (v   a       + v   a     + v   a    )
       ,l       i j,%2    ,j  i %2    ,i  %2 j

                          %1  k        %1  k      %1  k
                      + (v   b      - b   v    + v   b   ) a
                              ,%1 l    ,l  ,%1    ,l  ,%1   i j

Функция: rediff (ten)

Вычисляет все команды idiff в выражении ten.

Функция: undiff (expr)

Возвращает выражение эквивалентное expr, но в котором все производные индексных объектов заменяются на не вычисляемую форму функции idiff с такими аргументами, чтобы при дифференцировании получился бы соответствующий индексный объект. Это бывает полезно, когда желательно провести некоторые замены в продифференцированных индексных объектах. После этого дифференцирование выполняется при помощи ev(expr, idiff).

Функция: evundiff

Эквивалентно применению undiff, затем ev и rediff.

При помощи этой функции можно легко вычислять выражения, дифференциальную форму которых иначе невозможно вычислить. Например, следующее выражение приводит к ошибке:

(%i1) load("itensor");
(%o1)      /share/tensor/itensor.lisp
(%i2) icurvature([i,j,k],[l],m);
Maxima encountered a Lisp error:

 Error in $ICURVATURE [or a callee]: 
 $ICURVATURE [or a callee] requires less than three arguments.

Automatically continuing.
To reenable the Lisp debugger set *debugger-hook* to nil.

Однако, если сначала ввести icurvature в не вычисляемой форме, а затем применить evundiff, то получим желаемый результат:

(%i3) ishow('icurvature([i,j,k],[l],m))$
                                         l
(%t3)                          icurvature
                                         i j k,m
(%i4) ishow(evundiff(%))$
             l              l         %1           l           %1
(%t4) - ichr2        - ichr2     ichr2      - ichr2       ichr2
             i k,j m        %1 j      i k,m        %1 j,m      i k

             l              l         %1           l           %1
      + ichr2        + ichr2     ichr2      + ichr2       ichr2
             i j,k m        %1 k      i j,m        %1 k,m      i j

ЗАМЕЧАНИЕ: В ранних версиях Maxima, операции производных в определениях символов Кристоффеля всегда должны были вводится в не вычисляемой форме. Сейчас это исправлено и надобность в процедуре evundiff в этом случае отпала. Например:

(%i5) imetric(g);
(%o5)                                done
(%i6) ishow(ichr2([i,j],[k],l))$
       k %3
      g     (g         - g         + g        )
              j %3,i l    i j,%3 l    i %3,j l
(%t6) -----------------------------------------
                          2

                         k %3
                        g     (g       - g       + g      )
                         ,l     j %3,i    i j,%3    i %3,j
                      + -----------------------------------
                                         2
Функция: flush (expr, tensor_1, tensor_2, ...)

Обнуляет в expr все объекты tensor_i, не имеющие индексов производной.

Функция: flushd (expr, tensor_1, tensor_2, ...)

Обнуляет в expr все объекты tensor_i, имеющие индексы производной.

Функция: flushnd (expr, tensor, n)

Обнуляет в expr все объекты tensor, имеющие n и больше индексов производной. Например,

(%i1) load("itensor");
(%o1)      /share/tensor/itensor.lisp
(%i2) ishow(a([i],[J,r],k,r)+a([i],[j,r,s],k,r,s))$
                                J r      j r s
(%t2)                          a      + a
                                i,k r    i,k r s
(%i3) ishow(flushnd(%,a,3))$
                                     J r
(%t3)                               a
                                     i,k r
Функция: coord (tensor_1, tensor_2, ...)

Дает тензорам tensor_i свойства координатного дифференцирования, такие что производная контравариантного вектора, имя которого совпадает с одним из tensor_i, дает дельта-символ Кронекера. Например, если coord(x), тогда вычисление idiff(x([],[i]),j) дает kdelta([i],[j]). coord это список всех индексных объектов имеющих это свойство.

Функция: remcoord (tensor_1, tensor_2, ...)

Удаляет свойства координатного дифференцирования для объектов tensor_i. remcoord(all) удаляет свойства координатного дифференцирования для всех индексных объектов.

Функция: makebox (expr)

Служит для цели аналогичной ishow. В дополнение, все даламбертианы, встречающиеся в expr отображаются символом []. Например, []p([m],[n]) представляет сокращение для g([],[i,j])*p([m],[n],i,j).

Функция: conmetderiv (expr, tensor)

Используется для упрощения выражений, содержащих частные производные ковариантных и контравариантных форм метрического тензора. Например, при помощи conmetderiv можно связать частные производные метрического тензора с символами Кристоффеля:

(%i1) load("itensor");
(%o1)      /share/tensor/itensor.lisp
(%i2) ishow(g([],[a,b],c))$
                                      a b
(%t2)                                g
                                      ,c
(%i3) ishow(conmetderiv(%,g))$
                         %1 b      a       %1 a      b
(%t3)                 - g     ichr2     - g     ichr2
                                   %1 c              %1 c

Функция: simpmetderiv (expr)
Функция: simpmetderiv (expr [, stop])

Упрощает выражения, содержащие произведения производных метрического тензора. В частности simpmetderiv использует два тождества:

   ab        ab           ab                 a
  g   g   + g   g     = (g   g  )   = (kdelta )   = 0
   ,d  bc        bc,d         bc ,d          c ,d

откуда

   ab          ab
  g   g   = - g   g
   ,d  bc          bc,d

и

  ab          ab
 g   g     = g   g
  ,j  ab,i    ,i  ab,j

которое следует из симметрии символов Кристоффеля.

Функция simpmetderiv имеет один необязательный аргумент, который, если присутствует, вызывает прекращение работы функции сразу после первой успешной подстановки. Функция simpmetderiv использует глобальную опцию flipflag, которая определяет каким образом следует выбирать "канонический" порядок индексов произведения.

В целом, данные возможности позволяют осуществлять упрощения, которые невозможно реализовать другими способами, что демонстрируется в следующем примере:

(%i1) load("itensor");
(%o1)      /share/tensor/itensor.lisp
(%i2) imetric(g);
(%o2)                                done
(%i3) ishow(g([],[a,b])*g([],[b,c])*g([a,b],[],d)*g([b,c],[],e))$
                             a b  b c
(%t3)                       g    g    g      g
                                       a b,d  b c,e
(%i4) ishow(canform(%))$

errexp1 has improper indices
 -- an error.  Quitting.  To debug this try debugmode(true);
(%i5) ishow(simpmetderiv(%))$
                             a b  b c
(%t5)                       g    g    g      g
                                       a b,d  b c,e
(%i6) flipflag:not flipflag;
(%o6)                                true
(%i7) ishow(simpmetderiv(%th(2)))$
                               a b  b c
(%t7)                         g    g    g    g
                               ,d   ,e   a b  b c
(%i8) flipflag:not flipflag;
(%o8)                                false
(%i9) ishow(simpmetderiv(%th(2),stop))$
                               a b  b c
(%t9)                       - g    g    g      g
                                    ,e   a b,d  b c
(%i10) ishow(contract(%))$
                                    b c
(%t10)                           - g    g
                                    ,e   c b,d

См. также weyl.dem, для примера совместного применения simpmetderiv и conmetderiv для упрощения тензора Вейля.

Функция: flush1deriv (expr, tensor)

Обнуляет все производные первого порядка от tensor в expr.

25.2.4 Тензоры в искривленном пространстве

Функция: imetric (g)
Системная переменная: imetric

Определяет имя метрического тензора, присваивая соответствующее значение переменной imetric, imetric:g. В дополнение к этому программа устанавливает соответствующие свойства свертки для данной метрики: defcon(g), defcon(g,g,kdelta). По умолчанию переменная imetric не имеет значения.

Функция: ichr1 ([i, j, k])

Дает значение символа Кристоффеля первого рода, которое по определению равно:

       (g      + g      - g     )/2 .
         ik,j     jk,i     ij,k

Перед тем как использовать явные выражения для символов Кристоффеля необходимо определить имя метрического тензора, присвоив соответствующее значение переменной imetric, см. пример ниже в разделе covdiff.

Функция: ichr2 ([i, j],[k])

Дает значение символа Кристоффеля 2-го рода, которые по определению равны:

                       ks
   ichr2([i,j],[k]) = g    (g      + g      - g     )/2
                             is,j     js,i     ij,s
Функция: icurvature ([i, j, k], [h])

Дает выражение для тензора кривизны Римана через символы Кристоффеля 2-го рода (ichr2). Используется следующее определение:

            h             h            h         %1         h
  icurvature     = - ichr2      - ichr2     ichr2    + ichr2
            i j k         i k,j        %1 j      i k        i j,k
                            h          %1
                     + ichr2      ichr2
                            %1 k       i j
Функция: covdiff (expr, v_1, v_2, ...)

Вычисляет ковариантную производную от expr по переменным v_i используя символы Кристоффеля 2-го рода (ichr2). Для получения явных выражений ковариантной производной через компоненты метрики необходимо использовать ev(expr,ichr2), определив предварительно метрический тензор.

(%i1) load("itensor");
(%o1)      /share/tensor/itensor.lisp
(%i2) entertensor()$
Enter tensor name: a;
Enter a list of the covariant indices: [i,j];
Enter a list of the contravariant indices: [k];
Enter a list of the derivative indices: [];
                                      k
(%t2)                                a
                                      i j
(%i3) ishow(covdiff(%,s))$
             k         %1     k         %1     k
(%t3)     - a     ichr2    - a     ichr2    + a
             i %1      j s    %1 j      i s    i j,s

             k     %1
      + ichr2     a
             %1 s  i j
(%i4) imetric:g;

(%o4)                                  g
(%i5) ishow(ev(%t3,ichr2))$

         %1 %4  k
        g      a     (g       - g       + g      )
                i %1   s %4,j    j s,%4    j %4,s
(%t5) - ------------------------------------------
                            2
    %1 %3  k
   g      a     (g       - g       + g      )
           %1 j   s %3,i    i s,%3    i %3,s
 - ------------------------------------------
                       2
    k %2  %1
   g     a    (g        - g        + g       )
          i j   s %2,%1    %1 s,%2    %1 %2,s     k
 + ------------------------------------------- + a
                        2                         i j,s

Функция: lorentz_gauge (expr)

Налагает условие Лоренцевой калибровки на все индексные объекты в expr, приравнивая к нулю те, в которых индекс производной совпадает с одним из контравариантных индексов.

Функция: igeodesic_coords (expr, name)

Позволяет пользователю обнулить не дифференцированные символы Кристоффеля и первые производные метрического тензора в expr (подразумевая "нормальные" координаты). Переменная name в функции igeodesic_coords может относится, или к имени метрики (если таковая присутствует в явном виде в expr), или к имени связности в качестве которых используются фиксированные имена ichr1 и (или) ichr2. В следующем примере, при помощи igeodesic_coords), проверяется свойство цикличности тензора Римана.

(%i1) load("itensor");
(%o1)      /share/tensor/itensor.lisp
(%i2) ishow(icurvature([r,s,t],[u]))$
             u            u         %1         u     
(%t2) - ichr2      - ichr2     ichr2    + ichr2      
             r t,s        %1 s      r t        r s,t 

                                              u         %1
                                       + ichr2     ichr2
                                              %1 t      r s
(%i3) ishow(igeodesic_coords(%,ichr2))$
                                 u            u
(%t3)                       ichr2      - ichr2
                                 r s,t        r t,s
(%i4) ishow(igeodesic_coords(icurvature([r,s,t],[u]),ichr2)+
            igeodesic_coords(icurvature([s,t,r],[u]),ichr2)+
            igeodesic_coords(icurvature([t,r,s],[u]),ichr2))$
             u            u            u            u
(%t4) - ichr2      + ichr2      + ichr2      - ichr2
             t s,r        t r,s        s t,r        s r,t

                                             u            u
                                      - ichr2      + ichr2
                                             r t,s        r s,t
(%i5) canform(%);
(%o5)                                  0

25.2.5 Вычисления в подвижном базисе

В Maxima существует возможность проводить вычисления с использованием подвижных базисов в качестве которых можно выбирать, либо ортонормированный базис типа тетрады либо произвольный базис.

Для использования подвижного базиса переменной iframe_flag необходимо присвоить значение true. В этом случае символы Кристоффеля ichr1 и ichr2 заменяются более общими коэффициентами связности icc1 и icc2 соответственно. Выражения для covdiff и icurvature также заменяются более общими.

Базис определяется двумя тензорами: полем дуального базиса (ifri), и метрическим тензором ifg. Для ортонормированного базиса метрический тензор совпадает с единичной матрицей или Лоренцевой метрикой для пространства-времени Минковского. Дуальный базис определяется базисом векторов (единичных). Явный вид дуального базиса и его метрики не обязателен. По умолчанию все вычисления проводятся в общем виде без использования явных выражений для ifri и ifg.

При iframe_flag равном true, во многих случаях для опускания и подъема индексов вместо стандартной метрики imetric используется метрика тетрады ifg.

ВАЖНО: Присвоение iframe_flag значения true не отменяет свойства свертки обычной метрики, определенные ранее командами defcon или imetric. Если используется тетрадный формализм, то определение стандартной метрики лучше всего ввести с помощью присвоения соответствующего имени переменной imetric. Команду imetric лучше НЕ использовать.

Maxima использует поле дуального базиса (ifri) и метрический тензор ifg для определения структурных коэффициентов базиса (ifc1 и ifc2), которые в дальнейшем используются для вычисления коэффициентов связности (icc1 и icc2), как показано в следующем примере:

(%i1) load("itensor");
(%o1)      /share/tensor/itensor.lisp
(%i2) iframe_flag:true;
(%o2)                                true
(%i3) ishow(covdiff(v([],[i]),j))$
                               i        i     %1
(%t3)                         v   + icc2     v
                               ,j       %1 j
(%i4) ishow(ev(%,icc2))$
                        %1      i           i        i
(%t4)                  v   (ifc2     + ichr2    ) + v
                                %1 j        %1 j     ,j
(%i5) ishow(ev(%,ifc2))$
            %1    i %2
           v   ifg     (ifb        - ifb        + ifb       )
                           j %2 %1      %2 %1 j      %1 j %2     i
(%t5)      -------------------------------------------------- + v
                                   2                             ,j
(%i6) ishow(ifb([a,b,c]))$
                       %5    %4
(%t6)               ifr   ifr   (ifri        - ifri       )
                       a     b       c %4,%5       c %5,%4

Когда переменной iframe_bracket_form присвоено false, то используется альтернативный метод для вычисления коммутатора тетрады (ifb).

(%i8) block([iframe_bracket_form:false],ishow(ifb([a,b,c])))$
                       %7    %6        %6      %7
(%t8)              (ifr   ifr     - ifr     ifr  ) ifri
                       a     b,%7      a,%7    b       c %6

Функция: iframes ()

Поскольку в данной версии Maxima свойства свертки для ifr и ifri, а также (ifb) определены всегда, то данная функция не выполняет никаких действий.

Переменная: ifb

Скобка тетрады (коммутатор). Вклад метрического тензора тетрады в коэффициенты связности выражается через коммутатор тетрады.

          - ifb      + ifb      + ifb
               c a b      b c a      a b c
ifc1    = --------------------------------
    abc                  2

Сам по себе коммутатор вычисляется через компоненты тетрады и метрический тензор тетрады. В зависимости от значения frame_bracket_form вычисление скобки тетрады дает разный результат. При frame_bracket_form равном true получим:

          d      e                                      f
ifb =  ifr    ifr   (ifri      - ifri      - ifri    itr   )
   abc    b      c       a d,e       a e,d       a f    d e


А при itorsion_flag равном true:

             e      d        d      e
ifb    = (ifr    ifr    - ifr    ifr   ) ifri
   abc       b      c,e      b,e    c        a d

Переменная: icc1

Коэффициенты связности первого рода. В itensor, определяется как:

icc1    = ichr1    - ikt1    - inmc1
    abc        abc       abc        abc

В этом выражении, если iframe_flag равно true, символы Кристоффеля ichr1 заменяются коэффициентами связности тетрады ifc1. Если itorsion_flag равно false, то ikt1 опускается. ikt1 опускается и в случае если используется базис тетрады, так как кручение уже вычислено, как часть скобки тетрады. Наконец, если inonmet_flag равен false, то inmc1, также опускается при вычислениях.

Переменная: icc2

Коэффициенты связности второго рода. В itensor, определяются как,

    c         c        c         c
icc2   = ichr2   - ikt2   - inmc2
    ab        ab       ab        ab

В этом выражении, если iframe_flag равно true, символы Кристоффеля ichr2 заменяются коэффициентами связности тетрады ifc2. Если itorsion_flag равно false, то ikt2 опускается. ikt2 опускается и в случае, если используется базис тетрады, так как кручение уже вычислено, как часть скобки тетрады. Наконец, если inonmet_flag равен false, то inmc2, также опускается при вычислениях.

Переменная: ifc1

Структурные коэффициенты 1-го рода, известные, также, как коэффициенты вращения Риччи. Этот тензор выражает вклад метрики тетрады в коэффициенты связности 1-го рода. Определяется как:

          - ifb      + ifb      + ifb
               c a b      b c a      a b c
ifc1    = --------------------------------
    abc                   2


Переменная: ifc2

Структурные коэффициенты 2-го рода. Получаются сверткой структурных коэффициентов 1-го рода и метрики тетрады:

    c       cd
ifc2   = ifg   ifc1
    ab             abd

Переменная: ifr

Базис тетрады. Произведение с дуальным базисом (ifri) дает метрику тетрады.

Переменная: ifri

Дуальный базис тетрады. Определяется набором векторов. Вместе с тензором тетрадной метрики ifg образует основу тетрадного формализма реализованного в itensor.

Переменная: ifg

Тензор тетрадной метрики. По умолчанию равен kdelta. Пользователь может определить свой, используя components.

Переменная: ifgi

Обратная тетрадная метрика. Свертка с ifg дает kdelta.

Управляющая переменная: iframe_bracket_form

Значение по умолчанию: true

Определяет метод вычисления скобки тетрады ifb.

25.2.6 Кручение и неметричность

Maxima умеет учитывать кручение и неметричность. Вклад кручения в коэффициенты связности вычисляется, если itorsion_flag равен true. Аналогично, компоненты неметричности будут учтены, если inonmet_flag равен true.

Переменная: inm

Вектор неметричности. Конформная неметричность определяется через ковариантную производную метрического тензора, которая в обычном случае равна нулю. Если inonmet_flag равен true, то вычисление ковариантной производной метрики дает:

g     =- g  inm
 ij;k     ij   k

Переменная: inmc1

Ковариантная перестановка компонент вектора неметричности. Определяется путем:

           g   inm  - inm  g   - g   inm
            ab    c      a  bc    ac    b
inmc1    = ------------------------------
     abc                 2

В тетрадном формализме вместо g используется ifg.

Переменная: inmc2

Контравариантная перестановка компонент вектора неметричности. Применяется когда inonmet_flag равен true. Определяется путем:

                      c         c         cd
          -inm  kdelta  - kdelta  inm  + g   inm  g
     c        a       b         a    b          d  ab
inmc2   = -------------------------------------------
     ab                        2

В тетрадном формализме вместо g используется ifg.

Переменная: ikt1

Ковариантная перестановка тензора кручения. Вычисляется посредством:

                  d           d       d
          -g   itr  - g    itr   - itr   g
            ad    cb    bd    ca      ab  cd
ikt1    = ----------------------------------
    abc                   2

В тетрадном формализме вместо g используется ifg.

Переменная: ikt2

Контравариантная перестановка тензора кручения. Вычисляется посредством:

    c     cd
ikt2   = g   ikt1
    ab           abd

В тетрадном формализме вместо g используется ifg.

Переменная: itr

Тензор кручения. Для метрики с кручением индексы ковариантной производной не коммутируют. Пример:

(%i1) load("itensor");
(%o1)      /share/tensor/itensor.lisp
(%i2) imetric:g;
(%o2)                                  g
(%i3) covdiff( covdiff( f( [], []), i), j)
                      - covdiff( covdiff( f( [], []), j), i)$
(%i4) ishow(%)$
                                   %4              %2
(%t4)                    f    ichr2    - f    ichr2
                          ,%4      j i    ,%2      i j
(%i5) canform(%);
(%o5)                                  0
(%i6) itorsion_flag:true;
(%o6)                                true
(%i7) covdiff( covdiff( f( [], []), i), j)
                      - covdiff( covdiff( f( [], []), j), i)$
(%i8) ishow(%)$
                           %8             %6
(%t8)             f    icc2    - f    icc2    - f     + f
                   ,%8     j i    ,%6     i j    ,j i    ,i j
(%i9) ishow(canform(%))$
                                   %1             %1
(%t9)                     f    icc2    - f    icc2
                           ,%1     j i    ,%1     i j
(%i10) ishow(canform(ev(%,icc2)))$
                                   %1             %1
(%t10)                    f    ikt2    - f    ikt2
                           ,%1     i j    ,%1     j i
(%i11) ishow(canform(ev(%,ikt2)))$
                      %2 %1                    %2 %1
(%t11)          f    g      ikt1       - f    g      ikt1
                 ,%2            i j %1    ,%2            j i %1
(%i12) ishow(factor(canform(rename(expand(ev(%,ikt1))))))$
                           %3 %2            %1       %1
                     f    g      g      (itr    - itr   )
                      ,%3         %2 %1     j i      i j
(%t12)               ------------------------------------
                                      2
(%i13) decsym(itr,2,1,[anti(all)],[]);
(%o13)                               done
(%i14) defcon(g,g,kdelta);
(%o14)                               done
(%i15) subst(g,nounify(g),%th(3))$
(%i16) ishow(canform(contract(%)))$
                                           %1
(%t16)                           - f    itr
                                    ,%1    i j

25.2.7 Внешняя алгебра

В itensor реализованы возможности для операций с полностью антисимметричными ковариантными тензорными объектами (внешние формы). Полностью антисимметричное тензорное поле ранга (0,L) соответствует внешней (дифференциальной) L-форме. Грассманова алгебра L-форм включает операции внешнего (косого) произведения.

Операция внешнего произведения не имеет общепринятого определения. Некоторые авторы определяют внешнее произведение способом, который соответствует операции антисимметризации. Например,

            a a  - a a
             i j    j i
 a  /\ a  = -----------
  i     j        2

В более общем случае, внешнее произведение p-формы и q-формы можно определить путем:

                       1     k1..kp l1..lq
A       /\ B       = ------ D              A       B
 i1..ip     j1..jq   (p+q)!  i1..ip j1..jq  k1..kp  l1..lq

где D обозначает дельта-символ Кронекера.

Другие авторы предпочитают "геометрическое" определение, соответствующее понятию элемента объема:

a  /\ a  = a a  - a a
 i     j    i j    j i

В более общем случае имеем:

                       1    k1..kp l1..lq
A       /\ B       = ----- D              A       B
 i1..ip     j1..jq   p! q!  i1..ip j1..jq  k1..kp  l1..lq

С алгебраической точки зрения первое определение выглядит более естественным для itensor. С другой стороны, во многих приложения более принято следовать "геометрическому" определению. У пользователя есть выбор – какое из двух определений использовать. При igeowedge_flag равном false (по умолчанию), используется антисимметризация. В противном случае применяется "геометрическое" определение.

Оператор: ~

Обозначает операцию внешнего произведения. Это бинарная операция. В качестве аргументов можно использовать выражения, включающие скаляры, ковариантные тензоры 1-го ранга или антисимметричные ковариантные тензоры ранга l (предварительно объявленные, как антисимметричные по всем ковариантным индексам).

Результат внешнего произведения контролируется флагом igeowedge_flag. Например:

(%i1) load("itensor");
(%o1)      /share/tensor/itensor.lisp
(%i2) ishow(a([i])~b([j]))$
                                 a  b  - b  a
                                  i  j    i  j
(%t2)                            -------------
                                       2
(%i3) decsym(a,2,0,[anti(all)],[]);
(%o3)                                done
(%i4) ishow(a([i,j])~b([k]))$
                          a    b  + b  a    - a    b
                           i j  k    i  j k    i k  j
(%t4)                     ---------------------------
                                       3
(%i5) igeowedge_flag:true;
(%o5)                                true
(%i6) ishow(a([i])~b([j]))$
(%t6)                            a  b  - b  a
                                  i  j    i  j
(%i7) ishow(a([i,j])~b([k]))$
(%t7)                     a    b  + b  a    - a    b
                           i j  k    i  j k    i k  j
Оператор: |

Бинарная операция, обозначающая "внутреннее" произведение – свертку с контравариантным вектором. При этой операции результат не зависит от векторных индексов, участвующих в свертке. Поэтому вектор можно задать только именем.

В пакете itensor, "внутренняя" свертка с вектором всегда выполняется по первому (в отношении алфавитного порядка) индексу. Это позволяет проводить более эффективные упрощения выражений, включающих "внутренние" свертки. Например:

(%i1) load("itensor");
(%o1)      /share/tensor/itensor.lisp
(%i2) decsym(a,2,0,[anti(all)],[]);
(%o2)                                done
(%i3) ishow(a([i,j],[])|v)$
                                    %1
(%t3)                              v   a
                                        %1 j
(%i4) ishow(a([j,i],[])|v)$
                                     %1
(%t4)                             - v   a
                                         %1 j

Заметим, что "внутренняя" свертка определена только для полностью антисимметричных объектов. В противном случае результат вычисления будет неправильным.

Функция: extdiff (expr, ind)

Внешнее дифференцирование expr по индексу ind. В itensor оператор внешней производной определен как внешнее произведение оператора производной и формы. Таким образом, результат вычисления, также зависит от значения флага igeowedge_flag. Например:

(%i1) load("itensor");
(%o1)      /share/tensor/itensor.lisp
(%i2) ishow(extdiff(v([i]),j))$
                                  v    - v
                                   j,i    i,j
(%t2)                             -----------
                                       2
(%i3) decsym(a,2,0,[anti(all)],[]);
(%o3)                                done
(%i4) ishow(extdiff(a([i,j]),k))$
                           a      - a      + a
                            j k,i    i k,j    i j,k
(%t4)                      ------------------------
                                      3
(%i5) igeowedge_flag:true;
(%o5)                                true
(%i6) ishow(extdiff(v([i]),j))$
(%t6)                             v    - v
                                   j,i    i,j
(%i7) ishow(extdiff(a([i,j]),k))$
(%t7)                      a      - a      + a
                            j k,i    i k,j    i j,k
Функция: hodge (expr)

Вычисляет форму дуальную expr. Например:

(%i1) load("itensor");
(%o1)      /share/tensor/itensor.lisp
(%i2) imetric(g);
(%o2)                            done
(%i3) idim(4);
(%o3)                            done
(%i4) icounter:100;
(%o4)                             100
(%i5) decsym(A,3,0,[anti(all)],[])$

(%i6) ishow(A([i,j,k],[]))$
(%t6)                           A
                                 i j k
(%i7) ishow(canform(hodge(%)))$
                          %1 %2 %3 %4
               levi_civita            g        A
                                       %1 %102  %2 %3 %4
(%t7)          -----------------------------------------
                                   6
(%i8) ishow(canform(hodge(%)))$
                 %1 %2 %3 %8            %4 %5 %6 %7
(%t8) levi_civita            levi_civita            g       
                                                     %1 %106
                             g        g        g      A         /6
                              %2 %107  %3 %108  %4 %8  %5 %6 %7
(%i9) lc2kdt(%)$

(%i10) %,kdelta$

(%i11) ishow(canform(contract(expand(%))))$
(%t11)                     - A
                              %106 %107 %108

Переменная: igeowedge_flag

Значение по умолчанию: false

Контролирует результат вычисления внешнего произведения или внешней производной. При igeowedge_flag равном false (по умолчанию), понятие внешней (дифференциальной) формы соответствует полностью антисимметричному ковариантному тензорному полю. В противном случае внешняя форма будет согласована с понятием элемента объема.

25.2.8 Экспорт в TeX

В itensor имеется некоторая поддержка экспорта тензорных выражений в формат TeX. Поскольку на базовом уровне Maxima тензорные выражения представлены как вызов некоторых функций, то вызов команды, tex() не даст желаемого результата. Для экспорта тензорных выражений в TeX можно использовать команду tentex.

Функция: tentex (expr)

Команда экспорта тензорных выражений в TeX. Перед использованием необходимо загрузить необходимый подпакет, load("tentex"). Например:

(%i1) load("itensor");
(%o1)      /share/tensor/itensor.lisp
(%i2) load("tentex");
(%o2)       /share/tensor/tentex.lisp
(%i3) idummyx:m;
(%o3)                                  m
(%i4) ishow(icurvature([j,k,l],[i]))$
            m1       i           m1       i           i
(%t4)  ichr2    ichr2     - ichr2    ichr2     - ichr2
            j k      m1 l        j l      m1 k        j l,k

                                                      i
                                               + ichr2
                                                      j k,l
(%i5) tentex(%)$
$$\Gamma_{j\,k}^{m_1}\,\Gamma_{l\,m_1}^{i}-\Gamma_{j\,l}^{m_1}\,
 \Gamma_{k\,m_1}^{i}-\Gamma_{j\,l,k}^{i}+\Gamma_{j\,k,l}^{i}$$

Заметим, что данном примере idummyx равен m, для того чтобы избежать символов % в TeX-овских выражениях.

ЗАМЕЧАНИЕ: Текущая версия tentex является экспериментальной.

25.2.9 Взаимодействие с пакетом ctensor

В пакет itensor заложены возможности для генерации кода Maxima для компонент тензорных выражений для последующего использования в ctensor. Эта задача выполняется вызовом команды ic_convert().

Функция: ic_convert (eqn)

Конвертирует тензорное выражение eqn из формата itensor в компоненты для использования в ctensor. При этом суммирование по немым индексам выполняется в явном виде, используя соответствующие замены индексных объектов в массивы; индексы производной заменяются не вычисляемую форму diff; символы Кристоффеля ichr1 и ichr2 заменяются на lcs и mcs, соответственно и если флаг metricconvert равен true, тогда ковариантные (контравариантные) выражения для метрического тензора везде заменяется на lg (или ug). Кроме того, для суммирования по всем немым индексам вводится do. Полученное выражение можно вычислить (загрузив предварительно пакет ctensor), используя ev. Пример:

(%i1) load("itensor");
(%o1)      /share/tensor/itensor.lisp
(%i2) eqn:ishow(t([i,j],[k])=f([],[])*g([l,m],[])*a([],[m],j)
      *b([i],[l,k]))$
                             k        m   l k
(%t2)                       t    = f a   b    g
                             i j      ,j  i    l m
(%i3) ic_convert(eqn);
(%o3) for i thru dim do (for j thru dim do (
       for k thru dim do
        t        : f sum(sum(diff(a , ct_coords ) b
         i, j, k                   m           j   i, l, k

 g    , l, 1, dim), m, 1, dim)))
  l, m
(%i4) imetric(g);
(%o4)                                done
(%i5) metricconvert:true;
(%o5)                                true
(%i6) ic_convert(eqn);
(%o6) for i thru dim do (for j thru dim do (
       for k thru dim do
        t        : f sum(sum(diff(a , ct_coords ) b
         i, j, k                   m           j   i, l, k

 lg    , l, 1, dim), m, 1, dim)))
   l, m

25.2.10 Зарезервированные имена переменных

Следующие имена переменных зарезервированы для использования в пакете itensor. Следует избегать их переопределения.

  Имя        Комментарий
  ------------------------------------------
  indices2() Внутренняя версия indices()
  conti      Список контравариантных индексов
  covi       Список ковариантных индексов
  deri       Список индексов производной
  name       Возвращает имя индексного объекта
  concan
  irpmon
  lc0
  _lc2kdt0
  _lcprod
  _extlc

25.2.11 Замечания разработчика

Я (Viktor Toth) добавил поддержку тетрадного формализма, кручения и неметричности в itensor в ноябре, 2004. Эти возможности были реконструированы на основе описаний данных в руководстве коммерческой версии Macsyma, а также с использованием результатов исполнения демонстрационных файлов Macsyma.

Данная функциональность должна рассматриваться как экспериментальная. Следует учесть, что доступная документация Macsyma содержала несколько очевидных ошибок, например, неправильные комбинации индексов. Кроме того, результаты демонстрационных расчетов показали, что функциональность тетрадного формализма в Macsyma далеко не полна. Моей цель состоит не в том, чтобы механически воспроизвести все возможности Macsyma, включая ошибки, а в том, чтобы в итоге получить математически корректную поддержку данных видов вычислений в itensor. Выполнение этой задачи займет некоторое время.


Next: , Previous: Пакет itensor, Up: Top   [Contents][Index]

26 Пакет ctensor


Next: , Previous: Пакет ctensor, Up: Пакет ctensor   [Contents][Index]

26.1 Введение в пакет ctensor

Пакет ctensor предназначен для операций с компонентами тензоров. Для загрузки ctensor необходимо ввести команду load("ctensor"). Стандартная интерактивная сессия в ctensor начинается с команды csetup(). После этого пользователь запрашивается о размерности многообразия. Если размерность равна 2, 3 или 4, тогда список координат по умолчанию устанавливается равным [x,y], [x,y,z] или [x,y,z,t] соответственно. Имена координат могут быть изменены присваиванием нового списка координат переменной ct_coords (см. ниже), пользователь также запрашивается о необходимости переопределения списка координат. Следует внимательно выбирать имена координат таким образом, чтобы избежать конфликтов с другими объектами.

После этого пользователь задает метрику непосредственно, либо указывая файл в котром она находится. Файл share/tensor/metrics.mac содержит определения некоторых стандартных метрик. Метрика хранится в матрице lg. Обратная метрика вычисляется и помещается в матрицу ug. При определении метрики существует возможность использования степенных рядов.

Ниже приведено начало протокола определения статической, сферически-симметричной метрики (стандартные координаты) с целью вычисления вакуумных уравнений Эйнштейна, приводящих к решению Шварцшильда. Многие функции пакета ctensor будут продемонстрированы на примере этой метрики.

(%i1) load("ctensor");
(%o1)      /usr/local/lib/maxima/share/tensor/ctensor.mac
(%i2) csetup();
Enter the dimension of the coordinate system:
4;
Do you wish to change the coordinate names?
n;
Do you want to
1. Enter a new metric?

2. Enter a metric from a file?

3. Approximate a metric with a Taylor series?
1;

Is the matrix  1. Diagonal  2. Symmetric  3. Antisymmetric  4. General
Answer 1, 2, 3 or 4
1;
Row 1 Column 1:
a;
Row 2 Column 2:
x^2;
Row 3 Column 3:
x^2*sin(y)^2;
Row 4 Column 4:
-d;

Matrix entered.
Enter functional dependencies with the DEPENDS function or 'N' if none
depends([a,d],x);
Do you wish to see the metric?
y;
                          [ a  0       0        0  ]
                          [                        ]
                          [     2                  ]
                          [ 0  x       0        0  ]
                          [                        ]
                          [         2    2         ]
                          [ 0  0   x  sin (y)   0  ]
                          [                        ]
                          [ 0  0       0       - d ]
(%o2)                                done
(%i3) christof(mcs);
                                            a
                                             x
(%t3)                          mcs        = ---
                                  1, 1, 1   2 a

                                             1
(%t4)                           mcs        = -
                                   1, 2, 2   x

                                             1
(%t5)                           mcs        = -
                                   1, 3, 3   x

                                            d
                                             x
(%t6)                          mcs        = ---
                                  1, 4, 4   2 d

                                              x
(%t7)                          mcs        = - -
                                  2, 2, 1     a

                                           cos(y)
(%t8)                         mcs        = ------
                                 2, 3, 3   sin(y)

                                               2
                                          x sin (y)
(%t9)                      mcs        = - ---------
                              3, 3, 1         a

(%t10)                   mcs        = - cos(y) sin(y)
                            3, 3, 2

                                            d
                                             x
(%t11)                         mcs        = ---
                                  4, 4, 1   2 a
(%o11)                               done


Previous: Введение в пакет ctensor, Up: Пакет ctensor   [Contents][Index]

26.2 Функции и переменные пакета ctensor

26.2.1 Начальные установки

Функция: csetup ()

Эта функция производит начальные установки пакета ctensor и позволяет пользователю ввести метрику интерактивно. См. ctensor для более подробного описания.

Функция: cmetric (dis)
Функция: cmetric ()

Функция пакета ctensor, которая вычисляет обратную метрику и готовит пакет к проведению дальнейших вычислений.

Если переключатель cframe_flag равен false, то функция вычисляет обратную метрику ug исходя из заданной пользователем матрицы lg. Определитель метрики тоже вычисляется и сохраняется в переменной gdet. Боле того, программа определяет является ли метрика диагональной и соответственным образом устанавливает значение ключа diagmetric. Если задан необязательный ключ dis и его значение не равно false, то в ходе сессии пользователь запрашивается требуется ли распечатать компоненты обратной метрики на экран.

Если ключ cframe_flag равен true, тогда ожидается, что заданы значения fri (матрица обратного базиса) и массив lfg (метрика относительно данного базиса). Исходя из этих данных вычисляются матрица fr и обратная метрика ufg относительно заданного базиса.

Функция: ct_coordsys (coordinate_system, extra_arg)
Функция: ct_coordsys (coordinate_system)

Задает одну из предопределенных координатных систем и метрик. Аргумент coordinate_system может принимать одно из следующих значений:

 Символ               Dim Координаты        Описание/комментарии
 ------------------------------------------------------------------
 cartesian2d           2  [x,y]             Декартовы 2D координаты
 polar                 2  [r,phi]           Полярные координаты
 elliptic              2  [u,v]             Эллиптические 
                                            координаты
 confocalelliptic      2  [u,v]             Конфокальные 
                                            эллиптические
 bipolar               2  [u,v]             Биполярные координаты
 parabolic             2  [u,v]             Параболические 
                                            координаты
 cartesian3d           3  [x,y,z]           Декартова 3D система 
                                            координат
 polarcylindrical      3  [r,theta,z]       Цилиндрические 
                                            координаты
 ellipticcylindrical   3  [u,v,z]           Эллиптические 2D 
                                            с цилинром z
 confocalellipsoidal   3  [u,v,w]           Конфокальные 
                                            эллипсоидальные
 bipolarcylindrical    3  [u,v,z]           Биполярные 2D 
                                            с цилиндром z
 paraboliccylindrical  3  [u,v,z]           Параболические 2D 
                                            с цилиндром z
 paraboloidal          3  [u,v,phi]         Параболоидные 
                                            координаты
 conical               3  [u,v,w]           Конические координаты
 toroidal              3  [u,v,phi]         Тороидальные координаты
 spherical             3  [r,theta,phi]     Сферические координаты
 oblatespheroidal      3  [u,v,phi]         Сжатые сфероидальные
 oblatespheroidalsqrt  3  [u,v,phi]
 prolatespheroidal     3  [u,v,phi]         Вытянутые сфероидальные
 prolatespheroidalsqrt 3  [u,v,phi]
 ellipsoidal           3  [r,theta,phi]     Эллипсоидальные 
                                            координаты
 cartesian4d           4  [x,y,z,t]         Декартовы 4D координаты
 spherical4d           4  [r,theta,eta,phi] Сферические 4D 
                                            координаты
 exteriorschwarzschild 4  [t,r,theta,phi]   Метрика Шварцшильда
 interiorschwarzschild 4  [t,z,u,v]         Внутреняя метрика 
                                            Шрарцшильда
 kerr_newman           4  [t,r,theta,phi]   Метрика Керра-Ньюмана

coordinate_system может быть списком функций преобразования, за которым следует список координат. Например, можно задать метрику следующим образом:

(%i1) load("ctensor");
(%o1)       /share/tensor/ctensor.mac
(%i2) ct_coordsys([r*cos(theta)*cos(phi),r*cos(theta)*sin(phi),
      r*sin(theta),[r,theta,phi]]);
(%o2)                                done
(%i3) lg:trigsimp(lg);
                           [ 1  0         0        ]
                           [                       ]
                           [     2                 ]
(%o3)                      [ 0  r         0        ]
                           [                       ]
                           [         2    2        ]
                           [ 0  0   r  cos (theta) ]
(%i4) ct_coords;
(%o4)                           [r, theta, phi]
(%i5) dim;
(%o5)                                  3

Функции преобразования могут также использоваться и в случае, когда cframe_flag равно true:

(%i1) load("ctensor");
(%o1)       /share/tensor/ctensor.mac
(%i2) cframe_flag:true;
(%o2)                                true
(%i3) ct_coordsys([r*cos(theta)*cos(phi),r*cos(theta)*sin(phi),
      r*sin(theta),[r,theta,phi]]);
(%o3)                                done
(%i4) fri;
(%o4)
 [cos(phi)cos(theta) -cos(phi) r sin(theta) -sin(phi) r cos(theta)]
 [                                                                ]
 [sin(phi)cos(theta) -sin(phi) r sin(theta)  cos(phi) r cos(theta)]
 [                                                                ]
 [    sin(theta)           r cos(theta)                0          ]

(%i5) cmetric();
(%o5)                                false
(%i6) lg:trigsimp(lg);
                           [ 1  0         0        ]
                           [                       ]
                           [     2                 ]
(%o6)                      [ 0  r         0        ]
                           [                       ]
                           [         2    2        ]
                           [ 0  0   r  cos (theta) ]

Необязательный аргумент extra_arg может принимать одно из следующих значений:

cylindrical указывает ct_coordsys добавить одну дополнительную цилиндрическую координату.

minkowski указывает ct_coordsys добавить дополнительную декартову координату с отрицательной сигнатурой.

all указывает ct_coordsys, что после определения метрики необходимо вызвать cmetric и christof(false).

Если глобальная переменная verbose равна true, то ct_coordsys выводит значения dim, ct_coords, и или lg или lfg и fri, в зависимости от значения cframe_flag.

Функция: init_ctensor ()

Инициализирует пакет ctensor.

Функция init_ctensor ре-инициализирует пакет ctensor, при этом из памяти удаляются все использованные ранее пакетом ctensor массивы и матрицы и восстанавливаются стандартные значения всех ключей, в том числе: размерность многообразия, dim, устанавливается равной 4, а метрика устанавливается равной метрике Лоренца.

26.2.2 Тензоры искривленного пространства

Основное назначение пакета ctensor – вычисление различных тензоров для искривленного пространства-времени, в основном тензоров, использующихся в общей теории относительности.

При использовании голономного (координатного) базиса ctensor может вычислить следующие объекты:

 lg  -- ug
   \      \
    lcs -- mcs -- ric -- uric
              \      \       \
               \      tracer - ein -- lein
                \
                 riem -- lriem -- weyl
                     \
                      uriem


ctensor может также работать при неголономном базисе (тетрадный формализм). Когда cframe_flag равно true, следующие объекты могут быть вычислены:

 lfg -- ufg
     \
 fri -- fr -- lcs -- mcs -- lriem -- ric -- uric
      \                       |  \      \       \
       lg -- ug               |   weyl   tracer - ein -- lein
                              |\
                              | riem
                              |
                              \uriem

Функция: christof (dis)

Функция пакета ctensor, вычисляющая символы Кристоффеля первого и второго родов. Аргумент dis определяет какой результат должен быть отображен. Символы Кристоффеля первого и второго рода хранятся в массивах lcs[i,j,k] и mcs[i,j,k] соответственно и считается симметричным по первой паре индексов. Если аргумент christof есть lcs или mcs то будут выведены все уникальные (симметрия) ненулевые значения lcs[i,j,k] или mcs[i,j,k], соответственно. Если аргумент равен all, тогда печатаются уникальные ненулевые значения как lcs[i,j,k] и mcs[i,j,k]. Если аргумент равен false, то ни какие значения не отображаются. Массив mcs[i,j,k] определен таким образом, что последний индекс является контравариантным.

Функция: ricci (dis)

Функция пакета ctensor, вычисляющая ковариантные (симметричные) компоненты тензора Риччи ric[i,j]. Если аргумент dis равен true, то на экран выводится печать результатов вычисления ненулевых компонент тензора.

Функция: uricci (dis)

Эта функция сначала вычисляет ковариантные компоненты тензора Риччи ric[i,j]. Затем с помощью контравариантной метрики вычисляется тензор Риччи со смешанными компонентами. Если аргумент dis равен true, тогда смешанные компоненты uric[i,j] (индекс i ковариантный, а индекс j контравариантный), будут распечатаны. При ricci(false) просто вычисляется массив uric[i,j] без печати на экран.

Функция: scurvature ()

Возвращает значение скалярной кривизны, получаемое сверткой тензора кривизны Риччи.

Функция: einstein (dis)

Функция einstein вычисляет смешанный тензор Эйнштейна после того как вычислены символы Кристоффеля и тензор Риччи пи помощи функций christof и ricci. Если аргумент dis равен true, тогда ненулевые компоненты тензора Эйнштейна ein[i,j] будут напечатаны, где индекс j является ковариантным. Переключатель rateinstein вызывает рациональное упрощение результирующих компонент. Если ratfac равен true тогда компоненты будут автоматически факторизованы.

Функция: leinstein (dis)

Вычисляет ковариантный тензор Эйнштейна. leinstein записывает компоненты ковариантного тензора Эйнштейна в массив lein. Контравариантные компоненты тензора Эйнштейна вычисляются исходя из смешанного тензора Эйнштейна ein. Если аргумент dis равен true, тогда ненулевые компоненты ковариантного тензора Эйнштейна распечатываются на экране.

Функция: riemann (dis)

Функция riemann вычисляет тензор кривизны Римана используя метрику и символы Кристоффеля. При этом используются следующие соглашения:

                l      _l       _l       _l   _m    _l   _m
 R[i,j,k,l] =  R    = |      - |      + |    |   - |    |
                ijk     ij,k     ik,j     mk   ij    mj   ik

Эти обозначения совместимы с используемыми в пакете itensor и его функцией icurvature. Если необязательный аргумент dis равен true, тогда ненулевые компоненты тензора riem[i,j,k,l] печатаются на экране. Как и для тензора Эйнштейна, управление процессом упрощения компонент тензора Римана осуществляется при помощи различные переключателей(флагов). Если ratriemann равен true, тогда будет применено рациональное упрощение. Если ratfac равен true, тогда каждая компонента факторизуется.

Если cframe_flag равен false, тогда тензор Римана вычисляется непосредственно исходя из символов Кристоффеля. Если cframe_flag равен true, тогда сначала вычисляется ковариантный тензор Римана исходя из компонент неголономного базиса.

Функция: lriemann (dis)

Ковариантный тензор Римана (lriem[]). Функция вычисляет ковариантный тензор Римана и заносит результаты в массив lriem. Если флаг dis равен true, то результаты вычислений уникальных ненулевых компонент тензора выводятся на экран.

Если флаг cframe_flag равен true, то ковариантный тензор Римана вычисляется напрямую по компонентам тетрады, если иначе, то вначале вычисляется тензор Римана ранга (3,1).

Информация о порядке следования индексов подробнее освящена в пункте riemann.

Функция: uriemann (dis)

Вычисляет контравариантные компоненты тензора Римана и заносит их в матрицу uriem[i,j,k,l]. Результаты вычислений печатаются на экране если флаг dis равен true.

Функция: rinvariant ()

Вычисляет инвариант Кречмана (Kretchmann) (kinvariant), используя свертку тензоров. Например,

lriem[i,j,k,l]*uriem[i,j,k,l].

Поскольку выражение может быть громоздким, то по умолчанию отключено автоматическое упрощение результата вычисления инварианта.

Функция: weyl (dis)

Вычисляет конформный тензор Вейля. Если флаг dis равен true - на экране печатаются не нулевые компоненты weyl[i,j,k,l], если иначе, то результаты вычислений просто заносятся в матрицу. Если ключ ratweyl равен true, тогда производится автоматическое упрощение результата с использованием алгебры рациональных чисел; при ratfac равном true результат вычислений автоматически факторизуется.

26.2.3 Разложение в ряды Тейлора

В пакете ctensor реализованы возможности упрощения результатов вычислений если метрика апроксимирована рядом Тейлора. Для учета метрики такого типа необходимо установить ключ ctayswitch равным true. Данный ключ заставляет использовать при пакетных вычислениях функцию ctaylor для упрощения результатов.

Функция ctaylor вызывается в следующих пакетных функциях ctensor:

    Функция      Комментарий
    ---------------------------------
    christof()   Только для mcs
    ricci()
    uricci()
    einstein()
    riemann()
    weyl()
    checkdiv()

Функция: ctaylor ()

Функция ctaylor преобразует выражения заданных аргументов конвертируя их в Тейлоровские ряды, используя функцию taylor, и затем вызывая ratdisrep. Это приводит к отбрасыванию слагаемых высокого порядка по переменной разложения ctayvar. Порядок отбрасываемых членов определен переменной ctaypov; центральная точка окрестности разложения определяется переменной ctaypt.

В качестве примера рассмотрим простую метрику , полученную в результате возмущений метрики Минковского. Если не наложить ограничений, то даже диагональная метрика в этом случае приводит к достаточно громоздким выражениям тензора Эйнштейна:

(%i1) load("ctensor");
(%o1)       /share/tensor/ctensor.mac
(%i2) ratfac:true;
(%o2)                                true
(%i3) derivabbrev:true;
(%o3)                                true
(%i4) ct_coords:[t,r,theta,phi];
(%o4)                         [t, r, theta, phi]
(%i5) lg:matrix([-1,0,0,0],[0,1,0,0],[0,0,r^2,0],
                [0,0,0,r^2*sin(theta)^2]);
                        [ - 1  0  0         0        ]
                        [                            ]
                        [  0   1  0         0        ]
                        [                            ]
(%o5)                   [          2                 ]
                        [  0   0  r         0        ]
                        [                            ]
                        [              2    2        ]
                        [  0   0  0   r  sin (theta) ]
(%i6) h:matrix([h11,0,0,0],[0,h22,0,0],[0,0,h33,0],[0,0,0,h44]);
                            [ h11   0    0    0  ]
                            [                    ]
                            [  0   h22   0    0  ]
(%o6)                       [                    ]
                            [  0    0   h33   0  ]
                            [                    ]
                            [  0    0    0   h44 ]
(%i7) depends(l,r);
(%o7)                               [l(r)]
(%i8) lg:lg+l*h;
      [ h11 l - 1      0          0                 0            ]
      [                                                          ]
      [     0      h22 l + 1      0                 0            ]
      [                                                          ]
(%o8) [                        2                                 ]
      [     0          0      r  + h33 l            0            ]
      [                                                          ]
      [                                    2    2                ]
      [     0          0          0       r  sin (theta) + h44 l ]
(%i9) cmetric(false);
(%o9)                                done
(%i10) einstein(false);
(%o10)                               done
(%i11) ntermst(ein);
[[1, 1], 62]
[[1, 2], 0]
[[1, 3], 0]
[[1, 4], 0]
[[2, 1], 0]
[[2, 2], 24]
[[2, 3], 0]
[[2, 4], 0]
[[3, 1], 0]
[[3, 2], 0]
[[3, 3], 46]
[[3, 4], 0]
[[4, 1], 0]
[[4, 2], 0]
[[4, 3], 0]
[[4, 4], 46]
(%o12)                               done

Однако если считать что l мало и оставить только линейные члены по l, тогда получим намного более простое выражение для тензора Эйнштейна:

(%i14) ctayswitch:true;
(%o14)                               true
(%i15) ctayvar:l;
(%o15)                                 l
(%i16) ctaypov:1;
(%o16)                                 1
(%i17) ctaypt:0;
(%o17)                                 0
(%i18) christof(false);
(%o18)                               done
(%i19) ricci(false);
(%o19)                               done
(%i20) einstein(false);
(%o20)                               done
(%i21) ntermst(ein);
[[1, 1], 6]
[[1, 2], 0]
[[1, 3], 0]
[[1, 4], 0]
[[2, 1], 0]
[[2, 2], 13]
[[2, 3], 2]
[[2, 4], 0]
[[3, 1], 0]
[[3, 2], 2]
[[3, 3], 9]
[[3, 4], 0]
[[4, 1], 0]
[[4, 2], 0]
[[4, 3], 0]
[[4, 4], 9]
(%o21)                               done
(%i22) ratsimp(ein[1,1]);
                         2      2  4               2     2
(%o22) - (((h11 h22 - h11 ) (l )  r  - 2 h33 l    r ) sin (theta)
                              r               r r

                            2               2      4    2
              - 2 h44 l    r  - h33 h44 (l ) )/(4 r  sin (theta))
                       r r                r

Данное приближение полезно в пределе слабого поля, вдали от гравитационных источников.

26.2.4 Неголономный базис

Если ключ cframe_flag равен true, то пакетные вычисления выполняются с использованием тетрадного (неголономного в общем случае) базиса.

Функция: frame_bracket (fr, fri, diagframe)

Скобка тетрады (fb[]).

Вычисляет скобку тетрады, следуя определению:

   c          c         c        d     e
ifb   = ( ifri    - ifri    ) ifr   ifr
   ab         d,e       e,d      a     b

26.2.5 Алгебраическая классификация

Новой особенностью пакета ctensor (начиная с ноября 2004) является возможность вычисления классификации Петрова 4-мерного пространственно-временного многообразия. Демонстрационные вычисления по данной теме представлены в файле share/tensor/petrov.dem.

Функция: nptetrad ()

Вычисляет световую тетраду (np) Ньюмана-Пенроуза и связанную с ней дуальную часть (npi), см. petrov для примера.

Световая тетрада конструируется с использованием 4-х мерного ортонормального базиса метрики, обладающей сигнатурой (-,+,+,+). Компоненты световой тетрады связаны с обратной матрицей метрики следующими соотношениями:

np  = (fri  + fri ) / sqrt(2)
  1       1      2

np  = (fri  - fri ) / sqrt(2)
  2       1      2

np  = (fri  + %i fri ) / sqrt(2)
  3       3         4

np  = (fri  - %i fri ) / sqrt(2)
  4       3         4

Функция: psi (dis)

Вычисляет пять коэффициентов Ньюмана-Пенроуза psi[0]...psi[4]. Если psi равен true, эти коэффициенты печатаются на экране, см пример в пункте petrov.

Коэффициенты вычисляются в координатном базисе из тензора Вейля. Если при использовании тетрадного базиса, компоненты тензора Вейля предварительно конвертируются в координатный базис. Эта процедура не оптимальна с вычислительной точки зрения и поэтому перед вычислением тензора Вейля предварительно рекомендуется задать координатный базис. Заметим однако, что вычисления световой тетрады (np) Ньюмана-Пенроуза требует задания тетрадного базиса. Таким образом, имеющая смысл схема вычислений в этом случае может состоять из следующих этапов: вначале задается базис тетрады, который затем используется для вычисления метрики lg (вычисляется автоматически при вызове cmetric) и обратной метрики ug; на этом этапе можно переключится обратно к координатному базису установив ключ cframe_flag равным false перед началом вычислений символов Кристоффеля. Переход обратно к тетрадному базису на более поздних стадиях вычислений может привести к несогласованным результатам, поскольку в выражении перемешиваются результаты вычислений компонент тензоров выполненных в различных базисах.

Функция: petrov ()

Вычисляет классификацию Петрова для данной метрики, определяя psi[0]...psi[4].

Например, нижеследующее показывает, как получить классификацию Петрова для метрики Керра:

(%i1) load("ctensor");
(%o1)       /share/tensor/ctensor.mac
(%i2) (cframe_flag:true,gcd:spmod,ctrgsimp:true,ratfac:true);
(%o2)                                true
(%i3) ct_coordsys(exteriorschwarzschild,all);
(%o3)                                done
(%i4) ug:invert(lg)$
(%i5) weyl(false);
(%o5)                                done
(%i6) nptetrad(true);
(%t6) np =

[ sqrt(r - 2 m)           sqrt(r)                                 ]
[---------------   ---------------------    0            0        ]
[sqrt(2) sqrt(r)   sqrt(2) sqrt(r - 2 m)                          ]
[                                                                 ]
[ sqrt(r - 2 m)            sqrt(r)                                ]
[---------------  - ---------------------   0            0        ]
[sqrt(2) sqrt(r)    sqrt(2) sqrt(r - 2 m)                         ]
[                                                                 ]
[                                          r      %i r sin(theta) ]
[       0                    0          -------   --------------- ]
[                                       sqrt(2)       sqrt(2)     ]
[                                                                 ]
[                                          r       %i r sin(theta)]
[       0                    0          -------  - ---------------]
[                                       sqrt(2)        sqrt(2)    ]

                             sqrt(r)         sqrt(r - 2 m)
(%t7) npi = matrix([- ---------------------,---------------, 0, 0],
                      sqrt(2) sqrt(r - 2 m) sqrt(2) sqrt(r)

          sqrt(r)            sqrt(r - 2 m)
[- ---------------------, - ---------------, 0, 0],
   sqrt(2) sqrt(r - 2 m)    sqrt(2) sqrt(r)

           1               %i
[0, 0, ---------, --------------------],
       sqrt(2) r  sqrt(2) r sin(theta)

           1                 %i
[0, 0, ---------, - --------------------])
       sqrt(2) r    sqrt(2) r sin(theta)

(%o7)                                done
(%i7) psi(true);
(%t8)                              psi  = 0
                                      0

(%t9)                              psi  = 0
                                      1

                                          m
(%t10)                             psi  = --
                                      2    3
                                          r

(%t11)                             psi  = 0
                                      3

(%t12)                             psi  = 0
                                      4
(%o12)                               done
(%i12) petrov();
(%o12)                                 D

Вычисление классификации Петрова основано на алгоритме опубликованном в монографии "Classifying geometries in general relativity: III Classification in practice" by Pollney, Skea, and d’Inverno, Class. Quant. Grav. 17 2885-2902 (2000). В текущем виде (по состоянию на 19 декабря 2004) код программы протестирован только для некоторых простых случаев и может содержать ошибки.

26.2.6 Кручение и неметричность

В пакете ctensor реализованы учета неметричности и кручения в коэффициентах связности.

Коэффициенты кручения вычисляются при помощи определенного пользователем тензора кручения ранга (2,1) tr. Используя его, коэффициенты кручения, kt, вычисляются по формулам:

              m          m      m
       - g  tr   - g   tr   - tr   g
          im  kj    jm   ki     ij  km
kt   = -------------------------------
  ijk                 2


  k     km
kt   = g   kt
  ij         ijm

Заметим, что массив kt содержит только смешанные компоненты.

Коэффициенты неметричности вычисляются из предварительно определенного пользователем вектора неметричности nm по следующим формулам:

             k    k        km
       -nm  D  - D  nm  + g   nm  g
   k      i  j    i   j         m  ij
nmc  = ------------------------------
   ij                2

где D обозначает дельта-символ Кронекера.

Если ключ ctorsion_flag равен true, то коэффициенты kt выделяются из смешанных компонент связности вычисляемых функцией christof и запоминаются в массиве mcs. Аналогичным образом Maxima поступает, если флаг cnonmet_flag равен true, в этом случае из смешанных компонент связности выделяется массив nmc.

Если необходимо, функция christof вызывает функции contortion nonmetricity для вычисления массивов kt nm.

Функция: contortion (tr)

Вычисляет коэффициенты кручения ранга (2,1) из тензора кручения tr.

Функция: nonmetricity (nmс)

Вычисляет коэффициенты неметричности ранга (2,1) из вектора неметричности nm.

26.2.7 Вспомогательные средства

Функция: ctransform (M)

Функция, выполняющая координатное преобразование произвольной симметричной матрицы M. Пользователь интерактивно запрашивается системой о функциях осуществляющих преобразование (прошлое название transform).

Функция: findde (A, n)

возвращает список дифференциальных уравнений, соответствующих элементам n -ой квадратной матрицы A. В текущем виде n может быть 2 или 3. deindex - список (определенный глобально) содержащий индексы матрицы A соответствующие этим дифференциальным уравнениям. Для тензора Эйнштейна (ein), представленного в форме двухмерного массива вычисленного по метрике данной ниже, функция findde дает следующую систему уравнений:

(%i1) load("ctensor");
(%o1)       /share/tensor/ctensor.mac
(%i2) derivabbrev:true;
(%o2)                                true
(%i3) dim:4;
(%o3)                                  4
(%i4) lg:matrix([a, 0, 0, 0], [ 0, x^2, 0, 0],
                              [0, 0, x^2*sin(y)^2, 0], [0,0,0,-d]);
                          [ a  0       0        0  ]
                          [                        ]
                          [     2                  ]
                          [ 0  x       0        0  ]
(%o4)                     [                        ]
                          [         2    2         ]
                          [ 0  0   x  sin (y)   0  ]
                          [                        ]
                          [ 0  0       0       - d ]
(%i5) depends([a,d],x);
(%o5)                            [a(x), d(x)]
(%i6) ct_coords:[x,y,z,t];
(%o6)                            [x, y, z, t]
(%i7) cmetric();
(%o7)                                done
(%i8) einstein(false);
(%o8)                                done
(%i9) findde(ein,2);
                                            2
(%o9) [d  x - a d + d, 2 a d d    x - a (d )  x - a  d d  x
        x                     x x         x        x    x

                                              2          2
                          + 2 a d d   - 2 a  d , a  x + a  - a]
                                   x       x      x
(%i10) deindex;
(%o10)                     [[1, 1], [2, 2], [4, 4]]

Функция: cograd ()

Вычисляет ковариантный градиент скалярной функции. Пользователь может задать имя полученному вектору, согласно процедуре проиллюстрированной ниже в пункте contragrad.

Функция: contragrad ()

Вычисляет контравариантный градиент скалярной функции. Пользователь может задать имя полученному вектору, следуя примеру (вычисления используют метрику Шварцшильда):

(%i1) load("ctensor");
(%o1)       /share/tensor/ctensor.mac
(%i2) derivabbrev:true;
(%o2)                                true
(%i3) ct_coordsys(exteriorschwarzschild,all);
(%o3)                                done
(%i4) depends(f,r);
(%o4)                               [f(r)]
(%i5) cograd(f,g1);
(%o5)                                done
(%i6) listarray(g1);
(%o6)                            [0, f , 0, 0]
                                      r
(%i7) contragrad(f,g2);
(%o7)                                done
(%i8) listarray(g2);
                               f  r - 2 f  m
                                r        r
(%o8)                      [0, -------------, 0, 0]
                                     r

Функция: dscalar ()

вычисляет даламбертиан скалярной функции, (зависимость от переменных должна быть определена заранее), например:

(%i1) load("ctensor");
(%o1)       /share/tensor/ctensor.mac
(%i2) derivabbrev:true;
(%o2)                                true
(%i3) ct_coordsys(exteriorschwarzschild,all);
(%o3)                                done
(%i4) depends(p,r);
(%o4)                               [p(r)]
(%i5) factor(dscalar(p));
                          2
                    p    r  - 2 m p    r + 2 p  r - 2 m p
                     r r           r r        r          r
(%o5)               --------------------------------------
                                       2
                                      r
Функция: checkdiv ()

вычисляет ковариантную дивергенцию смешанного тензора второго ранга (первый индекс должен быть ковариантным). На печать выводится n-соответствующих компонент полученного векторного поля, где n = dim. Если аргументом функции является g (метрический тензор), тогда для упрощения результата используется равенство нулю ковариантной дивергенции тензора Эйнштейна. Результат вычислений (вектор) запоминается в массиве с именем div.

Функция: cgeodesic (dis)

Функция пакета ctensor вычисляющая уравнения геодезических для заданной метрики. Результат запоминается в массиве geod[i]. Если аргумент dis равен true, тогда на экране печатается результат вычислений.

Функция: bdvac (f)

генерирует ковариантные компоненты вакуумных уравнений поля теории Бранса-Дикке. Скалярное поле определено аргументом f, который задается в виде взятого в кавычки имени функции вместе со своими функциональными аргументами, например, bdvac('p(x)). Результат вычислений (компоненты поля ковариантного тензора 2-го ранга) запоминается в bd.

Функция: invariant1 ()

генерирует полевые уравнения Эйлера-Лагранжа для инвариантной плотности R^2. Результат запоминается в массиве inv1.

Функция: invariant2 ()

*** ПОКА НЕ РЕАЛИЗОВАНО *** генерирует смешанные полевые уравнения Эйлера-Лагранжа для инвариантной плотности ric[i,j]*uriem[i,j]. Результат запоминается в массиве inv2.

Функция: bimetric ()

*** ПОКА НЕ РЕАЛИЗОВАНО *** генерирует полевые уравнения биметрической теории Розена. Результат запоминается в массиве rosen.

26.2.8 Утилиты

Функция: diagmatrixp (M)

Возвращает true если M - диагональная матрица (2-х мерный массив).

Функция: symmetricp (M)

Возвращает true если M - симметричная матрица (2-х мерный массив).

Функция: ntermst (f)

Дает пользователю возможность оценить размеры массива компонент тензора f. В результате печатается список двух элементов, где первый элемент является списком индексов компоненты тензора, а второй элемент соответствует количеству слагаемых этой компоненты. Таким способом можно быстро выявить ненулевые компоненты и оценить стратегию упрощения тензора.

Функция: cdisplay (ten)

показывает все элементы тензора ten, в виде многомерного массива. Тензора ранга 0 и 1, также как и другие типы переменных показываются стандартной функцией Maxima - ldisplay. Тензоры ранга 2 печатаются в виде двухмерной матрицы, тензоры более высокого порядка выводятся на экран как список 2-мерных матриц. Например в следующем примере на экран выводится результаты вычисления тензора Римана для метрики Шварцшильда:

(%i1) load("ctensor");
(%o1)       /share/tensor/ctensor.mac
(%i2) ratfac:true;
(%o2)                                true
(%i3) ct_coordsys(exteriorschwarzschild,all);
(%o3)                                done
(%i4) riemann(false);
(%o4)                                done
(%i5) cdisplay(riem);
          [ 0               0                   0           0     ]
          [                                                       ]
          [                              2                        ]
          [      3 m (r - 2 m)   m    2 m                         ]
          [ 0  - ------------- + -- - ----      0           0     ]
          [            4          3     4                         ]
          [           r          r     r                          ]
          [                                                       ]
riem    = [                                m (r - 2 m)            ]
    1, 1  [ 0               0              -----------      0     ]
          [                                     4                 ]
          [                                    r                  ]
          [                                                       ]
          [                                           m (r - 2 m) ]
          [ 0               0                   0     ----------- ]
          [                                                4      ]
          [                                               r       ]

                                [    2 m (r - 2 m)       ]
                                [ 0  -------------  0  0 ]
                                [          4             ]
                                [         r              ]
                     riem     = [                        ]
                         1, 2   [ 0        0        0  0 ]
                                [                        ]
                                [ 0        0        0  0 ]
                                [                        ]
                                [ 0        0        0  0 ]

                                [         m (r - 2 m)    ]
                                [ 0  0  - -----------  0 ]
                                [              4         ]
                                [             r          ]
                     riem     = [                        ]
                         1, 3   [ 0  0        0        0 ]
                                [                        ]
                                [ 0  0        0        0 ]
                                [                        ]
                                [ 0  0        0        0 ]

                                [            m (r - 2 m) ]
                                [ 0  0  0  - ----------- ]
                                [                 4      ]
                                [                r       ]
                     riem     = [                        ]
                         1, 4   [ 0  0  0        0       ]
                                [                        ]
                                [ 0  0  0        0       ]
                                [                        ]
                                [ 0  0  0        0       ]

                               [       0         0  0  0 ]
                               [                         ]
                               [       2 m               ]
                               [ - ------------  0  0  0 ]
                    riem     = [    2                    ]
                        2, 1   [   r  (r - 2 m)          ]
                               [                         ]
                               [       0         0  0  0 ]
                               [                         ]
                               [       0         0  0  0 ]

             [     2 m                                         ]
             [ ------------  0        0               0        ]
             [  2                                              ]
             [ r  (r - 2 m)                                    ]
             [                                                 ]
             [      0        0        0               0        ]
             [                                                 ]
  riem     = [                         m                       ]
      2, 2   [      0        0  - ------------        0        ]
             [                     2                           ]
             [                    r  (r - 2 m)                 ]
             [                                                 ]
             [                                         m       ]
             [      0        0        0         - ------------ ]
             [                                     2           ]
             [                                    r  (r - 2 m) ]

                                [ 0  0       0        0 ]
                                [                       ]
                                [            m          ]
                                [ 0  0  ------------  0 ]
                     riem     = [        2              ]
                         2, 3   [       r  (r - 2 m)    ]
                                [                       ]
                                [ 0  0       0        0 ]
                                [                       ]
                                [ 0  0       0        0 ]

                                [ 0  0  0       0       ]
                                [                       ]
                                [               m       ]
                                [ 0  0  0  ------------ ]
                     riem     = [           2           ]
                         2, 4   [          r  (r - 2 m) ]
                                [                       ]
                                [ 0  0  0       0       ]
                                [                       ]
                                [ 0  0  0       0       ]

                                      [ 0  0  0  0 ]
                                      [            ]
                                      [ 0  0  0  0 ]
                                      [            ]
                           riem     = [ m          ]
                               3, 1   [ -  0  0  0 ]
                                      [ r          ]
                                      [            ]
                                      [ 0  0  0  0 ]

                                      [ 0  0  0  0 ]
                                      [            ]
                                      [ 0  0  0  0 ]
                                      [            ]
                           riem     = [    m       ]
                               3, 2   [ 0  -  0  0 ]
                                      [    r       ]
                                      [            ]
                                      [ 0  0  0  0 ]

                               [   m                      ]
                               [ - -   0   0       0      ]
                               [   r                      ]
                               [                          ]
                               [        m                 ]
                               [  0   - -  0       0      ]
                    riem     = [        r                 ]
                        3, 3   [                          ]
                               [  0    0   0       0      ]
                               [                          ]
                               [              2 m - r     ]
                               [  0    0   0  ------- + 1 ]
                               [                 r        ]

                                    [ 0  0  0    0   ]
                                    [                ]
                                    [ 0  0  0    0   ]
                                    [                ]
                         riem     = [            2 m ]
                             3, 4   [ 0  0  0  - --- ]
                                    [             r  ]
                                    [                ]
                                    [ 0  0  0    0   ]

                                [       0        0  0  0 ]
                                [                        ]
                                [       0        0  0  0 ]
                                [                        ]
                     riem     = [       0        0  0  0 ]
                         4, 1   [                        ]
                                [      2                 ]
                                [ m sin (theta)          ]
                                [ -------------  0  0  0 ]
                                [       r                ]

                                [ 0        0        0  0 ]
                                [                        ]
                                [ 0        0        0  0 ]
                                [                        ]
                     riem     = [ 0        0        0  0 ]
                         4, 2   [                        ]
                                [         2              ]
                                [    m sin (theta)       ]
                                [ 0  -------------  0  0 ]
                                [          r             ]

                              [ 0  0          0          0 ]
                              [                            ]
                              [ 0  0          0          0 ]
                              [                            ]
                   riem     = [ 0  0          0          0 ]
                       4, 3   [                            ]
                              [                2           ]
                              [         2 m sin (theta)    ]
                              [ 0  0  - ---------------  0 ]
                              [                r           ]

           [        2                                             ]
           [   m sin (theta)                                      ]
           [ - -------------         0                0         0 ]
           [         r                                            ]
           [                                                      ]
           [                         2                            ]
           [                    m sin (theta)                     ]
riem     = [        0         - -------------         0         0 ]
    4, 4   [                          r                           ]
           [                                                      ]
           [                                          2           ]
           [                                   2 m sin (theta)    ]
           [        0                0         ---------------  0 ]
           [                                          r           ]
           [                                                      ]
           [        0                0                0         0 ]

(%o5)                                done

Функция: deleten (L, n)

Возвращает новый список состоящий из элементов списка L с удаленным n-ым элементом.

26.2.9 Переменные пакета ctensor

Управляющая переменная: dim

Значение по умолчанию: 4

Опция пакета ctensor (компонентные вычисления). Размерность многообразия, по умолчанию: 4 Команда dim: n переопределяет размерность величине равной n.

Управляющая переменная: diagmetric

Значение по умолчанию: false

Опция пакета ctensor (компонентные вычисления). Если diagmetric равен true, тогда вычисления всех геометрических объектов проводятся по упрощенной схеме: с учетом диагональности метрики. Это позволяет уменьшить время счета. Данная опция устанавливается автоматически если при вызове csetup была задана диагональная метрика.

Управляющая переменная: ctrgsimp

Включает использование тригонометрических преобразований при упрощении тензора. В настоящее время, ctrgsimp влияет только на результаты вычислений, выполненные в тетрадном базисе.

Управляющая переменная: cframe_flag

Если ключ cframe_flag равен true, тогда вычисления проводятся в тетрадном базисе (в общем случае с не голономной метрикой). Базис определяется массивом дуального фрейма fri и метрикой базиса lfg. При вычислениях в декартовой тетраде массив, lfg должен быть единичной матрицей соответствующего размера; при вычислениях с Лоренцевой тетрадой, массив lfg должен иметь соответствующую сигнатуру.

Управляющая переменная: ctorsion_flag

Если ctorsion_flag равен true, тогда при вычислении связности учитываются коэффициенты кручения contortion. В свою очередь, коэффициенты кручения, contortion, вычисляются из заданного пользователем тензора кручения tr.

Управляющая переменная: cnonmet_flag

Если cnonmet_flag равен true, тогда при вычислении связности учитывается неметричность nonmetricity, которая, сама по себе, вычисляется из заданного пользователем вектора неметричности nm.

Управляющая переменная: ctayswitch

Если ключ равен true, то при вычислениях используются ряды Тейлора. В текущем состоянии пакета, эти ряды влияют на вычисление следующих тензоров: christof, ricci, uricci, einstein, и weyl.

Управляющая переменная: ctayvar

Переменная ряда Тейлора. Она активируется при ctayswitch равном true.

Управляющая переменная: ctaypov

Максимальная ряда Тэйлора. Ее определение влияет на вычисления только если ctayswitch равен true.

Управляющая переменная: ctaypt

Центральная точка ряда Тэйлора. Ее определение влияет на вычисления только если ctayswitch равен true.

Системная переменная: gdet

Детерминант метрического тензора lg. Вычисляется функцией cmetric, когда флаг cframe_flag равен false.

Управляющая переменная: ratchristof

Включает рациональное упрощение коэффициентов связности christof.

Управляющая переменная: rateinstein

Значение по умолчанию: true

Если равен true тогда проводится рациональное упрощение компонент тензора Эйнштейна; если ratfac равен true, тогда компоненты тензора автоматически факторизуются.

Управляющая переменная: ratriemann

Значение по умолчанию: true

Один из ключей, контролирующих упрощение тензора Римана; Если равен true тогда применяется рациональное упрощение; если ratfac равен true, тогда компоненты тензора автоматически факторизуются.

Управляющая переменная: ratweyl

Значение по умолчанию: true

Если равен true тогда применяется рациональное упрощение тензора Вейля; если ratfac равен true, тогда компоненты тензора автоматически факторизуются.

Переменная: lfg

Имя ковариантной метрики тетрады. По умолчанию совпадает с Лоренцевой метрикой, имеет сигнатуру (+,+,+,-). Используется когда cframe_flag равен true.

Переменная: ufg

Имя контравариантной метрики тетрады. Вычисляется из lfg, если вызывается функция cmetric и флаг cframe_flag равен true.

Переменная: riem

Тензор Римана ранга (3,1). Вычисляется вызовом функции riemann. Для информации о порядке следования индексов см. описание riemann.

Если cframe_flag равен true, riem вычисляется по ковариантным компонентам тензора Римана lriem.

Переменная: lriem

Ковариантная версия тензора Римана. Вычисляется вызовом функции lriemann.

Переменная: uriem

Контравариантная версия тензора Римана. Вычисляется вызовом функции uriemann.

Переменная: ric

Смешанный тензор Риччи. Вычисляется функцией ricci.

Переменная: uric

Контравариантный тензор Риччи. Вычисляется функцией uricci.

Переменная: lg

Метрический тензор. Данный тензор должен (наравне с переменной dim) определен до начала других вычислений.

Переменная: ug

Обратный метрический тензор. Вычисляется функцией cmetric.

Переменная: weyl

Тензор Вейля. Вычисляется функцией weyl.

Переменная: fb

Коммутатор (скобка) тетрады, вычисляется функцией frame_bracket.

Переменная: kinvariant

Инвариант Кретчмана. Вычисляется функцией rinvariant.

Переменная: np

Нуль-тетрада Ньюмана-Пенроуза. Вычисляется функцией nptetrad.

Переменная: npi

Нуль-тетрада Ньюмана-Пенроуза с поднятыми индексами; вычисляется процедурой nptetrad. Определена посредством ug.np. Произведение np.transpose(npi) является константой:

(%i39) trigsimp(np.transpose(npi));
                              [  0   - 1  0  0 ]
                              [                ]
                              [ - 1   0   0  0 ]
(%o39)                        [                ]
                              [  0    0   0  1 ]
                              [                ]
                              [  0    0   1  0 ]
Переменная: tr

Определенный пользователем тензор 3-го ранга, задающий кручение. Используется процедурой contortion.

Переменная: kt

Вклад кручения в коэффициенты связности, вычисляется из тензора кручения tr функцией contortion.

Переменная: nm

Определенный пользователем вектор неметричности. Используется функцией nonmetricity.

Переменная: nmc

Вклад неметричности в связность; вычисляется из nm функцией nonmetricity.

Системная переменная: tensorkill

Переменная показывающая, что пакет ctensor инициализирован. Эти установки используются процедурой csetup, и переопределяются процедурой init_ctensor.

Управляющая переменная: ct_coords

Значение по умолчанию: []

Опция пакета ctensor (компонентные вычисления тензоров). ct_coords содержит список имен координат. Обычно он определяется при вызове процедуры csetup. Список может быть переопределен назначением нового списка ct_coords: [j1, j2, ..., jn], j’s имена новых координат. Смотри также csetup.

26.2.10 Зарезервированные имена

Следующие имена используются функциями и процедурами пакета ctensor (не следует их переопределять):

  Наименование Описание
  ----------------------------------------------------------------
  _lg()        Присваивается массиву lfg если используется 
               тетрадная метрика; по умолчанию присваивается  
               массиву lg
  _ug()        Присваивается массиву ufg если используется 
               тетрадная метрика; по умолчанию присваивается 
               массиву ug
  cleanup()    Удаляет элементы drom списка deindex 
  contract4()  используется функцией psi()
  filemet()    используется функцией csetup() при чтении метрики 
               из файла
  findde1()    используется функцией findde()
  findde2()    используется функцией findde()
  findde3()    используется функцией findde()
  kdelt()      дельта-символ Кронекера (необобщенный)
  newmet()     используется функцией csetup() для интерактивного
               определения метрики
  setflags()   используется функцией init_ctensor()
  readvalue()
  resimp()
  sermet()     используется функцией csetup() для ввода метрики 
               в виде разложения в ряд Тэйлора
  txyzsum()
  tmetric()    Метрика тетрады, используется функцией cmetric(), 
               если cframe_flag:true
  triemann()   Тензор Римана в тетрадном представлении, 
               используется если cframe_flag:true
  tricci()     Тензор Риччи в тетрадном представлении, 
               используется если cframe_flag:true
  trrc()       Коэффициенты вращения Риччи, используется  
               функцией christof()
  yesp()

26.2.11 Изменения

В ноябре 2004 пакет ctensor был существенно переписан. Многие функции и переменные были переименованы для того чтобы сделать данный пакет совместимым с коммерческой версией Macsyma.

  Новое имя    Статое имя      Описание
  -----------------------------------------------------------------
  ctaylor()    DLGTAYLOR()     Разложение выражения в ряд
                               Тэйлора
  lgeod[]      EM              Уравнения геодезических
  ein[]        G[]             Смешанный тензор Эйнштейна
  ric[]        LR[]            Смешанный тензор Риччи
  ricci()      LRICCICOM()     Вычисляет смешанный тензор Риччи
  ctaypov      MINP            Максимальная степень ряда Тэйлора
  cgeodesic()  MOTION          Вычисляет уравнения геодезических
  ct_coords    OMEGA           метрические координаты
  ctayvar      PARAM           Переменная ряда Тэйлора
  lriem[]      R[]             
  uriemann()   RAISERIEMANN()  Вычисляет контравариантный тензор 
                               Римана 
  ratriemann   RATRIEMAN       Рациональное упрощение тензора 
                               Римана
  uric[]       RICCI[]         Контравариантный тензор Риччи
  uricci()     RICCICOM()      Вычисляет контравариантный тензор 
                               Риччи
  cmetric()    SETMETRIC()     Определяет метрику
  ctaypt       TAYPT           Центральная точка окрестности ряда 
                               Тэйлора
  ctayswitch   TAYSWITCH       Ключ, устанавливающий использовать 
                               ли ряды Тэйлора в метрике
  csetup()     TSETUP()        Вызывает начало интерактивного 
                               режима задания метрики и пр.       
  ctransform() TTRANSFORM()    Интерактивное преобразование 
                               координат
  uriem[]      UR[]            Контравариантный тензор Римана
  weyl[]       W[]             Тензор Вейля ранга (3,1)


Next: , Previous: Пакет ctensor, Up: Top   [Contents][Index]

27 Пакет atensor


Next: , Previous: Пакет atensor, Up: Пакет atensor   [Contents][Index]

27.1 Введение в пакет atensor

Пакет atensor предназначен для вычислений с тензорными алгебрами. Для того, чтобы использовать atensor, надо ввести load("atensor"), с последующим вызовом функции init_atensor.

Основой пакета atensor является набор правил упрощения для оператора некоммутативного произведения ("." – dot product). atensor знает несколько типов алгебр и соответствующий набор правил активизируется при вызове функции init_atensor.

Возможности пакета atensor можно продемонстрировать определив алгебру кватернионов как алгебру Клиффорда Cl(0,2) с двумя базисными векторами. В этом случае три кватернионные мнимые единицы представляются двумя базисными векторами и их произведением:

    i = v     j = v     k = v  . v
         1         2         1    2

Хотя atensor имеет встроенное определение алгебры кватернионов, оно не используется в данном примере, в котором мы построим таблицу умножения кватернионов в виде матрицы:

(%i1) load("atensor");
(%o1)       /share/tensor/atensor.mac
(%i2) init_atensor(clifford,0,0,2);
(%o2)                                done
(%i3) atensimp(v[1].v[1]);
(%o3)                                 - 1
(%i4) atensimp((v[1].v[2]).(v[1].v[2]));
(%o4)                                 - 1
(%i5) q:zeromatrix(4,4);
                                [ 0  0  0  0 ]
                                [            ]
                                [ 0  0  0  0 ]
(%o5)                           [            ]
                                [ 0  0  0  0 ]
                                [            ]
                                [ 0  0  0  0 ]
(%i6) q[1,1]:1;
(%o6)                                  1
(%i7) for i thru adim do q[1,i+1]:q[i+1,1]:v[i];
(%o7)                                done
(%i8) q[1,4]:q[4,1]:v[1].v[2];
(%o8)                               v  . v
                                     1    2
(%i9) for i from 2 thru 4 do for j from 2 thru 4 do
      q[i,j]:atensimp(q[i,1].q[1,j]);
(%o9)                                done
(%i10) q;
                   [    1        v         v      v  . v  ]
                   [              1         2      1    2 ]
                   [                                      ]
                   [   v         - 1     v  . v    - v    ]
                   [    1                 1    2      2   ]
(%o10)             [                                      ]
                   [   v      - v  . v     - 1      v     ]
                   [    2        1    2              1    ]
                   [                                      ]
                   [ v  . v      v        - v       - 1   ]
                   [  1    2      2          1            ]

В качестве базисных векторов atensor использует переменные с индексом. Символ переменой хранится в asymbol а индекс может принимать значения от 1 до adim. Для переменных с индексом вычисляются билинейные формы sf, af и av. Вычисление подставляет значение aform[i,j] вместо fun(v[i],v[j]), где v есть значение asymbol и fun есть af или sf; либо подставляет v[aform[i,j]] вместо av(v[i],v[j]).

Функции sf, af и av могут быть переопределены пользователем.

Когда пакет atensor загружен, устанавливаются следующие значения переключателей:

dotscrules:true;
dotdistrib:true;
dotexptsimp:false;

Если вы хотите поэкспериментировать с неассоциативными алгебрами надо присвоить dotassoc значение false. Однако, в данном случае atensimp не всегда может получить желаемое упрощение.


Previous: Введение в пакет atensor, Up: Пакет atensor   [Contents][Index]

27.2 Функции и переменные пакета atensor

Функция: init_atensor (alg_type, opt_dims)
Функция: init_atensor (alg_type)

Инициализирует пакет atensor с указанием типа алгебры. Здесь alg_type может принимать одно из следующих значений:

universal: Универсальная алгебра без определенных правил коммутации.

grassmann: Алгебра Грассмана, определяемая коммутационным правилом u.v+v.u=0.

clifford: Алгебра Клиффорда, определяемая коммутационным правилом u.v+v.u=-2*sf(u,v), где sf есть симметричная скалярная функция. Для этой алгебры opt_dims может задавать до 3-х неотрицательных целых чисел, которые представляют собой число положительных, вырожденных и отрицательных размерностей алгебры. Если opt_dims задано, то atensor автоматически сконфигурирует значения adim и aform. В противном случае adim принимает значение 0 а aform остается неопределенным.

symmetric: Симметричная алгебра, определяемая коммутационным правилом u.v-v.u=0.

symplectic: Симплектическая алгебра, определяемая коммутационным правилом u.v-v.u=2*af(u,v), гда af есть антисимметричная скалярная функция. Для симплектической алгебры opt_dims может задавать до двух неотрицательных целых чисел, представляющих число невырожденных и вырожденных измерений соответственно. Если opt_dims задано, то atensor автоматически сконфигурирует значения adim и aform. В противном случае adim принимает значение 0 а aform остается неопределенным.

lie_envelop: Обертывающая алгебра Ли, определяемая коммутационным правилом u.v-v.u=2*av(u,v), где av есть антисимметричная функция.

init_atensor также распознает несколько предопределенных типов алгебр:

complex реализует алгебру комплексных чисел, как алгебру Клиффорда Cl(0,1). Вызов init_atensor(complex) эквивалентен init_atensor(clifford,0,0,1).

quaternion реализует алгебру кватернионов. Вызов init_atensor(quaternion) эквивалентен init_atensor(clifford,0,0,2).

pauli реализует алгебру спиноров Паули как алгебру Клиффорда Cl(3,0). Вызов init_atensor(pauli) эквивалентен init_atensor(clifford,3).

dirac реализует алгебру спиноров Дирака как алгебру Клиффорда Cl(3,1). Вызов init_atensor(dirac) эквивалентен init_atensor(clifford,3,0,1).

Функция: atensimp (expr)

Упрощает алгебраическое выражение expr в соответствии с правилами, определенными при вызове init_atensor. Упрощение сводится к рекурсивному применению коммутационных правил м вычислению, где возможно, значений sf, af и av. При этом применяются предосторожности, обеспечивающие то, что процесс упрощения завершится.

Функция: alg_type

Тип алгебры. Допустимые значения: universal, grassmann, clifford, symmetric, symplectic или lie_envelop.

Переменная: adim

Значение по умолчанию: 0

Размерность алгебры. atensor использует adim для того чтобы определить является ли индексированный объект допустимым базисным вектором. См. abasep.

Переменная: aform

Значение по умолчанию: ident(3)

Значение билинейных форм sf, af или av. Значение по умолчанию – единичная 3х3 матрица ident(3).

Переменная: asymbol

Значение по умолчанию: v

Символ, используемый для обозначения базисного вектора.

Функция: sf (u, v)

Симметричная скалярная функция, используемая в коммутационных правилах. По умолчанию с помощью abasep проверяется, что оба аргумента функции являются базисными векторами, и если это так, подставляется соответствующее значение из матрицы aform.

Функция: af (u, v)

Антисимметричная скалярная функция, используемая в коммутационных правилах. По умолчанию с помощью abasep проверяется, что оба аргумента функции являются базисными векторами, и если это так, подставляется соответствующее значение из матрицы aform.

Функция: av (u, v)

Антисимметричная скалярная функция, используемая в коммутационных правилах. По умолчанию с помощью abasep проверяется, что оба аргумента функции являются базисными векторами, и если это так, подставляется соответствующее значение из матрицы aform.

Например:

(%i1) load("atensor");
(%o1)       /share/tensor/atensor.mac
(%i2) adim:3;
(%o2)                                  3
(%i3) aform:matrix([0,3,-2],[-3,0,1],[2,-1,0]);
                               [  0    3   - 2 ]
                               [               ]
(%o3)                          [ - 3   0    1  ]
                               [               ]
                               [  2   - 1   0  ]
(%i4) asymbol:x;
(%o4)                                  x
(%i5) av(x[1],x[2]);
(%o5)                                 x
                                       3
Функция: abasep (v)

Проверяет является ли аргумент базисным вектором для atensor. Т.е. проверяет, что: это индексированная переменная, символ этой переменной совпадает с значением asymbol, индекс имеет числовое значение в пределах от 1 до adim.


Next: , Previous: Пакет atensor, Up: Top   [Contents][Index]

28 Sums, Products, and Series


Next: , Previous: Sums Products and Series, Up: Sums Products and Series   [Contents][Index]

28.1 Functions and Variables for Sums and Products

Function: bashindices (expr)

Transforms the expression expr by giving each summation and product a unique index. This gives changevar greater precision when it is working with summations or products. The form of the unique index is jnumber. The quantity number is determined by referring to gensumnum, which can be changed by the user. For example, gensumnum:0$ resets it.

Function: lsum (expr, x, L)

Represents the sum of expr for each element x in L. A noun form 'lsum is returned if the argument L does not evaluate to a list.

Examples:

(%i1) lsum (x^i, i, [1, 2, 7]);
                            7    2
(%o1)                      x  + x  + x
(%i2) lsum (i^2, i, rootsof (x^3 - 1, x));
                     ====
                     \      2
(%o2)                 >    i
                     /
                     ====
                                   3
                     i in rootsof(x  - 1, x)
Function: intosum (expr)

Moves multiplicative factors outside a summation to inside. If the index is used in the outside expression, then the function tries to find a reasonable index, the same as it does for sumcontract. This is essentially the reverse idea of the outative property of summations, but note that it does not remove this property, it only bypasses it.

In some cases, a scanmap (multthru, expr) may be necessary before the intosum.

Option variable: simpproduct

Default value: false

When simpproduct is true, the result of a product is simplified. This simplification may sometimes be able to produce a closed form. If simpproduct is false or if the quoted form 'product is used, the value is a product noun form which is a representation of the pi notation used in mathematics.

Function: product (expr, i, i_0, i_1)

Represents a product of the values of expr as the index i varies from i_0 to i_1. The noun form 'product is displayed as an uppercase letter pi.

product evaluates expr and lower and upper limits i_0 and i_1, product quotes (does not evaluate) the index i.

If the upper and lower limits differ by an integer, expr is evaluated for each value of the index i, and the result is an explicit product.

Otherwise, the range of the index is indefinite. Some rules are applied to simplify the product. When the global variable simpproduct is true, additional rules are applied. In some cases, simplification yields a result which is not a product; otherwise, the result is a noun form 'product.

See also `nouns' and evflag.

Examples:

(%i1) product (x + i*(i+1)/2, i, 1, 4);
(%o1)           (x + 1) (x + 3) (x + 6) (x + 10)
(%i2) product (i^2, i, 1, 7);
(%o2)                       25401600
(%i3) product (a[i], i, 1, 7);
(%o3)                 a  a  a  a  a  a  a
                       1  2  3  4  5  6  7
(%i4) product (a(i), i, 1, 7);
(%o4)          a(1) a(2) a(3) a(4) a(5) a(6) a(7)
(%i5) product (a(i), i, 1, n);
                             n
                           /===\
                            ! !
(%o5)                       ! !  a(i)
                            ! !
                           i = 1
(%i6) product (k, k, 1, n);
                               n
                             /===\
                              ! !
(%o6)                         ! !  k
                              ! !
                             k = 1
(%i7) product (k, k, 1, n), simpproduct;
(%o7)                          n!
(%i8) product (integrate (x^k, x, 0, 1), k, 1, n);
                             n
                           /===\
                            ! !    1
(%o8)                       ! !  -----
                            ! !  k + 1
                           k = 1
(%i9) product (if k <= 5 then a^k else b^k, k, 1, 10);
                              15  40
(%o9)                        a   b
Option variable: simpsum

Default value: false

When simpsum is true, the result of a sum is simplified. This simplification may sometimes be able to produce a closed form. If simpsum is false or if the quoted form 'sum is used, the value is a sum noun form which is a representation of the sigma notation used in mathematics.

Function: sum (expr, i, i_0, i_1)

Represents a summation of the values of expr as the index i varies from i_0 to i_1. The noun form 'sum is displayed as an uppercase letter sigma.

sum evaluates its summand expr and lower and upper limits i_0 and i_1, sum quotes (does not evaluate) the index i.

If the upper and lower limits differ by an integer, the summand expr is evaluated for each value of the summation index i, and the result is an explicit sum.

Otherwise, the range of the index is indefinite. Some rules are applied to simplify the summation. When the global variable simpsum is true, additional rules are applied. In some cases, simplification yields a result which is not a summation; otherwise, the result is a noun form 'sum.

When the evflag (evaluation flag) cauchysum is true, a product of summations is expressed as a Cauchy product, in which the index of the inner summation is a function of the index of the outer one, rather than varying independently.

The global variable genindex is the alphabetic prefix used to generate the next index of summation, when an automatically generated index is needed.

gensumnum is the numeric suffix used to generate the next index of summation, when an automatically generated index is needed. When gensumnum is false, an automatically-generated index is only genindex with no numeric suffix.

See also lsum, sumcontract, intosum, bashindices, niceindices, `nouns', evflag, and zeilberger-pkg

Examples:

(%i1) sum (i^2, i, 1, 7);
(%o1)                          140
(%i2) sum (a[i], i, 1, 7);
(%o2)           a  + a  + a  + a  + a  + a  + a
                 7    6    5    4    3    2    1
(%i3) sum (a(i), i, 1, 7);
(%o3)    a(7) + a(6) + a(5) + a(4) + a(3) + a(2) + a(1)
(%i4) sum (a(i), i, 1, n);
                            n
                           ====
                           \
(%o4)                       >    a(i)
                           /
                           ====
                           i = 1
(%i5) sum (2^i + i^2, i, 0, n);
                          n
                         ====
                         \       i    2
(%o5)                     >    (2  + i )
                         /
                         ====
                         i = 0
(%i6) sum (2^i + i^2, i, 0, n), simpsum;
                              3      2
                   n + 1   2 n  + 3 n  + n
(%o6)             2      + --------------- - 1
                                  6
(%i7) sum (1/3^i, i, 1, inf);
                            inf
                            ====
                            \     1
(%o7)                        >    --
                            /      i
                            ====  3
                            i = 1
(%i8) sum (1/3^i, i, 1, inf), simpsum;
                                1
(%o8)                           -
                                2
(%i9) sum (i^2, i, 1, 4) * sum (1/i^2, i, 1, inf);
                              inf
                              ====
                              \     1
(%o9)                      30  >    --
                              /      2
                              ====  i
                              i = 1
(%i10) sum (i^2, i, 1, 4) * sum (1/i^2, i, 1, inf), simpsum;
                                  2
(%o10)                       5 %pi
(%i11) sum (integrate (x^k, x, 0, 1), k, 1, n);
                            n
                           ====
                           \       1
(%o11)                      >    -----
                           /     k + 1
                           ====
                           k = 1
(%i12) sum (if k <= 5 then a^k else b^k, k, 1, 10);
          10    9    8    7    6    5    4    3    2
(%o12)   b   + b  + b  + b  + b  + a  + a  + a  + a  + a
Function: sumcontract (expr)

Combines all sums of an addition that have upper and lower bounds that differ by constants. The result is an expression containing one summation for each set of such summations added to all appropriate extra terms that had to be extracted to form this sum. sumcontract combines all compatible sums and uses one of the indices from one of the sums if it can, and then try to form a reasonable index if it cannot use any supplied.

It may be necessary to do an intosum (expr) before the sumcontract.

Option variable: sumexpand

Default value: false

When sumexpand is true, products of sums and exponentiated sums simplify to nested sums.

See also cauchysum.

Examples:

(%i1) sumexpand: true$
(%i2) sum (f (i), i, 0, m) * sum (g (j), j, 0, n);
                     m      n
                    ====   ====
                    \      \
(%o2)                >      >     f(i1) g(i2)
                    /      /
                    ====   ====
                    i1 = 0 i2 = 0
(%i3) sum (f (i), i, 0, m)^2;
                     m      m
                    ====   ====
                    \      \
(%o3)                >      >     f(i3) f(i4)
                    /      /
                    ====   ====
                    i3 = 0 i4 = 0

Next: , Previous: Functions and Variables for Sums and Products, Up: Sums Products and Series   [Contents][Index]

28.2 Introduction to Series

Maxima contains functions taylor and powerseries for finding the series of differentiable functions. It also has tools such as nusum capable of finding the closed form of some series. Operations such as addition and multiplication work as usual on series. This section presents the global variables which control the expansion.


Next: , Previous: Introduction to Series, Up: Sums Products and Series   [Contents][Index]

28.3 Functions and Variables for Series

Option variable: cauchysum

Default value: false

When multiplying together sums with inf as their upper limit, if sumexpand is true and cauchysum is true then the Cauchy product will be used rather than the usual product. In the Cauchy product the index of the inner summation is a function of the index of the outer one rather than varying independently.

Example:

(%i1) sumexpand: false$
(%i2) cauchysum: false$
(%i3) s: sum (f(i), i, 0, inf) * sum (g(j), j, 0, inf);
                      inf         inf
                      ====        ====
                      \           \
(%o3)                ( >    f(i))  >    g(j)
                      /           /
                      ====        ====
                      i = 0       j = 0
(%i4) sumexpand: true$
(%i5) cauchysum: true$
(%i6) expand(s,0,0);
                 inf     i1
                 ====   ====
                 \      \
(%o6)             >      >     g(i1 - i2) f(i2)
                 /      /
                 ====   ====
                 i1 = 0 i2 = 0
Function: deftaylor (f_1(x_1), expr_1, …, f_n(x_n), expr_n)

For each function f_i of one variable x_i, deftaylor defines expr_i as the Taylor series about zero. expr_i is typically a polynomial in x_i or a summation; more general expressions are accepted by deftaylor without complaint.

powerseries (f_i(x_i), x_i, 0) returns the series defined by deftaylor.

deftaylor returns a list of the functions f_1, …, f_n. deftaylor evaluates its arguments.

Example:

(%i1) deftaylor (f(x), x^2 + sum(x^i/(2^i*i!^2), i, 4, inf));
(%o1)                          [f]
(%i2) powerseries (f(x), x, 0);
                      inf
                      ====      i1
                      \        x         2
(%o2)                  >     -------- + x
                      /       i1    2
                      ====   2   i1!
                      i1 = 4
(%i3) taylor (exp (sqrt (f(x))), x, 0, 4);
                      2         3          4
                     x    3073 x    12817 x
(%o3)/T/     1 + x + -- + ------- + -------- + . . .
                     2     18432     307200
Option variable: maxtayorder

Default value: true

When maxtayorder is true, then during algebraic manipulation of (truncated) Taylor series, taylor tries to retain as many terms as are known to be correct.

Function: niceindices (expr)

Renames the indices of sums and products in expr. niceindices attempts to rename each index to the value of niceindicespref[1], unless that name appears in the summand or multiplicand, in which case niceindices tries the succeeding elements of niceindicespref in turn, until an unused variable is found. If the entire list is exhausted, additional indices are constructed by appending integers to the value of niceindicespref[1], e.g., i0, i1, i2, …

niceindices returns an expression. niceindices evaluates its argument.

Example:

(%i1) niceindicespref;
(%o1)                  [i, j, k, l, m, n]
(%i2) product (sum (f (foo + i*j*bar), foo, 1, inf), bar, 1, inf);
                 inf    inf
                /===\   ====
                 ! !    \
(%o2)            ! !     >      f(bar i j + foo)
                 ! !    /
                bar = 1 ====
                        foo = 1
(%i3) niceindices (%);
                     inf  inf
                    /===\ ====
                     ! !  \
(%o3)                ! !   >    f(i j l + k)
                     ! !  /
                    l = 1 ====
                          k = 1
Option variable: niceindicespref

Default value: [i, j, k, l, m, n]

niceindicespref is the list from which niceindices takes the names of indices for sums and products.

The elements of niceindicespref are must be names of simple variables.

Example:

(%i1) niceindicespref: [p, q, r, s, t, u]$
(%i2) product (sum (f (foo + i*j*bar), foo, 1, inf), bar, 1, inf);
                 inf    inf
                /===\   ====
                 ! !    \
(%o2)            ! !     >      f(bar i j + foo)
                 ! !    /
                bar = 1 ====
                        foo = 1
(%i3) niceindices (%);
                     inf  inf
                    /===\ ====
                     ! !  \
(%o3)                ! !   >    f(i j q + p)
                     ! !  /
                    q = 1 ====
                          p = 1
Function: nusum (expr, x, i_0, i_1)

Carries out indefinite hypergeometric summation of expr with respect to x using a decision procedure due to R.W. Gosper. expr and the result must be expressible as products of integer powers, factorials, binomials, and rational functions.

The terms "definite" and "indefinite summation" are used analogously to "definite" and "indefinite integration". To sum indefinitely means to give a symbolic result for the sum over intervals of variable length, not just e.g. 0 to inf. Thus, since there is no formula for the general partial sum of the binomial series, nusum can’t do it.

nusum and unsum know a little about sums and differences of finite products. See also unsum.

Examples:

(%i1) nusum (n*n!, n, 0, n);

Dependent equations eliminated:  (1)
(%o1)                     (n + 1)! - 1
(%i2) nusum (n^4*4^n/binomial(2*n,n), n, 0, n);
                     4        3       2              n
      2 (n + 1) (63 n  + 112 n  + 18 n  - 22 n + 3) 4      2
(%o2) ------------------------------------------------ - ------
                    693 binomial(2 n, n)                 3 11 7
(%i3) unsum (%, n);
                              4  n
                             n  4
(%o3)                   ----------------
                        binomial(2 n, n)
(%i4) unsum (prod (i^2, i, 1, n), n);
                    n - 1
                    /===\
                     ! !   2
(%o4)              ( ! !  i ) (n - 1) (n + 1)
                     ! !
                    i = 1
(%i5) nusum (%, n, 1, n);

Dependent equations eliminated:  (2 3)
                            n
                          /===\
                           ! !   2
(%o5)                      ! !  i  - 1
                           ! !
                          i = 1
Function: pade (taylor_series, numer_deg_bound, denom_deg_bound)

Returns a list of all rational functions which have the given Taylor series expansion where the sum of the degrees of the numerator and the denominator is less than or equal to the truncation level of the power series, i.e. are "best" approximants, and which additionally satisfy the specified degree bounds.

taylor_series is an univariate Taylor series. numer_deg_bound and denom_deg_bound are positive integers specifying degree bounds on the numerator and denominator.

taylor_series can also be a Laurent series, and the degree bounds can be inf which causes all rational functions whose total degree is less than or equal to the length of the power series to be returned. Total degree is defined as numer_deg_bound + denom_deg_bound. Length of a power series is defined as "truncation level" + 1 - min(0, "order of series").

(%i1) taylor (1 + x + x^2 + x^3, x, 0, 3);
                              2    3
(%o1)/T/             1 + x + x  + x  + . . .
(%i2) pade (%, 1, 1);
                                 1
(%o2)                       [- -----]
                               x - 1
(%i3) t: taylor(-(83787*x^10 - 45552*x^9 - 187296*x^8
                   + 387072*x^7 + 86016*x^6 - 1507328*x^5
                   + 1966080*x^4 + 4194304*x^3 - 25165824*x^2
                   + 67108864*x - 134217728)
       /134217728, x, 0, 10);
                    2    3       4       5       6        7
             x   3 x    x    15 x    23 x    21 x    189 x
(%o3)/T/ 1 - - + ---- - -- - ----- + ----- - ----- - ------
             2    16    32   1024    2048    32768   65536

                                  8         9          10
                            5853 x    2847 x    83787 x
                          + ------- + ------- - --------- + . . .
                            4194304   8388608   134217728
(%i4) pade (t, 4, 4);
(%o4)                          []

There is no rational function of degree 4 numerator/denominator, with this power series expansion. You must in general have degree of the numerator and degree of the denominator adding up to at least the degree of the power series, in order to have enough unknown coefficients to solve.

(%i5) pade (t, 5, 5);
                     5                4                 3
(%o5) [- (520256329 x  - 96719020632 x  - 489651410240 x

                  2
 - 1619100813312 x  - 2176885157888 x - 2386516803584)

               5                 4                  3
/(47041365435 x  + 381702613848 x  + 1360678489152 x

                  2
 + 2856700692480 x  + 3370143559680 x + 2386516803584)]
Function: powerseries (expr, x, a)

Returns the general form of the power series expansion for expr in the variable x about the point a (which may be inf for infinity):

           inf
           ====
           \               n
            >    b  (x - a)
           /      n
           ====
           n = 0

If powerseries is unable to expand expr, taylor may give the first several terms of the series.

When verbose is true, powerseries prints progress messages.

(%i1) verbose: true$
(%i2) powerseries (log(sin(x)/x), x, 0);
can't expand 
                                 log(sin(x))
so we'll try again after applying the rule:
                                        d
                                      / -- (sin(x))
                                      [ dx
                        log(sin(x)) = i ----------- dx
                                      ]   sin(x)
                                      /
in the first simplification we have returned:
                             /
                             [
                             i cot(x) dx - log(x)
                             ]
                             /
                    inf
                    ====        i1  2 i1             2 i1
                    \      (- 1)   2     bern(2 i1) x
                     >     ------------------------------
                    /                i1 (2 i1)!
                    ====
                    i1 = 1
(%o2)                -------------------------------------
                                      2
Option variable: psexpand

Default value: false

When psexpand is true, an extended rational function expression is displayed fully expanded. The switch ratexpand has the same effect.

When psexpand is false, a multivariate expression is displayed just as in the rational function package.

When psexpand is multi, then terms with the same total degree in the variables are grouped together.

Function: revert (expr, x)
Function: revert2 (expr, x, n)

These functions return the reversion of expr, a Taylor series about zero in the variable x. revert returns a polynomial of degree equal to the highest power in expr. revert2 returns a polynomial of degree n, which may be greater than, equal to, or less than the degree of expr.

load ("revert") loads these functions.

Examples:

(%i1) load ("revert")$
(%i2) t: taylor (exp(x) - 1, x, 0, 6);
                   2    3    4    5     6
                  x    x    x    x     x
(%o2)/T/      x + -- + -- + -- + --- + --- + . . .
                  2    6    24   120   720
(%i3) revert (t, x);
               6       5       4       3       2
           10 x  - 12 x  + 15 x  - 20 x  + 30 x  - 60 x
(%o3)/R/ - --------------------------------------------
                                60
(%i4) ratexpand (%);
                     6    5    4    3    2
                    x    x    x    x    x
(%o4)             - -- + -- - -- + -- - -- + x
                    6    5    4    3    2
(%i5) taylor (log(x+1), x, 0, 6);
                    2    3    4    5    6
                   x    x    x    x    x
(%o5)/T/       x - -- + -- - -- + -- - -- + . . .
                   2    3    4    5    6
(%i6) ratsimp (revert (t, x) - taylor (log(x+1), x, 0, 6));
(%o6)                           0
(%i7) revert2 (t, x, 4);
                          4    3    2
                         x    x    x
(%o7)                  - -- + -- - -- + x
                         4    3    2
Function: taylor
    taylor (expr, x, a, n)
    taylor (expr, [x_1, x_2, …], a, n)
    taylor (expr, [x, a, n, 'asymp])
    taylor (expr, [x_1, x_2, …], [a_1, a_2, …], [n_1, n_2, …])
    taylor (expr, [x_1, a_1, n_1], [x_2, a_2, n_2], …)

taylor (expr, x, a, n) expands the expression expr in a truncated Taylor or Laurent series in the variable x around the point a, containing terms through (x - a)^n.

If expr is of the form f(x)/g(x) and g(x) has no terms up to degree n then taylor attempts to expand g(x) up to degree 2 n. If there are still no nonzero terms, taylor doubles the degree of the expansion of g(x) so long as the degree of the expansion is less than or equal to n 2^taylordepth.

taylor (expr, [x_1, x_2, ...], a, n) returns a truncated power series of degree n in all variables x_1, x_2, … about the point (a, a, ...).

taylor (expr, [x_1, a_1, n_1], [x_2, a_2, n_2], ...) returns a truncated power series in the variables x_1, x_2, … about the point (a_1, a_2, ...), truncated at n_1, n_2, …

taylor (expr, [x_1, x_2, ...], [a_1, a_2, ...], [n_1, n_2, ...]) returns a truncated power series in the variables x_1, x_2, … about the point (a_1, a_2, ...), truncated at n_1, n_2, …

taylor (expr, [x, a, n, 'asymp]) returns an expansion of expr in negative powers of x - a. The highest order term is (x - a)^-n.

When maxtayorder is true, then during algebraic manipulation of (truncated) Taylor series, taylor tries to retain as many terms as are known to be correct.

When psexpand is true, an extended rational function expression is displayed fully expanded. The switch ratexpand has the same effect. When psexpand is false, a multivariate expression is displayed just as in the rational function package. When psexpand is multi, then terms with the same total degree in the variables are grouped together.

See also the taylor_logexpand switch for controlling expansion.

Examples:

(%i1) taylor (sqrt (sin(x) + a*x + 1), x, 0, 3);
                           2             2
             (a + 1) x   (a  + 2 a + 1) x
(%o1)/T/ 1 + --------- - -----------------
                 2               8

                                   3      2             3
                               (3 a  + 9 a  + 9 a - 1) x
                             + -------------------------- + . . .
                                           48
(%i2) %^2;
                                    3
                                   x
(%o2)/T/           1 + (a + 1) x - -- + . . .
                                   6
(%i3) taylor (sqrt (x + 1), x, 0, 5);
                       2    3      4      5
                  x   x    x    5 x    7 x
(%o3)/T/      1 + - - -- + -- - ---- + ---- + . . .
                  2   8    16   128    256
(%i4) %^2;
(%o4)/T/                  1 + x + . . .
(%i5) product ((1 + x^i)^2.5, i, 1, inf)/(1 + x^2);
                         inf
                        /===\
                         ! !    i     2.5
                         ! !  (x  + 1)
                         ! !
                        i = 1
(%o5)                   -----------------
                              2
                             x  + 1
(%i6) ev (taylor(%, x,  0, 3), keepfloat);
                               2           3
(%o6)/T/    1 + 2.5 x + 3.375 x  + 6.5625 x  + . . .
(%i7) taylor (1/log (x + 1), x, 0, 3);
                               2       3
                 1   1   x    x    19 x
(%o7)/T/         - + - - -- + -- - ----- + . . .
                 x   2   12   24    720
(%i8) taylor (cos(x) - sec(x), x, 0, 5);
                                4
                           2   x
(%o8)/T/                - x  - -- + . . .
                               6
(%i9) taylor ((cos(x) - sec(x))^3, x, 0, 5);
(%o9)/T/                    0 + . . .
(%i10) taylor (1/(cos(x) - sec(x))^3, x, 0, 5);
                                               2          4
            1     1       11      347    6767 x    15377 x
(%o10)/T/ - -- + ---- + ------ - ----- - ------- - --------
             6      4        2   15120   604800    7983360
            x    2 x    120 x

                                                          + . . .
(%i11) taylor (sqrt (1 - k^2*sin(x)^2), x, 0, 6);
               2  2       4      2   4
              k  x    (3 k  - 4 k ) x
(%o11)/T/ 1 - ----- - ----------------
                2            24

                                    6       4       2   6
                               (45 k  - 60 k  + 16 k ) x
                             - -------------------------- + . . .
                                          720
(%i12) taylor ((x + 1)^n, x, 0, 4);
                      2       2     3      2         3
                    (n  - n) x    (n  - 3 n  + 2 n) x
(%o12)/T/ 1 + n x + ----------- + --------------------
                         2                 6

                               4      3       2         4
                             (n  - 6 n  + 11 n  - 6 n) x
                           + ---------------------------- + . . .
                                          24
(%i13) taylor (sin (y + x), x, 0, 3, y, 0, 3);
               3                 2
              y                 y
(%o13)/T/ y - -- + . . . + (1 - -- + . . .) x
              6                 2

                    3                       2
               y   y            2      1   y            3
          + (- - + -- + . . .) x  + (- - + -- + . . .) x  + . . .
               2   12                  6   12
(%i14) taylor (sin (y + x), [x, y], 0, 3);
                     3        2      2      3
                    x  + 3 y x  + 3 y  x + y
(%o14)/T/   y + x - ------------------------- + . . .
                                6
(%i15) taylor (1/sin (y + x), x, 0, 3, y, 0, 3);
          1   y              1    1               1            2
(%o15)/T/ - + - + . . . + (- -- + - + . . .) x + (-- + . . .) x
          y   6               2   6                3
                             y                    y

                                           1            3
                                      + (- -- + . . .) x  + . . .
                                            4
                                           y
(%i16) taylor (1/sin (y + x), [x, y], 0, 3);
                             3         2       2        3
            1     x + y   7 x  + 21 y x  + 21 y  x + 7 y
(%o16)/T/ ----- + ----- + ------------------------------- + . . .
          x + y     6                   360
Option variable: taylordepth

Default value: 3

If there are still no nonzero terms, taylor doubles the degree of the expansion of g(x) so long as the degree of the expansion is less than or equal to n 2^taylordepth.

Function: taylorinfo (expr)

Returns information about the Taylor series expr. The return value is a list of lists. Each list comprises the name of a variable, the point of expansion, and the degree of the expansion.

taylorinfo returns false if expr is not a Taylor series.

Example:

(%i1) taylor ((1 - y^2)/(1 - x), x, 0, 3, [y, a, inf]);
                  2                       2
(%o1)/T/ - (y - a)  - 2 a (y - a) + (1 - a )

         2                        2
 + (1 - a  - 2 a (y - a) - (y - a) ) x

         2                        2   2
 + (1 - a  - 2 a (y - a) - (y - a) ) x

         2                        2   3
 + (1 - a  - 2 a (y - a) - (y - a) ) x  + . . .
(%i2) taylorinfo(%);
(%o2)               [[y, a, inf], [x, 0, 3]]
Function: taylorp (expr)

Returns true if expr is a Taylor series, and false otherwise.

Option variable: taylor_logexpand

Default value: true

taylor_logexpand controls expansions of logarithms in taylor series.

When taylor_logexpand is true, all logarithms are expanded fully so that zero-recognition problems involving logarithmic identities do not disturb the expansion process. However, this scheme is not always mathematically correct since it ignores branch information.

When taylor_logexpand is set to false, then the only expansion of logarithms that occur is that necessary to obtain a formal power series.

Option variable: taylor_order_coefficients

Default value: true

taylor_order_coefficients controls the ordering of coefficients in a Taylor series.

When taylor_order_coefficients is true, coefficients of taylor series are ordered canonically.

Function: taylor_simplifier (expr)

Simplifies coefficients of the power series expr. taylor calls this function.

Option variable: taylor_truncate_polynomials

Default value: true

When taylor_truncate_polynomials is true, polynomials are truncated based upon the input truncation levels.

Otherwise, polynomials input to taylor are considered to have infinite precision.

Function: taytorat (expr)

Converts expr from taylor form to canonical rational expression (CRE) form. The effect is the same as rat (ratdisrep (expr)), but faster.

Function: trunc (expr)

Annotates the internal representation of the general expression expr so that it is displayed as if its sums were truncated Taylor series. expr is not otherwise modified.

Example:

(%i1) expr: x^2 + x + 1;
                            2
(%o1)                      x  + x + 1
(%i2) trunc (expr);
                                2
(%o2)                  1 + x + x  + . . .
(%i3) is (expr = trunc (expr));
(%o3)                         true
Function: unsum (f, n)

Returns the first backward difference f(n) - f(n - 1). Thus unsum in a sense is the inverse of sum.

See also nusum.

Examples:

(%i1) g(p) := p*4^n/binomial(2*n,n);
                                     n
                                  p 4
(%o1)               g(p) := ----------------
                            binomial(2 n, n)
(%i2) g(n^4);
                              4  n
                             n  4
(%o2)                   ----------------
                        binomial(2 n, n)
(%i3) nusum (%, n, 0, n);
                     4        3       2              n
      2 (n + 1) (63 n  + 112 n  + 18 n  - 22 n + 3) 4      2
(%o3) ------------------------------------------------ - ------
                    693 binomial(2 n, n)                 3 11 7
(%i4) unsum (%, n);
                              4  n
                             n  4
(%o4)                   ----------------
                        binomial(2 n, n)
Option variable: verbose

Default value: false

When verbose is true, powerseries prints progress messages.


Next: , Previous: Functions and Variables for Series, Up: Sums Products and Series   [Contents][Index]

28.4 Introduction to Fourier series

The fourie package comprises functions for the symbolic computation of Fourier series. There are functions in the fourie package to calculate Fourier integral coefficients and some functions for manipulation of expressions.


Next: , Previous: Introduction to Fourier series, Up: Sums Products and Series   [Contents][Index]

28.5 Functions and Variables for Fourier series

Function: equalp (x, y)

Returns true if equal (x, y) otherwise false (doesn’t give an error message like equal (x, y) would do in this case).

Function: remfun
    remfun (f, expr)
    remfun (f, expr, x)

remfun (f, expr) replaces all occurrences of f (arg) by arg in expr.

remfun (f, expr, x) replaces all occurrences of f (arg) by arg in expr only if arg contains the variable x.

Function: funp
    funp (f, expr)
    funp (f, expr, x)

funp (f, expr) returns true if expr contains the function f.

funp (f, expr, x) returns true if expr contains the function f and the variable x is somewhere in the argument of one of the instances of f.

Function: absint
    absint (f, x, halfplane)
    absint (f, x)
    absint (f, x, a, b)

absint (f, x, halfplane) returns the indefinite integral of f with respect to x in the given halfplane (pos, neg, or both). f may contain expressions of the form abs (x), abs (sin (x)), abs (a) * exp (-abs (b) * abs (x)).

absint (f, x) is equivalent to absint (f, x, pos).

absint (f, x, a, b) returns the definite integral of f with respect to x from a to b. f may include absolute values.

Function: fourier (f, x, p)

Returns a list of the Fourier coefficients of f(x) defined on the interval [-p, p].

Function: foursimp (l)

Simplifies sin (n %pi) to 0 if sinnpiflag is true and cos (n %pi) to (-1)^n if cosnpiflag is true.

Option variable: sinnpiflag

Default value: true

See foursimp.

Option variable: cosnpiflag

Default value: true

See foursimp.

Function: fourexpand (l, x, p, limit)

Constructs and returns the Fourier series from the list of Fourier coefficients l up through limit terms (limit may be inf). x and p have same meaning as in fourier.

Function: fourcos (f, x, p)

Returns the Fourier cosine coefficients for f(x) defined on [0, p].

Function: foursin (f, x, p)

Returns the Fourier sine coefficients for f(x) defined on [0, p].

Function: totalfourier (f, x, p)

Returns fourexpand (foursimp (fourier (f, x, p)), x, p, 'inf).

Function: fourint (f, x)

Constructs and returns a list of the Fourier integral coefficients of f(x) defined on [minf, inf].

Function: fourintcos (f, x)

Returns the Fourier cosine integral coefficients for f(x) on [0, inf].

Function: fourintsin (f, x)

Returns the Fourier sine integral coefficients for f(x) on [0, inf].


Previous: Functions and Variables for Fourier series, Up: Sums Products and Series   [Contents][Index]

28.6 Functions and Variables for Poisson series

Function: intopois (a)

Converts a into a Poisson encoding.

Function: outofpois (a)

Converts a from Poisson encoding to general representation. If a is not in Poisson form, outofpois carries out the conversion, i.e., the return value is outofpois (intopois (a)). This function is thus a canonical simplifier for sums of powers of sine and cosine terms of a particular type.

Function: poisdiff (a, b)

Differentiates a with respect to b. b must occur only in the trig arguments or only in the coefficients.

Function: poisexpt (a, b)

Functionally identical to intopois (a^b). b must be a positive integer.

Function: poisint (a, b)

Integrates in a similarly restricted sense (to poisdiff). Non-periodic terms in b are dropped if b is in the trig arguments.

Option variable: poislim

Default value: 5

poislim determines the domain of the coefficients in the arguments of the trig functions. The initial value of 5 corresponds to the interval [-2^(5-1)+1,2^(5-1)], or [-15,16], but it can be set to [-2^(n-1)+1, 2^(n-1)].

Function: poismap (series, sinfn, cosfn)

will map the functions sinfn on the sine terms and cosfn on the cosine terms of the Poisson series given. sinfn and cosfn are functions of two arguments which are a coefficient and a trigonometric part of a term in series respectively.

Function: poisplus (a, b)

Is functionally identical to intopois (a + b).

Function: poissimp (a)

Converts a into a Poisson series for a in general representation.

Special symbol: poisson

The symbol /P/ follows the line label of Poisson series expressions.

Function: poissubst (a, b, c)

Substitutes a for b in c. c is a Poisson series.

(1) Where B is a variable u, v, w, x, y, or z, then a must be an expression linear in those variables (e.g., 6*u + 4*v).

(2) Where b is other than those variables, then a must also be free of those variables, and furthermore, free of sines or cosines.

poissubst (a, b, c, d, n) is a special type of substitution which operates on a and b as in type (1) above, but where d is a Poisson series, expands cos(d) and sin(d) to order n so as to provide the result of substituting a + d for b in c. The idea is that d is an expansion in terms of a small parameter. For example, poissubst (u, v, cos(v), %e, 3) yields cos(u)*(1 - %e^2/2) - sin(u)*(%e - %e^3/6).

Function: poistimes (a, b)

Is functionally identical to intopois (a*b).

Function: poistrim ()

is a reserved function name which (if the user has defined it) gets applied during Poisson multiplication. It is a predicate function of 6 arguments which are the coefficients of the u, v, ..., z in a term. Terms for which poistrim is true (for the coefficients of that term) are eliminated during multiplication.

Function: printpois (a)

Prints a Poisson series in a readable format. In common with outofpois, it will convert a into a Poisson encoding first, if necessary.


Next: , Previous: Sums Products and Series, Up: Top   [Contents][Index]

29 Теория чисел


Previous: Теория чисел, Up: Теория чисел   [Contents][Index]

29.1 Функции и переменные для теории чисел

Функция: bern (n)

Возвращает n-е число Бернулли для целого n. Числа Бернулли, равные нулю, опускаются, если zerobern равно false.

См. также burn.

(%i1) zerobern: true$
(%i2) map (bern, [0, 1, 2, 3, 4, 5, 6, 7, 8]);
                  1  1       1      1        1
(%o2)       [1, - -, -, 0, - --, 0, --, 0, - --]
                  2  6       30     42       30
(%i3) zerobern: false$
(%i4) map (bern, [0, 1, 2, 3, 4, 5, 6, 7, 8]);
            1  1    1   5     691   7    3617  43867
(%o4) [1, - -, -, - --, --, - ----, -, - ----, -----]
            2  6    30  66    2730  6    510    798
Функция: bernpoly (x, n)

Возвращает значение многочлена Бернулли порядка n в точке x.

Функция: bfzeta (s, n)

Возвращает дзэта-функцию Римана для аргумента s. Возвращаемое значение - число с плавающей точкой повышенной точности (bfloat); n - количество цифр в возвращаемом значении.

Функция: bfhzeta (s, h, n)

Возвращает дзэта-функцию Гурвица для аргументов s и h. Возвращаемое значение - число с плавающей точкой повышенной точности (bfloat); n - количество цифр в возвращаемом значении. Дзэта-функция Гурвица определяется как

sum ((k+h)^-s, k, 0, inf)

Функцию загружает команда load ("bffac").

Функция: binomial (x, y)

Биномиальный коэффициент x!/(y! (x - y)!).

Если x и y - целые, рассчитывается численное значение биномиального коэффициента. Если y или x - y - целое, биномиальный коэффициент выражается через многочлен.

Примеры:

(%i1) binomial (11, 7);
(%o1)                          330
(%i2) 11! / 7! / (11 - 7)!;
(%o2)                          330
(%i3) binomial (x, 7);
        (x - 6) (x - 5) (x - 4) (x - 3) (x - 2) (x - 1) x
(%o3)   -------------------------------------------------
                              5040
(%i4) binomial (x + 7, x);
      (x + 1) (x + 2) (x + 3) (x + 4) (x + 5) (x + 6) (x + 7)
(%o4) -------------------------------------------------------
                               5040
(%i5) binomial (11, y);
(%o5)                    binomial(11, y)
Функция: burn (n)

Возвращает n-е число Бернулли для целого n. burn может быть более эффективным, чем bern для отдельных больших n (возможно, если n больше 105 или в районе этого), так как bern рассчитывает все числа Бернулли до n-го перед выдачей результата.

burn использует выражение чисел Бернулли через дзэта-функцию Римана.

Функцию загружает команда load ("bffac").

Функция: cf (expr)

Преобразует expr в цепную дробь. expr - выражение, составленное из цепных дробей и квадратных корней из целых чисел. Операнды выражения могут комбинироваться арифметическими операторами. Помимо цепных дробей и квадратных корней, сомножители выражения должны быть целыми или рациональными числами. Maxima не работает с операциями над цепными дробями вне cf.

cf вычисляет аргументы после установки listarith равной false. Цепная дробь a + 1/(b + 1/(c + ...)) представляется в виде списка [a, b, c, ...].

Элементы списка a, b, c, ... должны раскрываться в целые числа. expr может содержать sqrt (n), где n - целое. В этом случае cf даст число членов цепной дроби, равное произведению cflength на период. Цепная дробь может раскрываться в число через арифметическое представление, возвращенное cfdisrep. См. также cfexpand для другого способа вычисления цепной дроби.

См. также cfdisrep, cfexpand и cflength.

Примеры:

Функция: cfdisrep (list)

Возвращает простое выражение вида a + 1/(b + 1/(c + ...)) для списочного представления цепной дроби [a, b, c, ...].

(%i1) cf ([1, 2, -3] + [1, -2, 1]);
(%o1)                     [1, 1, 1, 2]
(%i2) cfdisrep (%);
                                  1
(%o2)                     1 + ---------
                                    1
                              1 + -----
                                      1
                                  1 + -
                                      2
Функция: cfexpand (x)

Возвращает матрицу числителей и знаменателей последней (первый столбец) и предпоследней (второй столбец) подходящей дроби для цепной дроби x.

(%i1) cf (rat (ev (%pi, numer)));

`rat' replaced 3.141592653589793 by 103993/33102 =3.141592653011902
(%o1)                  [3, 7, 15, 1, 292]
(%i2) cfexpand (%); 
                         [ 103993  355 ]
(%o2)                    [             ]
                         [ 33102   113 ]
(%i3) %[1,1]/%[2,1], numer;
(%o3)                   3.141592653011902
Управляющая переменная: cflength

Значение по умолчанию: 1

Функция cf возвращает число членов цепной дроби, равное произведению cflength на период. Таким образом, по умолчанию возвращается один период.

(%i1) cflength: 1$
(%i2) cf ((1 + sqrt(5))/2);
(%o2)                    [1, 1, 1, 1, 2]
(%i3) cflength: 2$
(%i4) cf ((1 + sqrt(5))/2);
(%o4)               [1, 1, 1, 1, 1, 1, 1, 2]
(%i5) cflength: 3$
(%i6) cf ((1 + sqrt(5))/2);
(%o6)           [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2]
Функция: divsum (n, k)
Функция: divsum (n)

divsum (n, k) возвращает сумму делителей n, возведенных в степень k.

divsum (n) возвращает сумму делителей n.

(%i1) divsum (12);
(%o1)                          28
(%i2) 1 + 2 + 3 + 4 + 6 + 12;
(%o2)                          28
(%i3) divsum (12, 2);
(%o3)                          210
(%i4) 1^2 + 2^2 + 3^2 + 4^2 + 6^2 + 12^2;
(%o4)                          210
Функция: euler (n)

Возвращает n-е число Эйлера для неотрицательного целого n. Для постоянной Эйлера-Маскерони см. %gamma.

(%i1) map (euler, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
(%o1)    [1, 0, - 1, 0, 5, 0, - 61, 0, 1385, 0, - 50521]
Константа: %gamma

Постоянная Эйлера-Маскерони, 0.5772156649015329 ....

Функция: factorial (x)

Представляет факториал x. Maxima работает с factorial (x) аналогично x!. См. !.

Функция: fib (n)

Возвращает n-е число Фибоначчи. fib(0) равно 0, fib(1) равно 1, fib (-n) равно (-1)^(n + 1) * fib(n).

После вызова fib prevfib равно fib (x - 1), числу Фибоначчи, предшествующему последнему рассчитанному.

(%i1) map (fib, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
(%o1)         [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Функция: fibtophi (expr)

Выражает числа Фибоначчи в expr через постоянную %phi, равную (1 + sqrt(5))/2, приблизительно 1.61803399.

Примеры:

(%i1) fibtophi (fib (n));
                           n             n
                       %phi  - (1 - %phi)
(%o1)                  -------------------
                           2 %phi - 1
(%i2) fib (n-1) + fib (n) - fib (n+1);
(%o2)          - fib(n + 1) + fib(n) + fib(n - 1)
(%i3) fibtophi (%);
            n + 1             n + 1       n             n
        %phi      - (1 - %phi)        %phi  - (1 - %phi)
(%o3) - --------------------------- + -------------------
                2 %phi - 1                2 %phi - 1
                                          n - 1             n - 1
                                      %phi      - (1 - %phi)
                                    + ---------------------------
                                              2 %phi - 1
(%i4) ratsimp (%);
(%o4)                           0
Функция: ifactors (n)

Для целого положительного n возвращает факторизацию n. Если n=p1^e1..pk^nk есть разложение n на простые множители, ifactors возвращает [[p1, e1], ... , [pk, ek]].

Используемые методы факторизации - обычное деление на простые числа (до 9973), ро-алгоритм Полларда и метод эллиптических кривых.

(%i1) ifactors(51575319651600);
(%o1)     [[2, 4], [3, 2], [5, 2], [1583, 1], [9050207, 1]]
(%i2) apply("*", map(lambda([u], u[1]^u[2]), %));
(%o2)                        51575319651600
Функция: inrt (x, n)

Возвращает целый n-й корень абсолютного значения x.

(%i1) l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]$
(%i2) map (lambda ([a], inrt (10^a, 3)), l);
(%o2) [2, 4, 10, 21, 46, 100, 215, 464, 1000, 2154, 4641, 10000]
Функция: inv_mod (n, m)

Рассчитывает число, обратное n по модулю m. inv_mod (n,m) возвращает false, если n есть делитель нуля по модулю m.

(%i1) inv_mod(3, 41);
(%o1)                           14
(%i2) ratsimp(3^-1), modulus=41;
(%o2)                           14
(%i3) inv_mod(3, 42);
(%o3)                          false
Функция: jacobi (p, q)

Символ Якоби для p и q.

(%i1) l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]$
(%i2) map (lambda ([a], jacobi (a, 9)), l);
(%o2)         [1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0]
Функция: lcm (expr_1, ..., expr_n)

Возвращает наибольший общий делитель аргументов. Аргументы могут быть как целыми числами, так и общими выражениями.

Функцию загружает load ("functs").

Функция: minfactorial (expr)

Проверяет expr на наличие двух факториалов, различающихся на целое число. После этого minfactorial заменяет выражение произведением многочленов.

(%i1) n!/(n+2)!;
                               n!
(%o1)                       --------
                            (n + 2)!
(%i2) minfactorial (%);
                                1
(%o2)                    ---------------
                         (n + 1) (n + 2)
Функция: next_prime (n)

Возвращает наименьшее простое число, большее n.

(%i1) next_prime(27);
(%o1)                       29
Функция: partfrac (expr, var)

Разлагает выражение expr на простые дроби относительно главной переменной var. partfrac делает полное разложение на простые дроби. Используемый алгоритм основан на том, что знаменатели в разложении на простые дроби (сомножители исходного знаменателя) взаимно просты. Числители могут быть записаны как линейные комбинации знаменателей, откуда вытекает разложение.

(%i1) 1/(1+x)^2 - 2/(1+x) + 2/(2+x);
                      2       2        1
(%o1)               ----- - ----- + --------
                    x + 2   x + 1          2
                                    (x + 1)
(%i2) ratsimp (%);
                                 x
(%o2)                 - -------------------
                         3      2
                        x  + 4 x  + 5 x + 2
(%i3) partfrac (%, x);
                      2       2        1
(%o3)               ----- - ----- + --------
                    x + 2   x + 1          2
                                    (x + 1)
Функция: power_mod (a, n, m)

Использует модулярный алгоритм вычисления a^n mod m, где a и n - целые и m - положительное целое. Если n отрицательно, для поиска обратного по модулю m числа используется inv_mod.

(%i1) power_mod(3, 15, 5);
(%o1)                          2
(%i2) mod(3^15,5);
(%o2)                          2
(%i3) power_mod(2, -1, 5);
(%o3)                          3
(%i4) inv_mod(2,5);
(%o4)                          3
Функция: primep (n)

Проверка на простоту. Если primep (n) возвращает false, то n является составным числом; если возвращает true, то n с большой вероятностью является простым числом.

Для n меньше 341550071728321 используется детерминированная версия теста Миллера-Рабина. Если primep (n) возвращает true, то n есть простое число.

Для n больше 34155071728321 primep использует primep_number_of_tests тестов Миллера-Рабина на псевдопростоту и один тест Люкаса на псевдопростоту. Вероятность того, что n пройдет один тест Миллера-Рабина, менее 1/4. Для значения по умолчанию 25 переменной primep_number_of_tests вероятность того, что n будет составным, много меньше 10^-15.

Управляющая переменная: primep_number_of_tests

Значение по умолчанию: 25

Число тестов Миллера-Рабина, используемых в primep.

Функция: prev_prime (n)

Возвращает наибольшее простое число, меньшее n.

(%i1) prev_prime(27);
(%o1)                       23
Функция: qunit (n)

Возвращает элемент поля sqrt (n) с единичной нормой, что равносильно решению уравнения Пелля a^2 - n b^2 = 1.

(%i1) qunit (17);
(%o1)                     sqrt(17) + 4
(%i2) expand (% * (sqrt(17) - 4));
(%o2)                           1
Функция: totient (n)

Возвращает число целых чисел, меньших или равных n, которые взаимно просты с n.

Управляющая переменная: zerobern

Значение по умолчанию: true

Если zerobern равно false, bern исключает числа Бернулли, равные нулю. См. bern.

Функция: zeta (n)

Возвращает дзэта-функцию Римана, если n - отрицательное целое, 0, 1, или положительное четное число, и возвращает невычисляемую форму zeta (n) для всех других аргументов, включая не целые рациональные, числа с плавающей точкой и комплексные.

См. также bfzeta и zeta%pi.

(%i1) map (zeta, [-4, -3, -2, -1, 0, 1, 2, 3, 4, 5]);
                                     2              4
           1        1     1       %pi            %pi
(%o1) [0, ---, 0, - --, - -, inf, ----, zeta(3), ----, zeta(5)]
          120       12    2        6              90
Управляющая переменная: zeta%pi

Значение по умолчанию: true

Значение по умолчанию: true

Если zeta%pi равно true, zeta возвращает выражение, пропорциональное %pi^n для целого четного n. В противном случае для целого четного n возвращается невычисляемая форма zeta (n).

(%i1) zeta%pi: true$
(%i2) zeta (4);
                                 4
                              %pi
(%o2)                         ----
                               90
(%i3) zeta%pi: false$
(%i4) zeta (4);
(%o4)                        zeta(4)

Next: , Previous: Теория чисел, Up: Top   [Contents][Index]

30 Symmetries


Next: , Previous: Symmetries, Up: Symmetries   [Contents][Index]

30.1 Introduction to Symmetries

sym is a package for working with symmetric groups of polynomials.

It was written for Macsyma-Symbolics by Annick Valibouze (http://www-calfor.lip6.fr/~avb/). The algorithms are described in the following papers:

  1. Fonctions symétriques et changements de bases. Annick Valibouze. EUROCAL’87 (Leipzig, 1987), 323–332, Lecture Notes in Comput. Sci 378. Springer, Berlin, 1989.
    http://www.stix.polytechnique.fr/publications/1984-1994.html
  2. Résolvantes et fonctions symétriques. Annick Valibouze. Proceedings of the ACM-SIGSAM 1989 International Symposium on Symbolic and Algebraic Computation, ISSAC’89 (Portland, Oregon). ACM Press, 390-399, 1989.
    http://www-calfor.lip6.fr/~avb/DonneesTelechargeables/MesArticles/issac89ACMValibouze.pdf
  3. Symbolic computation with symmetric polynomials, an extension to Macsyma. Annick Valibouze. Computers and Mathematics (MIT, USA, June 13-17, 1989), Springer-Verlag, New York Berlin, 308-320, 1989.
    http://www.stix.polytechnique.fr/publications/1984-1994.html
  4. Théorie de Galois Constructive. Annick Valibouze. Mémoire d’habilitation à diriger les recherches (HDR), Université P. et M. Curie (Paris VI), 1994.

Previous: Introduction to Symmetries, Up: Symmetries   [Contents][Index]

30.2 Functions and Variables for Symmetries

30.2.1 Changing bases

Function: comp2pui (n, L)

implements passing from the complete symmetric functions given in the list L to the elementary symmetric functions from 0 to n. If the list L contains fewer than n+1 elements, it will be completed with formal values of the type h1, h2, etc. If the first element of the list L exists, it specifies the size of the alphabet, otherwise the size is set to n.

(%i1) comp2pui (3, [4, g]);
                        2                    2
(%o1)    [4, g, 2 h2 - g , 3 h3 - g h2 + g (g  - 2 h2)]
Function: ele2pui (m, L)

goes from the elementary symmetric functions to the complete functions. Similar to comp2ele and comp2pui.

Other functions for changing bases: comp2ele.

Function: ele2comp (m, L)

Goes from the elementary symmetric functions to the compete functions. Similar to comp2ele and comp2pui.

Other functions for changing bases: comp2ele.

Function: elem (ele, sym, lvar)

decomposes the symmetric polynomial sym, in the variables contained in the list lvar, in terms of the elementary symmetric functions given in the list ele. If the first element of ele is given, it will be the size of the alphabet, otherwise the size will be the degree of the polynomial sym. If values are missing in the list ele, formal values of the type e1, e2, etc. will be added. The polynomial sym may be given in three different forms: contracted (elem should then be 1, its default value), partitioned (elem should be 3), or extended (i.e. the entire polynomial, and elem should then be 2). The function pui is used in the same way.

On an alphabet of size 3 with e1, the first elementary symmetric function, with value 7, the symmetric polynomial in 3 variables whose contracted form (which here depends on only two of its variables) is x^4-2*x*y decomposes as follows in elementary symmetric functions:

(%i1) elem ([3, 7], x^4 - 2*x*y, [x, y]);
(%o1) 7 (e3 - 7 e2 + 7 (49 - e2)) + 21 e3

                                         + (- 2 (49 - e2) - 2) e2
(%i2) ratsimp (%);
                              2
(%o2)             28 e3 + 2 e2  - 198 e2 + 2401

Other functions for changing bases: comp2ele.

Function: mon2schur (L)

The list L represents the Schur function S_L: we have L = [i_1, i_2, ..., i_q], with i_1 <= i_2 <= ... <= i_q. The Schur function S_[i_1, i_2, ..., i_q] is the minor of the infinite matrix h_[i-j], i <= 1, j <= 1, consisting of the q first rows and the columns 1 + i_1, 2 + i_2, ..., q + i_q.

This Schur function can be written in terms of monomials by using treinat and kostka. The form returned is a symmetric polynomial in a contracted representation in the variables x_1,x_2,...

(%i1) mon2schur ([1, 1, 1]);
(%o1)                       x1 x2 x3
(%i2) mon2schur ([3]);
                                  2        3
(%o2)                x1 x2 x3 + x1  x2 + x1
(%i3) mon2schur ([1, 2]);
                                      2
(%o3)                  2 x1 x2 x3 + x1  x2

which means that for 3 variables this gives:

   2 x1 x2 x3 + x1^2 x2 + x2^2 x1 + x1^2 x3 + x3^2 x1
    + x2^2 x3 + x3^2 x2

Other functions for changing bases: comp2ele.

Function: multi_elem (l_elem, multi_pc, l_var)

decomposes a multi-symmetric polynomial in the multi-contracted form multi_pc in the groups of variables contained in the list of lists l_var in terms of the elementary symmetric functions contained in l_elem.

(%i1) multi_elem ([[2, e1, e2], [2, f1, f2]], a*x + a^2 + x^3,
      [[x, y], [a, b]]);
                                                  3
(%o1)         - 2 f2 + f1 (f1 + e1) - 3 e1 e2 + e1
(%i2) ratsimp (%);
                         2                       3
(%o2)         - 2 f2 + f1  + e1 f1 - 3 e1 e2 + e1

Other functions for changing bases: comp2ele.

Function: multi_pui

is to the function pui what the function multi_elem is to the function elem.

(%i1) multi_pui ([[2, p1, p2], [2, t1, t2]], a*x + a^2 + x^3,
      [[x, y], [a, b]]);
                                            3
                                3 p1 p2   p1
(%o1)              t2 + p1 t1 + ------- - ---
                                   2       2
Function: pui (L, sym, lvar)

decomposes the symmetric polynomial sym, in the variables in the list lvar, in terms of the power functions in the list L. If the first element of L is given, it will be the size of the alphabet, otherwise the size will be the degree of the polynomial sym. If values are missing in the list L, formal values of the type p1, p2 , etc. will be added. The polynomial sym may be given in three different forms: contracted (elem should then be 1, its default value), partitioned (elem should be 3), or extended (i.e. the entire polynomial, and elem should then be 2). The function pui is used in the same way.

(%i1) pui;
(%o1)                           1
(%i2) pui ([3, a, b], u*x*y*z, [x, y, z]);
                       2
                   a (a  - b) u   (a b - p3) u
(%o2)              ------------ - ------------
                        6              3
(%i3) ratsimp (%);
                                       3
                      (2 p3 - 3 a b + a ) u
(%o3)                 ---------------------
                                6

Other functions for changing bases: comp2ele.

Function: pui2comp (n, lpui)

renders the list of the first n complete functions (with the length first) in terms of the power functions given in the list lpui. If the list lpui is empty, the cardinal is n, otherwise it is its first element (as in comp2ele and comp2pui).

(%i1) pui2comp (2, []);
                                       2
                                p2 + p1
(%o1)                   [2, p1, --------]
                                   2
(%i2) pui2comp (3, [2, a1]);
                                            2
                                 a1 (p2 + a1 )
                         2  p3 + ------------- + a1 p2
                  p2 + a1              2
(%o2)     [2, a1, --------, --------------------------]
                     2                  3
(%i3) ratsimp (%);
                            2                     3
                     p2 + a1   2 p3 + 3 a1 p2 + a1
(%o3)        [2, a1, --------, --------------------]
                        2               6

Other functions for changing bases: comp2ele.

Function: pui2ele (n, lpui)

effects the passage from power functions to the elementary symmetric functions. If the flag pui2ele is girard, it will return the list of elementary symmetric functions from 1 to n, and if the flag is close, it will return the n-th elementary symmetric function.

Other functions for changing bases: comp2ele.

Function: puireduc (n, lpui)

lpui is a list whose first element is an integer m. puireduc gives the first n power functions in terms of the first m.

(%i1) puireduc (3, [2]);
                                         2
                                   p1 (p1  - p2)
(%o1)          [2, p1, p2, p1 p2 - -------------]
                                         2
(%i2) ratsimp (%);
                                           3
                               3 p1 p2 - p1
(%o2)              [2, p1, p2, -------------]
                                     2
Function: schur2comp (P, l_var)

P is a polynomial in the variables of the list l_var. Each of these variables represents a complete symmetric function. In l_var the i-th complete symmetric function is represented by the concatenation of the letter h and the integer i: hi. This function expresses P in terms of Schur functions.

(%i1) schur2comp (h1*h2 - h3, [h1, h2, h3]);
(%o1)                         s
                               1, 2
(%i2) schur2comp (a*h3, [h3]);
(%o2)                         s  a
                               3

30.2.2 Changing representations

Function: cont2part (pc, lvar)

returns the partitioned polynomial associated to the contracted form pc whose variables are in lvar.

(%i1) pc: 2*a^3*b*x^4*y + x^5;
                           3    4      5
(%o1)                   2 a  b x  y + x
(%i2) cont2part (pc, [x, y]);
                                   3
(%o2)              [[1, 5, 0], [2 a  b, 4, 1]]
Function: contract (psym, lvar)

returns a contracted form (i.e. a monomial orbit under the action of the symmetric group) of the polynomial psym in the variables contained in the list lvar. The function explose performs the inverse operation. The function tcontract tests the symmetry of the polynomial.

(%i1) psym: explose (2*a^3*b*x^4*y, [x, y, z]);
         3      4      3      4      3    4        3    4
(%o1) 2 a  b y z  + 2 a  b x z  + 2 a  b y  z + 2 a  b x  z

                                           3      4      3    4
                                      + 2 a  b x y  + 2 a  b x  y
(%i2) contract (psym, [x, y, z]);
                              3    4
(%o2)                      2 a  b x  y
Function: explose (pc, lvar)

returns the symmetric polynomial associated with the contracted form pc. The list lvar contains the variables.

(%i1) explose (a*x + 1, [x, y, z]);
(%o1)                  a z + a y + a x + 1
Function: part2cont (ppart, lvar)

goes from the partitioned form to the contracted form of a symmetric polynomial. The contracted form is rendered with the variables in lvar.

(%i1) part2cont ([[2*a^3*b, 4, 1]], [x, y]);
                              3    4
(%o1)                      2 a  b x  y
Function: partpol (psym, lvar)

psym is a symmetric polynomial in the variables of the list lvar. This function returns its partitioned representation.

(%i1) partpol (-a*(x + y) + 3*x*y, [x, y]);
(%o1)               [[3, 1, 1], [- a, 1, 0]]
Function: tcontract (pol, lvar)

tests if the polynomial pol is symmetric in the variables of the list lvar. If so, it returns a contracted representation like the function contract.

Function: tpartpol (pol, lvar)

tests if the polynomial pol is symmetric in the variables of the list lvar. If so, it returns its partitioned representation like the function partpol.

30.2.3 Groups and orbits

Function: direct ([p_1, ..., p_n], y, f, [lvar_1, ..., lvar_n])

calculates the direct image (see M. Giusti, D. Lazard et A. Valibouze, ISSAC 1988, Rome) associated to the function f, in the lists of variables lvar_1, ..., lvar_n, and in the polynomials p_1, ..., p_n in a variable y. The arity of the function f is important for the calculation. Thus, if the expression for f does not depend on some variable, it is useless to include this variable, and not including it will also considerably reduce the amount of computation.

(%i1) direct ([z^2  - e1* z + e2, z^2  - f1* z + f2],
              z, b*v + a*u, [[u, v], [a, b]]);
       2
(%o1) y  - e1 f1 y

                                 2            2             2   2
                  - 4 e2 f2 - (e1  - 2 e2) (f1  - 2 f2) + e1  f1
                + -----------------------------------------------
                                         2
(%i2) ratsimp (%);
              2                2                   2
(%o2)        y  - e1 f1 y + (e1  - 4 e2) f2 + e2 f1
(%i3) ratsimp (direct ([z^3-e1*z^2+e2*z-e3,z^2  - f1* z + f2],
              z, b*v + a*u, [[u, v], [a, b]]));
       6            5         2                        2    2   4
(%o3) y  - 2 e1 f1 y  + ((2 e1  - 6 e2) f2 + (2 e2 + e1 ) f1 ) y

                          3                               3   3
 + ((9 e3 + 5 e1 e2 - 2 e1 ) f1 f2 + (- 2 e3 - 2 e1 e2) f1 ) y

         2       2        4    2
 + ((9 e2  - 6 e1  e2 + e1 ) f2

                    2       2       2                   2    4
 + (- 9 e1 e3 - 6 e2  + 3 e1  e2) f1  f2 + (2 e1 e3 + e2 ) f1 )

  2          2                      2     3          2
 y  + (((9 e1  - 27 e2) e3 + 3 e1 e2  - e1  e2) f1 f2

                 2            2    3                5
 + ((15 e2 - 2 e1 ) e3 - e1 e2 ) f1  f2 - 2 e2 e3 f1 ) y

           2                   3           3     2   2    3
 + (- 27 e3  + (18 e1 e2 - 4 e1 ) e3 - 4 e2  + e1  e2 ) f2

         2      3                   3    2   2
 + (27 e3  + (e1  - 9 e1 e2) e3 + e2 ) f1  f2

                   2    4        2   6
 + (e1 e2 e3 - 9 e3 ) f1  f2 + e3  f1

Finding the polynomial whose roots are the sums a+u where a is a root of z^2 - e_1 z + e_2 and u is a root of z^2 - f_1 z + f_2.

(%i1) ratsimp (direct ([z^2 - e1* z + e2, z^2 - f1* z + f2],
                          z, a + u, [[u], [a]]));
       4                    3             2
(%o1) y  + (- 2 f1 - 2 e1) y  + (2 f2 + f1  + 3 e1 f1 + 2 e2

     2   2                              2               2
 + e1 ) y  + ((- 2 f1 - 2 e1) f2 - e1 f1  + (- 2 e2 - e1 ) f1

                  2                     2            2
 - 2 e1 e2) y + f2  + (e1 f1 - 2 e2 + e1 ) f2 + e2 f1  + e1 e2 f1

     2
 + e2

direct accepts two flags: elementaires and puissances (default) which allow decomposing the symmetric polynomials appearing in the calculation into elementary symmetric functions, or power functions, respectively.

Functions of sym used in this function:

multi_orbit (so orbit), pui_direct, multi_elem (so elem), multi_pui (so pui), pui2ele, ele2pui (if the flag direct is in puissances).

Function: multi_orbit (P, [lvar_1, lvar_2,..., lvar_p])

P is a polynomial in the set of variables contained in the lists lvar_1, lvar_2, ..., lvar_p. This function returns the orbit of the polynomial P under the action of the product of the symmetric groups of the sets of variables represented in these p lists.

(%i1) multi_orbit (a*x + b*y, [[x, y], [a, b]]);
(%o1)                [b y + a x, a y + b x]
(%i2) multi_orbit (x + y + 2*a, [[x, y], [a, b, c]]);
(%o2)        [y + x + 2 c, y + x + 2 b, y + x + 2 a]

Also see: orbit for the action of a single symmetric group.

Function: multsym (ppart_1, ppart_2, n)

returns the product of the two symmetric polynomials in n variables by working only modulo the action of the symmetric group of order n. The polynomials are in their partitioned form.

Given the 2 symmetric polynomials in x, y: 3*(x + y) + 2*x*y and 5*(x^2 + y^2) whose partitioned forms are [[3, 1], [2, 1, 1]] and [[5, 2]], their product will be

(%i1) multsym ([[3, 1], [2, 1, 1]], [[5, 2]], 2);
(%o1)         [[10, 3, 1], [15, 3, 0], [15, 2, 1]]

that is 10*(x^3*y + y^3*x) + 15*(x^2*y + y^2*x) + 15*(x^3 + y^3).

Functions for changing the representations of a symmetric polynomial:

contract, cont2part, explose, part2cont, partpol, tcontract, tpartpol.

Function: orbit (P, lvar)

computes the orbit of the polynomial P in the variables in the list lvar under the action of the symmetric group of the set of variables in the list lvar.

(%i1) orbit (a*x + b*y, [x, y]);
(%o1)                [a y + b x, b y + a x]
(%i2) orbit (2*x + x^2, [x, y]);
                        2         2
(%o2)                 [y  + 2 y, x  + 2 x]

See also multi_orbit for the action of a product of symmetric groups on a polynomial.

Function: pui_direct (orbite, [lvar_1, ..., lvar_n], [d_1, d_2, ..., d_n])

Let f be a polynomial in n blocks of variables lvar_1, ..., lvar_n. Let c_i be the number of variables in lvar_i, and SC be the product of n symmetric groups of degree c_1, ..., c_n. This group acts naturally on f. The list orbite is the orbit, denoted SC(f), of the function f under the action of SC. (This list may be obtained by the function multi_orbit.) The di are integers s.t. c_1 <= d_1, c_2 <= d_2, ..., c_n <= d_n.

Let SD be the product of the symmetric groups S_[d_1] x S_[d_2] x ... x S_[d_n]. The function pui_direct returns the first n power functions of SD(f) deduced from the power functions of SC(f), where n is the size of SD(f).

The result is in multi-contracted form w.r.t. SD, i.e. only one element is kept per orbit, under the action of SD.

(%i1) l: [[x, y], [a, b]];
(%o1)                   [[x, y], [a, b]]
(%i2) pui_direct (multi_orbit (a*x + b*y, l), l, [2, 2]);
                                       2  2
(%o2)               [a x, 4 a b x y + a  x ]
(%i3) pui_direct (multi_orbit (a*x + b*y, l), l, [3, 2]);
                             2  2     2    2        3  3
(%o3) [2 a x, 4 a b x y + 2 a  x , 3 a  b x  y + 2 a  x , 

    2  2  2  2      3    3        4  4
12 a  b  x  y  + 4 a  b x  y + 2 a  x , 

    3  2  3  2      4    4        5  5
10 a  b  x  y  + 5 a  b x  y + 2 a  x , 

    3  3  3  3       4  2  4  2      5    5        6  6
40 a  b  x  y  + 15 a  b  x  y  + 6 a  b x  y + 2 a  x ]
(%i4) pui_direct ([y + x + 2*c, y + x + 2*b, y + x + 2*a],
      [[x, y], [a, b, c]], [2, 3]);
                             2              2
(%o4) [3 x + 2 a, 6 x y + 3 x  + 4 a x + 4 a , 

                 2                   3        2       2        3
              9 x  y + 12 a x y + 3 x  + 6 a x  + 12 a  x + 8 a ]

30.2.4 Partitions

Function: kostka (part_1, part_2)

written by P. Esperet, calculates the Kostka number of the partition part_1 and part_2.

(%i1) kostka ([3, 3, 3], [2, 2, 2, 1, 1, 1]);
(%o1)                           6
Function: lgtreillis (n, m)

returns the list of partitions of weight n and length m.

(%i1) lgtreillis (4, 2);
(%o1)                   [[3, 1], [2, 2]]

Also see: ltreillis, treillis and treinat.

Function: ltreillis (n, m)

returns the list of partitions of weight n and length less than or equal to m.

(%i1) ltreillis (4, 2);
(%o1)               [[4, 0], [3, 1], [2, 2]]

Also see: lgtreillis, treillis and treinat.

Function: treillis (n)

returns all partitions of weight n.

(%i1) treillis (4);
(%o1)    [[4], [3, 1], [2, 2], [2, 1, 1], [1, 1, 1, 1]]

See also: lgtreillis, ltreillis and treinat.

Function: treinat (part)

returns the list of partitions inferior to the partition part w.r.t. the natural order.

(%i1) treinat ([5]);
(%o1)                         [[5]]
(%i2) treinat ([1, 1, 1, 1, 1]);
(%o2) [[5], [4, 1], [3, 2], [3, 1, 1], [2, 2, 1], [2, 1, 1, 1], 

                                                 [1, 1, 1, 1, 1]]
(%i3) treinat ([3, 2]);
(%o3)                 [[5], [4, 1], [3, 2]]

See also: lgtreillis, ltreillis and treillis.

30.2.5 Polynomials and their roots

Function: ele2polynome (L, z)

returns the polynomial in z s.t. the elementary symmetric functions of its roots are in the list L = [n, e_1, ..., e_n], where n is the degree of the polynomial and e_i the i-th elementary symmetric function.

(%i1) ele2polynome ([2, e1, e2], z);
                          2
(%o1)                    z  - e1 z + e2
(%i2) polynome2ele (x^7 - 14*x^5 + 56*x^3  - 56*x + 22, x);
(%o2)          [7, 0, - 14, 0, 56, 0, - 56, - 22]
(%i3) ele2polynome ([7, 0, -14, 0, 56, 0, -56, -22], x);
                  7       5       3
(%o3)            x  - 14 x  + 56 x  - 56 x + 22

The inverse: polynome2ele (P, z).

Also see: polynome2ele, pui2polynome.

Function: polynome2ele (P, x)

gives the list l = [n, e_1, ..., e_n] where n is the degree of the polynomial P in the variable x and e_i is the i-the elementary symmetric function of the roots of P.

(%i1) polynome2ele (x^7 - 14*x^5 + 56*x^3 - 56*x + 22, x);
(%o1)          [7, 0, - 14, 0, 56, 0, - 56, - 22]
(%i2) ele2polynome ([7, 0, -14, 0, 56, 0, -56, -22], x);
                  7       5       3
(%o2)            x  - 14 x  + 56 x  - 56 x + 22

The inverse: ele2polynome (l, x)

Function: prodrac (L, k)

L is a list containing the elementary symmetric functions on a set A. prodrac returns the polynomial whose roots are the k by k products of the elements of A.

Also see somrac.

Function: pui2polynome (x, lpui)

calculates the polynomial in x whose power functions of the roots are given in the list lpui.

(%i1) pui;
(%o1)                           1
(%i2) kill(labels);
(%o0)                         done
(%i1) polynome2ele (x^3 - 4*x^2 + 5*x - 1, x);
(%o1)                     [3, 4, 5, 1]
(%i2) ele2pui (3, %);
(%o2)                     [3, 4, 6, 7]
(%i3) pui2polynome (x, %);
                        3      2
(%o3)                  x  - 4 x  + 5 x - 1

See also: polynome2ele, ele2polynome.

Function: somrac (L, k)

The list L contains elementary symmetric functions of a polynomial P . The function computes the polynomial whose roots are the k by k distinct sums of the roots of P.

Also see prodrac.

30.2.6 Resolvents

Function: resolvante (P, x, f, [x_1,..., x_d])

calculates the resolvent of the polynomial P in x of degree n >= d by the function f expressed in the variables x_1, ..., x_d. For efficiency of computation it is important to not include in the list [x_1, ..., x_d] variables which do not appear in the transformation function f.

To increase the efficiency of the computation one may set flags in resolvante so as to use appropriate algorithms:

If the function f is unitary:

the flag of resolvante may be, respectively:

(%i1) resolvante: unitaire$
(%i2) resolvante (x^7 - 14*x^5 + 56*x^3 - 56*x + 22, x, x^3 - 1,
      [x]);

" resolvante unitaire " [7, 0, 28, 0, 168, 0, 1120, - 154, 7840,
                         - 2772, 56448, - 33880, 

413952, - 352352, 3076668, - 3363360, 23114112, - 30494464, 

175230832, - 267412992, 1338886528, - 2292126760] 
  3       6      3       9      6      3
[x  - 1, x  - 2 x  + 1, x  - 3 x  + 3 x  - 1, 

 12      9      6      3       15      12       9       6      3
x   - 4 x  + 6 x  - 4 x  + 1, x   - 5 x   + 10 x  - 10 x  + 5 x

       18      15       12       9       6      3
 - 1, x   - 6 x   + 15 x   - 20 x  + 15 x  - 6 x  + 1, 

 21      18       15       12       9       6      3
x   - 7 x   + 21 x   - 35 x   + 35 x  - 21 x  + 7 x  - 1] 
[- 7, 1127, - 6139, 431767, - 5472047, 201692519, - 3603982011] 
       7      6        5         4          3           2
(%o2) y  + 7 y  - 539 y  - 1841 y  + 51443 y  + 315133 y

                                              + 376999 y + 125253
(%i3) resolvante: lineaire$
(%i4) resolvante (x^4 - 1, x, x1 + 2*x2 + 3*x3, [x1, x2, x3]);

" resolvante lineaire " 
       24       20         16            12             8
(%o4) y   + 80 y   + 7520 y   + 1107200 y   + 49475840 y

                                                    4
                                       + 344489984 y  + 655360000
(%i5) resolvante: general$
(%i6) resolvante (x^4 - 1, x, x1 + 2*x2 + 3*x3, [x1, x2, x3]);

" resolvante generale " 
       24       20         16            12             8
(%o6) y   + 80 y   + 7520 y   + 1107200 y   + 49475840 y

                                                    4
                                       + 344489984 y  + 655360000
(%i7) resolvante (x^4 - 1, x, x1 + 2*x2 + 3*x3, [x1, x2, x3, x4]);

" resolvante generale " 
       24       20         16            12             8
(%o7) y   + 80 y   + 7520 y   + 1107200 y   + 49475840 y

                                                    4
                                       + 344489984 y  + 655360000
(%i8) direct ([x^4 - 1], x, x1 + 2*x2 + 3*x3, [[x1, x2, x3]]);
       24       20         16            12             8
(%o8) y   + 80 y   + 7520 y   + 1107200 y   + 49475840 y

                                                    4
                                       + 344489984 y  + 655360000
(%i9) resolvante :lineaire$
(%i10) resolvante (x^4 - 1, x, x1 + x2 + x3, [x1, x2, x3]);

" resolvante lineaire " 
                              4
(%o10)                       y  - 1
(%i11) resolvante: symetrique$
(%i12) resolvante (x^4 - 1, x, x1 + x2 + x3, [x1, x2, x3]);

" resolvante symetrique " 
                              4
(%o12)                       y  - 1
(%i13) resolvante (x^4 + x + 1, x, x1 - x2, [x1, x2]);

" resolvante symetrique " 
                           6      2
(%o13)                    y  - 4 y  - 1
(%i14) resolvante: alternee$
(%i15) resolvante (x^4 + x + 1, x, x1 - x2, [x1, x2]);

" resolvante alternee " 
            12      8       6        4        2
(%o15)     y   + 8 y  + 26 y  - 112 y  + 216 y  + 229
(%i16) resolvante: produit$
(%i17) resolvante (x^7 - 7*x + 3, x, x1*x2*x3, [x1, x2, x3]);

" resolvante produit "
        35      33         29        28         27        26
(%o17) y   - 7 y   - 1029 y   + 135 y   + 7203 y   - 756 y

         24           23          22            21           20
 + 1323 y   + 352947 y   - 46305 y   - 2463339 y   + 324135 y

          19           18             17              15
 - 30618 y   - 453789 y   - 40246444 y   + 282225202 y

             14              12             11            10
 - 44274492 y   + 155098503 y   + 12252303 y   + 2893401 y

              9            8            7             6
 - 171532242 y  + 6751269 y  + 2657205 y  - 94517766 y

            5             3
 - 3720087 y  + 26040609 y  + 14348907
(%i18) resolvante: symetrique$
(%i19) resolvante (x^7 - 7*x + 3, x, x1*x2*x3, [x1, x2, x3]);

" resolvante symetrique " 
        35      33         29        28         27        26
(%o19) y   - 7 y   - 1029 y   + 135 y   + 7203 y   - 756 y

         24           23          22            21           20
 + 1323 y   + 352947 y   - 46305 y   - 2463339 y   + 324135 y

          19           18             17              15
 - 30618 y   - 453789 y   - 40246444 y   + 282225202 y

             14              12             11            10
 - 44274492 y   + 155098503 y   + 12252303 y   + 2893401 y

              9            8            7             6
 - 171532242 y  + 6751269 y  + 2657205 y  - 94517766 y

            5             3
 - 3720087 y  + 26040609 y  + 14348907
(%i20) resolvante: cayley$
(%i21) resolvante (x^5 - 4*x^2 + x + 1, x, a, []);

" resolvante de Cayley "
        6       5         4          3            2
(%o21) x  - 40 x  + 4080 x  - 92928 x  + 3772160 x  + 37880832 x

                                                       + 93392896

For the Cayley resolvent, the 2 last arguments are neutral and the input polynomial must necessarily be of degree 5.

See also:

resolvante_bipartite, resolvante_produit_sym, resolvante_unitaire, resolvante_alternee1, resolvante_klein, resolvante_klein3, resolvante_vierer, resolvante_diedrale.

Function: resolvante_alternee1 (P, x)

calculates the transformation P(x) of degree n by the function product(x_i - x_j, 1 <= i < j <= n - 1).

See also:

resolvante_produit_sym, resolvante_unitaire, resolvante, resolvante_klein, resolvante_klein3, resolvante_vierer, resolvante_diedrale, resolvante_bipartite.

Function: resolvante_bipartite (P, x)

calculates the transformation of P(x) of even degree n by the function x_1 x_2 ... x_[n/2] + x_[n/2 + 1] ... x_n.

(%i1) resolvante_bipartite (x^6 + 108, x);
              10        8           6             4
(%o1)        y   - 972 y  + 314928 y  - 34012224 y

See also:

resolvante_produit_sym, resolvante_unitaire, resolvante, resolvante_klein, resolvante_klein3, resolvante_vierer, resolvante_diedrale, resolvante_alternee1.

Function: resolvante_diedrale (P, x)

calculates the transformation of P(x) by the function x_1 x_2 + x_3 x_4.

(%i1) resolvante_diedrale (x^5 - 3*x^4 + 1, x);
       15       12       11       10        9         8         7
(%o1) x   - 21 x   - 81 x   - 21 x   + 207 x  + 1134 x  + 2331 x

        6         5          4          3          2
 - 945 x  - 4970 x  - 18333 x  - 29079 x  - 20745 x  - 25326 x

 - 697

See also:

resolvante_produit_sym, resolvante_unitaire, resolvante_alternee1, resolvante_klein, resolvante_klein3, resolvante_vierer, resolvante.

Function: resolvante_klein (P, x)

calculates the transformation of P(x) by the function x_1 x_2 x_4 + x_4.

See also:

resolvante_produit_sym, resolvante_unitaire, resolvante_alternee1, resolvante, resolvante_klein3, resolvante_vierer, resolvante_diedrale.

Function: resolvante_klein3 (P, x)

calculates the transformation of P(x) by the function x_1 x_2 x_4 + x_4.

See also:

resolvante_produit_sym, resolvante_unitaire, resolvante_alternee1, resolvante_klein, resolvante, resolvante_vierer, resolvante_diedrale.

Function: resolvante_produit_sym (P, x)

calculates the list of all product resolvents of the polynomial P(x).

(%i1) resolvante_produit_sym (x^5 + 3*x^4 + 2*x - 1, x);
        5      4             10      8       7       6       5
(%o1) [y  + 3 y  + 2 y - 1, y   - 2 y  - 21 y  - 31 y  - 14 y

    4       3      2       10      8       7    6       5       4
 - y  + 14 y  + 3 y  + 1, y   + 3 y  + 14 y  - y  - 14 y  - 31 y

       3      2       5      4
 - 21 y  - 2 y  + 1, y  - 2 y  - 3 y - 1, y - 1]
(%i2) resolvante: produit$
(%i3) resolvante (x^5 + 3*x^4 + 2*x - 1, x, a*b*c, [a, b, c]);

" resolvante produit "
       10      8       7    6        5       4       3     2
(%o3) y   + 3 y  + 14 y  - y  - 14 y  - 31 y  - 21 y  - 2 y  + 1

See also:

resolvante, resolvante_unitaire, resolvante_alternee1, resolvante_klein, resolvante_klein3, resolvante_vierer, resolvante_diedrale.

Function: resolvante_unitaire (P, Q, x)

computes the resolvent of the polynomial P(x) by the polynomial Q(x).

See also:

resolvante_produit_sym, resolvante, resolvante_alternee1, resolvante_klein, resolvante_klein3, resolvante_vierer, resolvante_diedrale.

Function: resolvante_vierer (P, x)

computes the transformation of P(x) by the function x_1 x_2 - x_3 x_4.

See also:

resolvante_produit_sym, resolvante_unitaire, resolvante_alternee1, resolvante_klein, resolvante_klein3, resolvante, resolvante_diedrale.

30.2.7 Miscellaneous

Function: multinomial (r, part)

where r is the weight of the partition part. This function returns the associate multinomial coefficient: if the parts of part are i_1, i_2, ..., i_k, the result is r!/(i_1! i_2! ... i_k!).

Function: permut (L)

returns the list of permutations of the list L.


Next: , Previous: Symmetries, Up: Top   [Contents][Index]

31 Groups


Previous: Groups, Up: Groups   [Contents][Index]

31.1 Functions and Variables for Groups

Function: todd_coxeter
    todd_coxeter (relations, subgroup)
    todd_coxeter (relations)

Find the order of G/H where G is the Free Group modulo relations, and H is the subgroup of G generated by subgroup. subgroup is an optional argument, defaulting to []. In doing this it produces a multiplication table for the right action of G on G/H, where the cosets are enumerated [H,Hg2,Hg3,...]. This can be seen internally in the variable todd_coxeter_state.

Example:

(%i1) symet(n):=create_list(
        if (j - i) = 1 then (p(i,j))^^3 else
            if (not i = j) then (p(i,j))^^2 else
                p(i,i) , j, 1, n-1, i, 1, j);
                                                       <3>
(%o1) symet(n) := create_list(if j - i = 1 then p(i, j)

                                <2>
 else (if not i = j then p(i, j)    else p(i, i)), j, 1, n - 1,

i, 1, j)
(%i2) p(i,j) := concat(x,i).concat(x,j);
(%o2)        p(i, j) := concat(x, i) . concat(x, j)
(%i3) symet(5);
         <2>           <3>    <2>           <2>           <3>
(%o3) [x1   , (x1 . x2)   , x2   , (x1 . x3)   , (x2 . x3)   ,

            <2>           <2>           <2>           <3>    <2>
          x3   , (x1 . x4)   , (x2 . x4)   , (x3 . x4)   , x4   ]
(%i4) todd_coxeter(%o3);

Rows tried 426
(%o4)                          120
(%i5) todd_coxeter(%o3,[x1]);

Rows tried 213
(%o5)                          60
(%i6) todd_coxeter(%o3,[x1,x2]);

Rows tried 71
(%o6)                          20

Next: , Previous: Groups, Up: Top   [Contents][Index]

32 Окружение времени выполнения


Next: , Previous: Окружение времени выполнения, Up: Окружение времени выполнения   [Contents][Index]

32.1 Введение в окружение времени выполнения

Файл maxima-init.mac загружается автоматически при каждом запуске Maxima. Можно использовать maxima-init.mac для настройки своего персонального Maxima окружения. Файл maxima-init.mac обычно размещается в директории, определяемой переменной maxima_userdir, хотя может находиться и в любой другой директории, просматриваемой функцией file_search.

Пример содержимого файла maxima-init.mac:

setup_autoload ("specfun.mac", ultraspherical, assoc_legendre_p);
showtime:all;

Здесь, setup_autoload заставляет Maxima загружать файл specfun.mac, если функции ultraspherical или assoc_legendre_p вызываются, но не определены в момент вызова. При этом нет нужды помнить о необходимости загружать соответствующий файл до вызова данных функций.

Команда showtime: all устанавливает значение переменной showtime. Файл maxima-init.mac может содержать любые присваивания и другие команды Maxima.


Next: , Previous: Введение в окружение времени выполнения, Up: Окружение времени выполнения   [Contents][Index]

32.2 Прерывания

Пользователь может остановить длительное вычисление, нажав на ^C (Control-C). По умолчанию, текущее вычисление прекращается и выводится новое приглашение. Невозможно возобновить прерванные вычисления.

Если Lisp переменная *debugger-hook* установлена равной nil при помощи

:lisp (setq *debugger-hook* nil)

то после получения ^C, Maxima запускает Lisp отладчик, и пользователь может исследовать Lisp окружение. Остановленное вычисление может быть продолжено вводом команды continue в Lisp отладчике . Способы возврата в Maxima из Lisp отладчика, другие кроме продолжение вычисления до его завершения, различны для разных версий Lisp.

В системах типа Unix нажатие ^Z (Сontrol-Z) вызывает полную приостановку работы Maxima с возвращением управления в командную строку. Команда fg вызывает возобновление работы остановленной Maxima с точки, на которой она была остановлена.


Previous: Прерывания, Up: Окружение времени выполнения   [Contents][Index]

32.3 Функции и переменные времени выполнения

Декларация: feature

Maxima понимает два различных типа свойств: системные свойства и свойства, относящиеся к математическим выражениям. См. status по поводу системных свойств. См. features и featurep по поводу математических свойств.

feature само по себе не является именем функции или переменной.

Функция: featurep (a, f)

Пытается определить имеет ли объект a свойство f, используя факты, находящиеся в текущей базе данных. Если да, то возвращается true, иначе возвращается false.

Отметим, что featurep возвращает false если даже ни f, ни отрицание f не могут быть установлены.

Функция featurep вычисляет свои аргументы.

См. также declare и features.

(%i1) declare (j, even)$
(%i2) featurep (j, integer);
(%o2)                           true
Системная переменная: maxima_tempdir

Переменная maxima_tempdir обозначает директорию, в которой Maxima создает некоторые временные файлы. Например, временные файлы с данными для графиков создаются в maxima_tempdir.

Начальное значение maxima_tempdir является домашней директорией пользователя, если Maxima может ее определить. В противном случае Maxima делает догадку о расположении подходящей директории.

Переменной maxima_tempdir можно присвоить строку с именем директории.

Системная переменная: maxima_userdir

Переменная maxima_userdir обозначает директорию, в которой Maxima ищет Maxima и Lisp файлы. (Maxima ищет файлы и в некоторых других директориях. Полный список определяется переменными file_search_maxima и file_search_lisp.)

Начальное значение maxima_userdir является поддиректорией домашней директории пользователя, если Maxima может определить последнюю. В противном случае Maxima делает догадку о расположении подходящей директории.

Переменной maxima_userdir можно присвоить строку с именем директории. Однако, присваивание нового значения maxima_userdir не меняет автоматически file_search_maxima и file_search_lisp. Значение этих переменных нужно менять отдельно.

Функция: room ()
Функция: room (true)
Функция: room (false)

Выводит информацию о состоянии использования памяти и стека в Maxima. Команда room вызывает одноименную Lisp функцию.

Функция: status (feature)
Функция: status (feature, putative_feature)
Функция: status (status)

Возвращает информацию о наличии или отсутствии определенных системно-зависимых свойств.

Переменная features содержит список свойств, применимых к математическим выражениям. См. features и featurep по поводу дополнительной информации.

Функция: time (%o1, %o2, %o3, ...)

Возвращает список времен, в секундах, вычисления результирующих выражений %o1, %o2, %o3, ... . Время является внутренним временем вычисления Maxima, а не временем, прошедшим по реальным часам. Функция time применима только к меткам результирующих выражений, для других переменных time возвращает unknown.

Установка showtime: true заставляет Maxima печатать внутренее время вычисления и время по реальным часам для каждого результата.

Функция: timedate ()

Возвращает строку, содержащую текущее время и дату. Строка имеет формат HH:MM:SS Day, mm/dd/yyyy (GMT-n), где поля есть часы, минуты, секунды, день недели, месяц, день месяца, год и сдвиг часового пояса от GMT (Стандартное время по Гринвичу).

Пример:

(%i1) d: timedate ();
(%o1) 08:05:09 Wed, 11/02/2005 (GMT-7)
(%i2) print ("timedate reports current time", d)$
timedate reports current time 08:05:09 Wed, 11/02/2005 (GMT-7)
Функция: absolute_real_time ()

Возвращает число секунд, истекших с полуночи 1 января 1900 года по Универсальному Координированному Времени (UTC). Значение является целым числом.

См. также elapsed_real_time и elapsed_run_time.

Пример:

(%i1) absolute_real_time ();
(%o1)                      3385045277
(%i2) 1900 + absolute_real_time () / (365.25 * 24 * 3600);
(%o2)                   2007.265612087104
Функция: elapsed_real_time ()

Возвращает число секунд (включая доли секунды), истекших с последнего запуска или перезапуска Maxima по реальным часам. Значение является числом с плавающей точкой.

См. также absolute_real_time и elapsed_run_time.

Пример:

(%i1) elapsed_real_time ();
(%o1)                       2.559324
(%i2) expand ((a + b)^500)$
(%i3) elapsed_real_time ();
(%o3)                       7.552087
Функция: elapsed_run_time ()

Возвращает число секунд (включая доли секунды), истекших с последнего запуска или перезапуска Maxima по внутренним часам Maxima. Значение является числом с плавающей точкой.

См. также absolute_real_time и elapsed_real_time.

Пример:

(%i1) elapsed_run_time ();
(%o1)                         0.04
(%i2) expand ((a + b)^500)$
(%i3) elapsed_run_time ();
(%o3)                         1.26

Next: , Previous: Окружение времени выполнения, Up: Top   [Contents][Index]

33 Вспомогательные опции


Next: , Previous: Вспомогательные опции, Up: Вспомогательные опции   [Contents][Index]

33.1 Введение в вспомогательные опции

В этом разделе обсуждаются различные опции, имеющие глобальное влияние на работу Maxima. Также описываются различные системные списки, такие как список всех определенных пользователем функций.


Next: , Previous: Введение в вспомогательные опции, Up: Вспомогательные опции   [Contents][Index]

33.2 Библиотека Share

Maxima директория "share" содержит программы и другие полезные для пользователей Maxima файлы, не входящие в ядро системы. Обычно, эти программы загружаются с помощью команд load или setup_autoload.

:lisp *maxima-sharedir* указывает расположение директории "share" в файловой системе.

Команда printfile ("share.usg") печатает устаревший список пакетов share. Возможно, более информативным будет просмотр этой директории при помощи обычного файл-менеджера.


Previous: Библиотека Share, Up: Вспомогательные опции   [Contents][Index]

33.3 Вспомогательные функции и переменные

Системная переменная: aliases

Значение по умолчанию: []

aliases – список всех атомов, котрые имеют определенные пользователем алиасы (определяются функциями alias, ordergreat, orderless или при декларации атома noun при помощи declare).

Декларация: alphabetic

alphabetic является декларацией типа, распознаваемой функцией declare. Декларация declare(s, alphabetic) говорит Maxima рассматривать все символы, входящие в s (должен быть строкой), как буквенные.

См. также Идентификаторы.

Пример:

(%i1) xx\~yy\`\@ : 1729;
(%o1)                         1729
(%i2) declare ("~`@", alphabetic);
(%o2)                         done
(%i3) xx~yy`@ + @yy`xx + `xx@@yy~;
(%o3)               `xx@@yy~ + @yy`xx + 1729
(%i4) listofvars (%);
(%o4)                  [@yy`xx, `xx@@yy~]
Функция: apropos (string)

Ищет имена объектов Maxima, содержащие string в качестве подстроки. Например, вызов apropos (exp) возвращает список всех переменных и функций, имеющих exp в качестве части своего имени, такие как expand, exp и exponentialize. Таким образом, если вы помните только часть имени какого-либо объекта, то можете использовать эту команду для поиска полного наименования. Аналогично, можно использовать apropos (tr_), для того, чтобы вывести список переключателей, влияющих на работу транслятора, т.к. имена большинства из них начинаются с tr_.

Функция: args (expr)

Возвращает список аргументов параметра expr, который может быть любым отличным от атома выражением. Возвращаются только аргументы оператора самого верхнего уровня. Подвыражения expr появляются, как элементы подвыражений элементов списка аргументов.

Порядок выражений в возвращаемом списке может зависеть от глобального флага inflag.

Вызов args (expr) эквивалентен substpart ("[", expr, 0). См. также substpart и op.

Управляющая переменная: genindex

Значение по умолчанию: i

genindex – буквенный префикс, используемый для создания новой переменной суммирования.

Управляющая переменная: gensumnum

Значение по умолчанию: 0

gensumnum – числовой суффикс, используемый для создания новой переменной суммирования. Если равна false, то индекс будет состоять только из genindex без числового суффикса.

Системная переменная: infolists

Значение по умолчанию: []

infolists – есть список имен всех информационных списков Maxima. А именно:

labels

Все имеющие значение %i, %o и %t метки.

values

Все имеющие значение атомы, определенные пользователем (не встроенные в Maxima управляющие переменные и переключатели), созданные при помощи операторов :, :: или функциональным присваиванием.

functions

Все определенные пользователем функции, созданные при помощи := или define.

arrays

Все объявленные и необъявленные массивы, созданные при помощи :, :: или :=.

macros

Все определенные пользователем макро-функции.

myoptions

Все управляющие переменные, значение которых было изменено пользователем, независимо от того, имеют ли они в данный момент значения по умолчанию или нет.

rules

Все определенные пользователем правила подстановок и правила упрощения, созданные при помощи tellsimp, tellsimpafter, defmatch или defrule.

aliases

Все атомы, имеющие определенные пользователем алиасы, созданные при помощи функций alias, ordergreat, orderless или при декларации атома noun с помощью declare.

dependencies

Все атомы, имеющие функциональные зависимости, созданные с помощью функций depends или gradef.

gradefs

Все функции, имеющие определенные пользователем производные, определенные при помощи функции gradef.

props

Все атомы, имеющие свойства, отличные от упомянутых выше, такие как свойства задаваемые atvalue, matchdeclare и т.п., а также, свойства, установленные функцией declare.

let_rule_packages

Все определенные пользователем пакеты правил let плюс специальный пакет default_let_rule_package. (default_let_rule_package – имя пакета правил, который используется по умолчанию, если иной не объявлен пользователем явно.)

Функция: integerp (expr)

Возвращает true, если expr является буквальным целым числом, и false в противном случае.

Функция integerp возвращает false, если аргумент является символом, даже если этот символ объявлен целочисленным.

Примеры:

(%i1) integerp (0);
(%o1)                         true
(%i2) integerp (1);
(%o2)                         true
(%i3) integerp (-17);
(%o3)                         true
(%i4) integerp (0.0);
(%o4)                         false
(%i5) integerp (1.0);
(%o5)                         false
(%i6) integerp (%pi);
(%o6)                         false
(%i7) integerp (n);
(%o7)                         false
(%i8) declare (n, integer);
(%o8)                         done
(%i9) integerp (n);
(%o9)                         false
Управляющая переменная: m1pbranch

Значение по умолчанию: false

m1pbranch определяет главную ветвь для отрицательной степени -1. Величины, подобные (-1)^(1/3) (т.е. "нечетные" рациональные степени) и (-1)^(1/4) (т.е. "четные" рациональные степени) определяются следующим образом:

              domain:real
                            
(-1)^(1/3):      -1         
(-1)^(1/4):   (-1)^(1/4)   

             domain:complex              
m1pbranch:false          m1pbranch:true
(-1)^(1/3)               1/2+%i*sqrt(3)/2
(-1)^(1/4)              sqrt(2)/2+%i*sqrt(2)/2
Функция: numberp (expr)

Возвращает true, если expr есть буквальное целое число, рациональное число, число с плавающей точкой или число с плавающей точкой высокой точности, иначе возвращается false.

Функция numberp возвращает false, если параметр является символом, даже если он является символическим числом, таким как %pi или %i, или объявлен even, odd, integer, rational, irrational, real, imaginary или complex.

Примеры:

(%i1) numberp (42);
(%o1)                         true
(%i2) numberp (-13/19);
(%o2)                         true
(%i3) numberp (3.14159);
(%o3)                         true
(%i4) numberp (-1729b-4);
(%o4)                         true
(%i5) map (numberp, [%e, %pi, %i, %phi, inf, minf]);
(%o5)      [false, false, false, false, false, false]
(%i6) declare (a, even, b, odd, c, integer, d, rational,
     e, irrational, f, real, g, imaginary, h, complex);
(%o6)                         done
(%i7) map (numberp, [a, b, c, d, e, f, g, h]);
(%o7) [false, false, false, false, false, false, false, false]
Функция: properties (a)

Возвращает список имен всех свойств, ассоциированных с атомом a.

Специальный символ: props

props – список атомов, имеющих свойства отличные от тех, что явно перечислены в infolists, такие как, свойства, задаваемые atvalue, matchdeclare и т.п., а также свойства, задаваемые функцией declare.

Функция: propvars (prop)

Возвращает список атомов из списка props, которые имеют свойство, обозначаемое prop. Т.е. propvars (atvalue) возвращает список атомов, имеющих свойство atvalue.

Функция: put (atom, value, indicator)

Присваивает атому atom значение свойства indicator, равное value. indicator может быть не только системным свойством, но любым другим именем свойства.

Функция put вычисляет свои аргументы. put возвращает value.

Примеры:

(%i1) put (foo, (a+b)^5, expr);
                                   5
(%o1)                       (b + a)
(%i2) put (foo, "Hello", str);
(%o2)                         Hello
(%i3) properties (foo);
(%o3)            [[user properties, str, expr]]
(%i4) get (foo, expr);
                                   5
(%o4)                       (b + a)
(%i5) get (foo, str);
(%o5)                         Hello
Функция: qput (atom, value, indicator)

Присваивает атому atom значение свойства indicator, равное value. Аналогично put, но не вычисляет свои аргументы.

Примеры:

(%i1) foo: aa$ 
(%i2) bar: bb$
(%i3) baz: cc$
(%i4) put (foo, bar, baz);
(%o4)                          bb
(%i5) properties (aa);
(%o5)                [[user properties, cc]]
(%i6) get (aa, cc);
(%o6)                          bb
(%i7) qput (foo, bar, baz);
(%o7)                          bar
(%i8) properties (foo);
(%o8)            [value, [user properties, baz]]
(%i9) get ('foo, 'baz);
(%o9)                          bar
Функция: rem (atom, indicator)

Удаляет свойство indicator у атома atom.

Функция: remove (a_1, p_1, ..., a_n, p_n)
Функция: remove ([a_1, ..., a_m], [p_1, ..., p_n], ...)
Функция: remove ("a", operator)
Функция: remove (a, transfun)
Функция: remove (all, p)

Удаляет свойства, ассоциированные с атомами.

Вызов remove (a_1, p_1, ..., a_n, p_n) удаляет свойство p_k у атома a_k.

Вызов remove ([a_1, ..., a_m], [p_1, ..., p_n], ...) удаляет свойства p_1, ..., p_n у атомов a_1, ..., a_m. Может быть более чем одна пара списков.

Вызов remove (all, p) удаляет все свойства p у всех имеющих его атомов.

Удаляемые свойства могут быть как системными, такими как function, macro или mode_declare, так и пользовательскими.

Удаление свойства transfun удаляет транслированный Lisp вариант функции. После удаления этого свойства, вместо транслированной Lisp версии функции будет выполняться Maxima версия.

Вызов remove ("a", operator) или, эквивалентно, remove ("a", op), удаляет у a операторные свойства, декларированные функциями prefix, infix, nary, postfix, matchfix или nofix. Отметим, что имя оператора должно быть записано в виде строки с двойными кавычками.

remove всегда возвращает done, независимо от того, имел ли атом требуемое свойство или нет. Такое поведение отличается от более специфичных функций, удаляющих свойства, таких как remvalue, remarray, remfunction и remrule.

Функция: remvalue (name_1, ..., name_n)
Функция: remvalue (all)

Удаляет из системы значения пользовательских переменных name_1, ..., name_n (могут быть переменными с индексом).

Вызов remvalue (all) удаляет все значения всех переменных из списка определенных пользователем переменных values (в отличии от переменных, автоматически определенных Maxima).

См. также values.

Функция: rncombine (expr)

Преобразует выражение expr, комбинируя слагаемые expr, имеющие одинаковые знаменатели или знаменатели отличающиеся только на числовой множитель. Это поведение несколько отличается от поведения функции combine, которая собирает члены с идентичными знаменателями.

Устанавливая pfeformat: true и используя combine, можно получить результат более компактный, чем дает rncombine, но rncombine выполняет дополнительный шаг, перемножая численные множители знаменателей. Это приводит к более ясной форме и возможности распознать сокращения.

Команда load("rncomb") загружает эту функцию.

Функция: scalarp (expr)

Возвращает true если expr является числом, константой или переменной, объявленной scalar при помощи declare, или выражением, полностью состоящим из чисел, констант и скалярных переменных, но не содержащим матрицы или списки.

Функция: setup_autoload (filename, function_1, ..., function_n)

Определяет то, что если любая из функций function_1, ..., function_n вызывается, но еще не определена в момент вызова, то файл filename загружается при помощи load. Файл filename обычно содержит определения указанных функций, хотя это и не обязательно.

setup_autoload не работает для функций-массивов.

setup_autoload не вычисляет свои аргументы.

Примеры:

(%i1) legendre_p (1, %pi);
(%o1)                  legendre_p(1, %pi)
(%i2) setup_autoload ("specfun.mac", legendre_p, ultraspherical);
(%o2)                         done
(%i3) ultraspherical (2, 1/2, %pi);
Warning - you are redefining the Macsyma function ultraspherical
Warning - you are redefining the Macsyma function legendre_p
                            2
                 3 (%pi - 1)
(%o3)            ------------ + 3 (%pi - 1) + 1
                      2
(%i4) legendre_p (1, %pi);
(%o4)                          %pi
(%i5) legendre_q (1, %pi);
                              %pi + 1
                      %pi log(-------)
                              1 - %pi
(%o5)                 ---------------- - 1
                             2

Next: , Previous: Вспомогательные опции, Up: Top   [Contents][Index]

34 Правила преобразования и шаблоны


Next: , Previous: Правила преобразования и шаблоны, Up: Правила преобразования и шаблоны   [Contents][Index]

34.1 Введение в правила преобразований и шаблоны

Данный раздел описывает особенности программирования правил преобразований и шаблонов, применяемые в Maxima для упрощения выражений. Имеется две группы функций, реализующих несколько различающиеся схемы применения шаблонов преобразований. К одной группе относятся функции tellsimp, tellsimpafter, defmatch, defrule,apply1, applyb1 и apply2. В другую группу входят функции let и letsimp. В обоих группах шаблоны определяются через переменные шаблонов, объявляемые функцией matchdeclare.

Правила преобразований, определенные в процедурах tellsimp и tellsimpafter, применяются Maxima автоматически (если управляющая переменная simp имеет значение true). Правила преобразований, определенные в процедурах defmatch, defrule и let применяются только при явном вызове соответствующих функций.

Имеются, также, дополнительные возможности использования правил преобразований, например, при работе с полиномами в процедуре tellrat, и для коммутативной и некоммутативной алгебры в пакете affine.


Previous: Введение в правила преобразований и шаблоны, Up: Правила преобразования и шаблоны   [Contents][Index]

34.2 Функции и переменные для правил преобразования и шаблонов

Функция: apply1 (expr, rule_1, ..., rule_n)

Осуществляет повторное применение правила преобразования rule_1 к expr до тех пор пока выражение отвечает шаблону преобразования, затем, таким же образом осуществляется повторное применение этого правила ко всем подвыражениям expr, слева направо. Далее, к полученному результату тем же способом применяется правило rule_2 и так далее все последующие правила вплоть до rule_n. Конечный результат возвращается.

Переменная maxapplydepth контролирует нижнюю глубину уровня подвыражения до которого применяются правила преобразований в функциях apply1 и apply2.

См. также applyb1, apply2 и let.

Функция: apply2 (expr, rule_1, ..., rule_n)

Если правило rule_1 неприменимо на подвыражении expr, тогда применяется правило rule_2 и далее по той же схеме остальные правила. Только если каждое из правил является неприменимым на данном подвыражении expr, программа переходит на следующий уровень подвыражнния expr, и по той же схеме последовательно применяет весь набор правил, начиная с первого. Если применение одного из правил оказывается успешным, тогда весь набор правил заново применяется к этому подвыражению.

Переменная maxapplydepth контролирует нижнюю глубину уровня подвыражения до которого применяются правила преобразований в функциях apply1 и apply2.

См. также apply1 и let.

Функция: applyb1 (expr, rule_1, ..., rule_n)

В отличие от apply1 применяется по восходящей, т.е., сначала на самом глубоком уровне expr повторяется применение правила rule_1. Затем программа переходит на более высокие уровни expr и применяет данное правило по той же схеме. После того как применение правила rule_1 терпит неудачу на самом вернем уровне expr программа переходит к применению правила rule_2 по той же схеме (по восходящей) и так далее, заканчивая применением правила rule_n. После этого возвращается результат.

Функция applyb1 аналогична apply1, но работает по восходящей.

Переменная maxapplyheight контролирует высоту уровня подвыражения до которого применяются правила преобразований в функции applyb1.

См. также apply1, apply2 и let.

Управляющая переменная: current_let_rule_package

Значение по умолчанию: default_let_rule_package

current_let_rule_package - имя пакета правил, которые, если не определен другой пакет правил, используются функциями из программы let (такими как, letsimp, и т.д.) Эта переменной может быть присвоено имя любого пакета правил преобразований, определенного при помощи функции let.

При вызове letsimp (expr, rule_pkg_name), пакет правил rule_pkg_name используется только во время данного действия, при этом значение переменной current_let_rule_package остается неизменным.

Управляющая переменная: default_let_rule_package

Значение по умолчанию: default_let_rule_package

default_let_rule_package - имя пакета правил, используемого по умолчанию, если пакет правил не был задан в явном виде при вызове let или через изменение значения переменной current_let_rule_package.

Функция: defmatch (progname, pattern, x_1, ..., x_n)
Функция: defmatch (progname, pattern)

Определяет функцию progname (expr, x_1, ..., x_n), которая проверяет выражение expr на соответствие шаблону pattern.

Шаблон pattern - выражение, содержащее аргументы шаблона x_1, ..., x_n (если есть) и переменные шаблона (если есть). Аргументы шаблона задаются в явном виде, как аргументы функции defmatch, а переменные шаблона декларируются функцией matchdeclare. Всякая переменная, не декларированная как переменная шаблона при помощи mathdeclare или как аргумент шаблона при помощи defmatch соответствует только сама себе.

Первым аргументом создаваемой функции progname является выражение, проверяемое на соответствие шаблону, а другие аргументы это актуальные параметры, соответствующие аргументам шаблона x_1, ..., x_n.

Если проверка на соответствие шаблону оказывается успешной, то progname возвращает список уравнений, в которых левые части являются аргументами и переменными шаблона, а правые части - подвыражения expr, сопоставленные данным аргументам и переменным. Переменным шаблона, но не аргументам шаблона, присваиваются соответствующие значения. В случае неудачи сопоставления progname возвращает false.

Любая переменная, не объявленная в параметрах шаблона в matchdeclare или в переменных шаблона в defmatch, сопоставляется только самой себе.

Программа для буквального шаблона, т.е. шаблона не содержащего ни аргументов ни переменных, в случае удачи сопоставления возвращает true.

См. также matchdeclare, defrule, tellsimp и tellsimpafter.

Примеры:

Определим функцию linearp (expr, x), которая проверяет может ли expr быть представлено ввиде a*x + b, где a и b не содержат x и a отлично от нуля. Эта функция сопоставима с выражениями линейными по любой переменной, поскольку аргумент шаблона x определен в defmatch.

(%i1) matchdeclare (a, lambda ([e], e#0 and freeof(x, e)), b,
                    freeof(x));
(%o1)                         done
(%i2) defmatch (linearp, a*x + b, x);
(%o2)                        linearp
(%i3) linearp (3*z + (y + 1)*z + y^2, z);
                         2
(%o3)              [b = y , a = y + 4, x = z]
(%i4) a;
(%o4)                         y + 4
(%i5) b;
                                2
(%o5)                          y
(%i6) x;
(%o6)                           x

Определим функцию linearp(expr), которая проверяет может ли expr быть представлено ввиде a*x + b, где a и b не содержат x и a отлично от нуля. Эта функция сопоставима с выражениями линейными только по x, поскольку в defmatch не заданы никакие аргументы шаблона.

(%i1) matchdeclare (a, lambda ([e], e#0 and freeof(x, e)), b,
                    freeof(x));
(%o1)                         done
(%i2) defmatch (linearp, a*x + b);
(%o2)                        linearp
(%i3) linearp (3*z + (y + 1)*z + y^2);
(%o3)                         false
(%i4) linearp (3*x + (y + 1)*x + y^2);
                             2
(%o4)                  [b = y , a = y + 4]

Определим функцию checklimits(expr), которая проверяет, определяет ли expr интеграл.

(%i1) matchdeclare ([a, f], true);
(%o1)                         done
(%i2) constinterval (l, h) := constantp (h - l);
(%o2)        constinterval(l, h) := constantp(h - l)
(%i3) matchdeclare (b, constinterval (a));
(%o3)                         done
(%i4) matchdeclare (x, atom);
(%o4)                         done
(%i5) simp : false;
(%o5)                         false
(%i6) defmatch (checklimits, 'integrate (f, x, a, b));
(%o6)                      checklimits
(%i7) simp : true;
(%o7)                         true
(%i8) 'integrate (sin(t), t, %pi + x, 2*%pi + x);
                       x + 2 %pi
                      /
                      [
(%o8)                 I          sin(t) dt
                      ]
                      /
                       x + %pi
(%i9) checklimits (%);
(%o9)    [b = x + 2 %pi, a = x + %pi, x = t, f = sin(t)]
Функция: defrule (rulename, pattern, replacement)

Определяет и именует правило преобразования для данного шаблона. Если правило c именем rulename применяется к выражению (путем apply1, applyb1 или apply2), то каждое подвыражение, удовлетворяющее шаблону, заменяется соответствующей подстановкой. После этого выражение упрощается.

Правила могут рассматриваться как функции, преобразующие выражение путем одной операции сопоставления с шаблоном и подстановки. При неудаче сопоставления, функция правила преобразования возвращает false.

Функция: disprule (rulename_1, ..., rulename_2)
Функция: disprule (all)

Выводит правила преобразований и их имена rulename_1, ..., rulename_n, определенные в defrule, tellsimp или tellsimpafter, или шаблоны, определенные defmatch. Каждое правило выводится в форме промежуточного выражения, маркированного символом (%t).

Вызов disprule (all) выводит все определенные правила.

Функция disprule не вычисляет свои аргументы. Функция disprule возвращает список меток промежуточных выражений, соответствующих выведенным правилам.

См. также функцию letrules, которая выводит правила определенные let.

Примеры:

(%i1) tellsimpafter (foo (x, y), bar (x) + baz (y));
(%o1)                   [foorule1, false]
(%i2) tellsimpafter (x + y, special_add (x, y));
(%o2)                   [+rule1, simplus]
(%i3) defmatch (quux, mumble (x));
(%o3)                         quux
(%i4) disprule (foorule1, "+rule1", quux);
(%t4)        foorule1 : foo(x, y) -> baz(y) + bar(x)

(%t5)          +rule1 : y + x -> special_add(x, y)

(%t6)                quux : mumble(x) -> []

(%o6)                    [%t4, %t5, %t6]
(%i6) ''%;
(%o6) [foorule1 : foo(x, y) -> baz(y) + bar(x), 
     +rule1 : y + x -> special_add(x, y), quux : mumble(x) -> []]
Функция: let (prod, repl, predname, arg_1, ..., arg_n)
Функция: let ([prod, repl, predname, arg_1, ..., arg_n], package_name)

Определяет правила подстановки для функции letsimp такие, что prod заменяется на repl. prod является произведением подвыражений положительной или отрицательной степени. Подвыражения могут быть следующего типа:

Члены положительной степени будут сопоставляться только членам, имеющим положительную степень. Члены отрицательной степени будут сопоставляться только членам, имеющим отрицательную степень. Для того чтобы letsimp работал с отрицательными степенями в prod переменная letrat должна быть установлена равной true. См. также letrat.

Если в функцию let включен предикат, с последующим списком аргументов, то подстановки осуществляются только если predname (arg_1', ..., arg_n') дает true, где arg_i’ есть значение, сопоставленное arg_i. Переменная arg_i может быть именем атома или аргументом любого ядра, присутствующего в prod. repl может быть любым рациональным выражением. Если любой атом или аргумент из prod присутствует в repl, то выполняются соответствующие подстановки.

Глобальная переменная letrat управляет упрощением дробных выражений в letsimp. Если letrat равена false, то letsimp упрощает отдельно числитель и знаменатель выражения expr, но не упрощает их частное. В этом случае подстановки типа n!/n на (n-1)! не будут работать. Если letrat равена true, тогда числитель, знаменатель и их частное упрощаются в данном порядке.

Данные функции подстановок позволяют работать с несколькими пакетами правил одновременно. Каждый пакет правил может содержать любое количество правил преобразований let и обозначается некоторым заданным пользователем именем. Вызов let ([prod, repl, predname, arg_1, ..., arg_n], package_name) добавляет правило predname к пакету правил package_name. Вызов letsimp (expr, package_name) применяет правила преобразований из пакета package_name. Процедура letsimp (expr, package_name1, package_name2, ...) эквивалентна применению функций letsimp (expr, package_name1) и затем функции letsimp (%, package_name2), ....

Переменная current_let_rule_package содержит имя текущего пакета правил. Данной переменной может быть присвоено имя любого пакета правил, определенного при помощи let. Вызов команды let без упоминания имени пакета приводит к применению пакета, определенного current_let_rule_package. При вызове типа letsimp (expr, rule_pkg_name), используются правила пакета rule_pkg_name, только для данного вызова lrtsimp а значение переменной current_let_rule_package не меняется. По умолчанию current_let_rule_package равно default_let_rule_package.

(%i1) matchdeclare ([a, a1, a2], true)$
(%i2) oneless (x, y) := is (x = y-1)$
(%i3) let (a1*a2!, a1!, oneless, a2, a1);
(%o3)         a1 a2! --> a1! where oneless(a2, a1)
(%i4) letrat: true$
(%i5) let (a1!/a1, (a1-1)!);
                        a1!
(%o5)                   --- --> (a1 - 1)!
                        a1
(%i6) letsimp (n*m!*(n-1)!/m);
(%o6)                      (m - 1)! n!
(%i7) let (sin(a)^2, 1 - cos(a)^2);
                        2               2
(%o7)                sin (a) --> 1 - cos (a)
(%i8) letsimp (sin(x)^4);
                        4           2
(%o8)                cos (x) - 2 cos (x) + 1
Управляющая переменная: letrat

Значение по умолчанию: false

Если letrat равна false, то letsimp упрощает отдельно числитель и знаменатель выражения expr, и не упрощает их частное.

Если letrat равна true, то числитель, знаменатель и их частное упрощаются в данном порядке.

(%i1) matchdeclare (n, true)$
(%i2) let (n!/n, (n-1)!);
                         n!
(%o2)                    -- --> (n - 1)!
                         n
(%i3) letrat: false$
(%i4) letsimp (a!/a);
                               a!
(%o4)                          --
                               a
(%i5) letrat: true$
(%i6) letsimp (a!/a);
(%o6)                       (a - 1)!
Функция: letrules ()
Функция: letrules (package_name)

Выводит правила, содержащиеся в пакете правил преобразований. letrules () выводит правила текущего пакета правил преобразований. letrules (package_name) выводит правила преобразований в пакете package_name.

Текущий пакет правил определяется значением current_let_rule_package. Если не определено иначе, то current_let_rule_package по умолчанию равен default_let_rule_package.

См. также функцию disprule, отображающую правила, определенные путем tellsimp и tellsimpafter.

Функция: letsimp (expr)
Функция: letsimp (expr, package_name)
Функция: letsimp (expr, package_name_1, ..., package_name_n)

Данная функция осуществляет повторное применение правил подстановки, определенных в let, до тех пор пока выражение expr не перестанет изменяться.

letsimp (expr) использует правила из пакета current_let_rule_package.

letsimp (expr, package_name) использует правила из пакета package_name без изменения значения переменной current_let_rule_package.

letsimp (expr, package_name_1, ..., package_name_n) эквивалентно применению letsimp (expr, package_name_1, затем letsimp (%, package_name_2) и так далее.

Управляющая переменная: let_rule_packages

Значение по умолчанию: [default_let_rule_package]

let_rule_packages - список определенных пользователем пакетов правил вместе с пакетом default_let_rule_package.

Функция: matchdeclare (a_1, pred_1, ..., a_n, pred_n)

Связывает предикат pred_k с переменной или списком переменных a_k, так что a_k сопоставляется с выражениями, для которых предикат возвращает значение отличное от false.

Предикат это есть имя функции, или лямбда-выражение, или вызов функции или лямбда-выражения без последнего аргумента, или true, или all. Если предикат определен при помощи вызова функции или лямбда-выражения, то тестируемое выражение добавляется к списку аргументов; аргументы вычисляются во время вызова процедуры проверки на соответствие. Если предикат определен в виде имени функции или лямбда-выражения, то единственным аргументом является тестируемое выражение. Предикат не обязан быть определенным в момент вызова matchdeclare, поскольку он не вычисляется до тех пор пока не вызывается проверка на соответствие.

Предикат может возвращать логическое выражение а также true или false. Логическое выражение вычисляется при помощи is внутри построенной функции правила, так что нет необходимости вызывать is в предикате.

Если выражение удовлетворяет предикату, то переменной шаблона присваивается выражение за исключением переменных шаблона которые являются операндами сложения + или умножения *. Только сложение и умножение управляется специальным образом. Другие n-арные операторы, (как пользовательские, так и встроенные) рассматриваются как обычные функции.

В случае операторов сложения и умножения, переменной шаблона может быть присвоено простое выражение, которое соответствует предикату, а также сумма или произведение таких выражений. Такое сложное сопоставление является ресурсоемким: предикаты вычисляются в порядке в котором, ассоциированные с ними переменные, встречаются в тестируемом выражении, и член, удовлетворяющий более чем одному предикату, сопоставляется первому соответствующему предикату. Каждый предикат проверяется для всех операндов суммы или произведения и только после этого проверяется следующий предикат. Кроме того, если 0 или 1 удовлетворяют предикату, а все остальные слагаемые выражения нет, тогда 0 или 1 присваиваются переменным шаблона ассоциированным с предикатом.

Алгоритм проверки шаблонов, содержащий суммы и произведения, может давать разные результаты (например, шаблон, содержащий переменную соответствующую "всему, что угодно") в зависимости от порядка членов заданного шаблона и порядка членов тестируемого выражения. Если все операторы предикаты взаимно исключают друг друга, то результат не зависит от порядка, поскольку члены, соответствующие одному предикату, не могут соответствовать другому.

Вызов matchdeclare с переменной a в качестве аргумента изменяет ранее объявленные свойства matchdeclare для a - при определении правил преобразования, учитываются только самый последний вызов matchdeclare. Все последующие изменения свойства matchdeclare (посредством matchdeclare или remove) не меняют существующих правил преобразований.

propvars (matchdeclare) возвращает список всех переменных, имеющих свойство matchdeclare. printprops (a, matchdeclare) возвращает предикат для переменной a. printprops (all, matchdeclare) возвращает список всех предикатов для всех переменных matchdeclare. remove (a, matchdeclare) удаляет свойства matchdeclare для переменной a.

Функции defmatch, defrule, tellsimp, tellsimpafter и let строят правила, которые сопоставляют выражения с шаблонами.

Функция matchdeclare не вычисляет свои аргументы. Функция matchdeclare всегда возвращает done.

Примеры:

Предикат есть имя функции, или лямбда-выражение, или вызов функции или лямбда-вызов без последнего аргумента, или true, или all.

(%i1) matchdeclare (aa, integerp);
(%o1)                         done
(%i2) matchdeclare (bb, lambda ([x], x > 0));
(%o2)                         done
(%i3) matchdeclare (cc, freeof (%e, %pi, %i));
(%o3)                         done
(%i4) matchdeclare (dd, lambda ([x, y], gcd (x, y) = 1) (1728));
(%o4)                         done
(%i5) matchdeclare (ee, true);
(%o5)                         done
(%i6) matchdeclare (ff, all);
(%o6)                         done

Если выражение удовлетворяет предикату, то переменной шаблона присваивается выражение.

(%i1) matchdeclare (aa, integerp, bb, atom);
(%o1)                         done
(%i2) defrule (r1, bb^aa, ["integer" = aa, "atom" = bb]);
                    aa
(%o2)        r1 : bb   -> [integer = aa, atom = bb]
(%i3) r1 (%pi^8);
(%o3)               [integer = 8, atom = %pi]

В случае суммы и произведения, переменной шаблона может быть присвоено простое выражение, которое удовлетворяет предикату, или также сумма или произведение таких выражений.

(%i1) matchdeclare (aa, atom, bb, lambda ([x], not atom(x)));
(%o1)                         done
(%i2) defrule (r1, aa + bb, ["all atoms" = aa, "all nonatoms" =
               bb]);
bb + aa partitions `sum'
(%o2)  r1 : bb + aa -> [all atoms = aa, all nonatoms = bb]
(%i3) r1 (8 + a*b + sin(x));
(%o3)     [all atoms = 8, all nonatoms = sin(x) + a b]
(%i4) defrule (r2, aa * bb, ["all atoms" = aa, "all nonatoms" =
               bb]);
bb aa partitions `product'
(%o4)   r2 : aa bb -> [all atoms = aa, all nonatoms = bb]
(%i5) r2 (8 * (a + b) * sin(x));
(%o5)    [all atoms = 8, all nonatoms = (b + a) sin(x)]

При сопоставлении аргументов + и *, если все предикаты условия являются взаимоисключающими, то результат проверки не зависит порядка, так как один предикат не соответствует членам, соответствующим другому предикату.

(%i1) matchdeclare (aa, atom, bb, lambda ([x], not atom(x)));
(%o1)                         done
(%i2) defrule (r1, aa + bb, ["all atoms" = aa, "all nonatoms" =
               bb]);
bb + aa partitions `sum'
(%o2)  r1 : bb + aa -> [all atoms = aa, all nonatoms = bb]
(%i3) r1 (8 + a*b + %pi + sin(x) - c + 2^n);
                                                     n
(%o3) [all atoms = %pi + 8, all nonatoms = sin(x) + 2  - c + a b]
(%i4) defrule (r2, aa * bb, ["all atoms" = aa, "all nonatoms" =
               bb]);
bb aa partitions `product'
(%o4)   r2 : aa bb -> [all atoms = aa, all nonatoms = bb]
(%i5) r2 (8 * (a + b) * %pi * sin(x) / c * 2^n);
                                                  n
                                         (b + a) 2  sin(x)
(%o5) [all atoms = 8 %pi, all nonatoms = -----------------]
                                                 c

Функции propvars и printprops возвращают информацию о переменных шаблона.

(%i1) matchdeclare ([aa, bb, cc], atom, [dd, ee], integerp);
(%o1)                         done
(%i2) matchdeclare (ff, floatnump, gg, lambda ([x], x > 100));
(%o2)                         done
(%i3) propvars (matchdeclare);
(%o3)             [aa, bb, cc, dd, ee, ff, gg]
(%i4) printprops (ee, matchdeclare);
(%o4)                    [integerp(ee)]
(%i5) printprops (gg, matchdeclare);
(%o5)              [lambda([x], x > 100, gg)]
(%i6) printprops (all, matchdeclare);
(%o6) [lambda([x], x > 100, gg), floatnump(ff), integerp(ee), 
                      integerp(dd), atom(cc), atom(bb), atom(aa)]
Функция: matchfix (ldelimiter, rdelimiter)
Функция: matchfix (ldelimiter, rdelimiter, arg_pos, pos)

Объявляет матчфиксный (matchfix) оператор с левым и правым ограничителями ldelimiter и rdelimiter соответственно. Ограничители являются строками.

Матчфиксный оператор является функцией любого количества аргументов заключенных между ограничителями ldelimiter и rdelimiter. Ограничителем может являться любая строка, если синтаксический анализатор может различить ограничители от других выражений и операторов. На практике, это исключает такие ограничители, как %, ,, $ и ;, и может потребовать при вводе изолировать ограничители пробелами. Правый ограничитель может совпадать с левым или отличаться от него.

Левый ограничитель может быть ассоциирован только с одним правым; два различных матчфиксных оператора не могут иметь одинаковых левых ограничителя.

Существующий оператор может быть переобъявлен, как матчфиксный оператор без изменения других его свойств. Например, встроенные операторы сложения + могут быть объявлены матчфиксными, однако операторные функции для встроенных операторов определены быть не могут.

Вызов matchfix (ldelimiter, rdelimiter, arg_pos, pos) объявляет аргумент "часть речи" arg_pos и результат "часть речи" pos вместе с ограничителями ldelimiter и rdelimiter.

Термин "чать речи" по отношению к декларации операторов означает тип выражения. Различаются три типа выражений: expr, clause и any, что обозначает алгебраическое выражение, логическое выражение и выражение произвольного типа соответственно. Maxima может обнаруживать некоторые синтаксические ошибки сравнивая объявленную часть речи с реальным выражением.

Функция для выполнения матчфиксной операции является обычной пользовательской функцией. Операторная функция определяется стандартным образом при помощи операторов := или define. Аргументы могут быть записаны между ограничителями или при помощи левого ограничителя в форме строки и последующих аргументов в скобках. dispfun (ldelimiter) выводит определение функции.

Единственный встроенный матчфиксный оператор это конструктор списка [ ]. Скобки ( ) и двойные кавычки " " работают как матчфиксные операторы, однако не обрабатываются синтаксическим анализатором Maxima как таковые.

Функция matchfix вычисляет свои аргументы. Функция matchfix возвращает свой первый аргумент ldelimiter.

Примеры:

(%i1) matchfix ("@@", "~");
(%o1)                          @@
(%i2) @@ a, b, c ~;
(%o2)                      @@a, b, c~
(%i3) matchfix (">>", "<<");
(%o3)                          >>
(%i4) >> a, b, c <<;
(%o4)                      >>a, b, c<<
(%i5) matchfix ("foo", "oof");
(%o5)                          foo
(%i6) foo a, b, c oof;
(%o6)                     fooa, b, coof
(%i7) >> w + foo x, y oof + z << / @@ p, q ~;
                     >>z + foox, yoof + w<<
(%o7)                ----------------------
                            @@p, q~
(%i1) matchfix ("!-", "-!");
(%o1)                         "!-"
(%i2) !- x, y -! := x/y - y/x;
                                    x   y
(%o2)                   !-x, y-! := - - -
                                    y   x
(%i3) define (!-x, y-!, x/y - y/x);
                                    x   y
(%o3)                   !-x, y-! := - - -
                                    y   x
(%i4) define ("!-" (x, y), x/y - y/x);
                                    x   y
(%o4)                   !-x, y-! := - - -
                                    y   x
(%i5) dispfun ("!-");
                                    x   y
(%t5)                   !-x, y-! := - - -
                                    y   x

(%o5)                         done
(%i6) !-3, 5-!;
                                16
(%o6)                         - --
                                15
(%i7) "!-" (3, 5);
                                16
(%o7)                         - --
                                15
Функция: remlet (prod, name)
Функция: remlet ()
Функция: remlet (all)
Функция: remlet (all, name)

Удаляет правило подстановки prod -> замена, определенное при самом последнем вызове функции let. При вызове с именем правила в качестве аргумента удаление производится из соответствующего пакета правил.

Вызовы remlet() и remlet(all) удаляют все правила подстановки из текущего пакета правил. При указании имени, например, remlet (all, name), пакет правил name также удаляется.

Если необходимо изменить правило подстановки одного произведения, нет необходимости вызывать remlet, можно просто переопределить подстановку данного произведения при помощи функции let, с новой заменой и/или предикатом. После этого вызов remlet (prod) восстанавливает исходное правило подстановки.

См. также функцию remrule, которая удаляет правила определенные функцией tellsimp или tellsimpafter.

Функция: remrule (op, rulename)
Функция: remrule (op, all)

Удаляет правила, определенные функциями tellsimp или tellsimpafter.

remrule (op, rulename) удаляет правило с именем rulename для оператора op. Если оператор op является встроенным оператором или определен пользователем (например, при помощи функций infix, prefix, и т.п.), тогда op и rulename необходимо заключить в двойные кавычки.

remrule (op, all) удаляет все правила для оператора op.

См. также функцию remlet, удаляющую правила, определенные при помощи let.

Примеры:

(%i1) tellsimp (foo (aa, bb), bb - aa);
(%o1)                   [foorule1, false]
(%i2) tellsimpafter (aa + bb, special_add (aa, bb));
(%o2)                   [+rule1, simplus]
(%i3) infix ("@@");
(%o3)                          @@
(%i4) tellsimp (aa @@ bb, bb/aa);
(%o4)                   [@@rule1, false]
(%i5) tellsimpafter (quux (%pi, %e), %pi - %e);
(%o5)                  [quuxrule1, false]
(%i6) tellsimpafter (quux (%e, %pi), %pi + %e);
(%o6)             [quuxrule2, quuxrule1, false]
(%i7) [foo (aa, bb), aa + bb, aa @@ bb, quux (%pi, %e),
       quux (%e, %pi)];
                                     bb
(%o7) [bb - aa, special_add(aa, bb), --, %pi - %e, %pi + %e]
                                     aa
(%i8) remrule (foo, foorule1);
(%o8)                          foo
(%i9) remrule ("+", "+rule1");
(%o9)                           +
(%i10) remrule ("@@", "@@rule1");
(%o10)                         @@
(%i11) remrule (quux, all);
(%o11)                        quux
(%i12) [foo (aa, bb), aa + bb, aa @@ bb, quux (%pi, %e),
        quux (%e, %pi)];
(%o12) [foo(aa, bb), bb + aa, aa @@ bb, quux(%pi, %e), 
                                         quux(%e, %pi)]
Функция: tellsimp (pattern, replacement)

аналогична tellsimpafter, но добавляет новую информацию о правилах до уже существующей. Таким образом, сначала применяются пользовательские правила упрощения, а потом правила, встроенные в систему.

Функция tellsimp используется, когда важно модифицировать выражение до того, как оно обработано упрощателем, например, встроенный механизм упрощения "знает" что-либо о структуре выражения, но возвращает результат, который вас не устраивает. Если встроенный механизм упрощения "знает" что-либо о главном операторе выражения, но работает не достаточно эффективно - можно попробовать использовать tellsimpafter.

Шаблон не может быть суммой, произведением, одиночной переменной или числом.

rules - список правил определенный функциями defrule, defmatch, tellsimp и tellsimpafter.

Примеры:

(%i1) matchdeclare (x, freeof (%i));
(%o1)                         done
(%i2) %iargs: false$
(%i3) tellsimp (sin(%i*x), %i*sinh(x));
(%o3)                 [sinrule1, simp-%sin]
(%i4) trigexpand (sin (%i*y + x));
(%o4)         sin(x) cos(%i y) + %i cos(x) sinh(y)
(%i5) %iargs:true$
(%i6) errcatch(0^0);
 0
0  has been generated
(%o6)                          []
(%i7) ev (tellsimp (0^0, 1), simp: false);
(%o7)                  [^rule1, simpexpt]
(%i8) 0^0;
(%o8)                           1
(%i9) remrule ("^", %th(2)[1]);
(%o9)                           ^
(%i10) tellsimp (sin(x)^2, 1 - cos(x)^2);
(%o10)                 [^rule2, simpexpt]
(%i11) (1 + sin(x))^2;
                                      2
(%o11)                    (sin(x) + 1)
(%i12) expand (%);
                                   2
(%o12)               2 sin(x) - cos (x) + 2
(%i13) sin(x)^2;
                                  2
(%o13)                     1 - cos (x)
(%i14) kill (rules);
(%o14)                        done
(%i15) matchdeclare (a, true);
(%o15)                        done
(%i16) tellsimp (sin(a)^2, 1 - cos(a)^2);
(%o16)                 [^rule3, simpexpt]
(%i17) sin(y)^2;
                                  2
(%o17)                     1 - cos (y)
Функция: tellsimpafter (pattern, replacement)

Определяет правило упрощения, которое встроенный в Maxima механизм упрощения применяет после встроенных правил упрощения. pattern - выражение, включающее переменные шаблона (объявленные в matchdeclare) и другие атомы и операторы, которые рассматриваются как константы с точки зрения сопоставления с шаблоном. replacement подставляется вместо первоначального выражения, удовлетворяющего шаблону pattern; переменным шаблона из в replacement присваиваются соответствующие подвыражения из реального выражения.

pattern может быть любым составным выражением в котором имя главного оператор не входит в число переменных шаблона; правило упрощения связывается с именем главного оператора. Имена функций (за исключением приведенных ниже), списки и массивы могут присутствовать в шаблоне pattern в качестве основного оператора только, как литералы (не переменные шаблона); это исключает шаблоны вида aa(x) и bb[y], если aa и bb являются переменными шаблона. Имена функций, списки и массивы, которые являются переменными шаблона могут входить в качестве не основных операторов в описание шаблона pattern.

Есть одно исключение к указанному правилу, касающееся имен функций. Имена функций с индексом в выражениях типа aa[x](y) могут быть переменными шаблона, поскольку в этом случае главный оператор не aa, а Lisp-атом mqapply. Это является следствием представления выражений, включающих функции с индексом.

Правила упрощения применяются после вычисления (если вычисления не запрещены либо экранированием выражения, либо ключом noeval). Правила введенные tellsimpafter применяются в том порядке в котором они были определены после всех встроенных правил. Преобразования применяются "снизу-вверх", т.е., сначала к подвыражению, перед обработкой выражения в целом. Иногда для того, чтобы обеспечить, что применены все правила, необходимо повторное упрощение результата (например, при применении оператора кавычка-кавычка '' или ключа infeval).

Переменные шаблона рассматриваются как локальные переменные в правилах упрощения. Как только правило определено, значение переменной шаблона не влияет на правило, и наоборот, правило не влияет на значение переменной. Присваивание значений переменным шаблона, происходящее в результате успешного сопоставления шаблона, не влияет на текущие значения (или их отсутствие) переменных шаблона. Однако, как и у всех атомов в Maxima, свойства переменных шаблона (объявленные оператором put и подобными функциями) являются глобальными.

Правило, построенное с помощью tellsimpafter, обозначаеся именем главного оператора pattern. Правила для встроенных операторов и пользовательских функций, определенных при помощи infix, prefix, postfix, matchfix и nofix, имеют имена, являющиеся Lisp-идентификаторами. Правила для других функций имеют имена, являющиеся идентификаторами Maxima.

Обработка вычисляемых и не вычисляемых форм немного неоднозначна. Если правило определено для невычисляемой (или вычисляемой) формы выражения, а правило для соответствующей вычисляемой (или невычисляемой) уже существует, то новое правило применяется к обеим формам выражения (вычисляемой и невычисляемой). Если правило для соответствующей вычисляемой (или невычисляемой) не существует, то новое правило применяется к невычисляемой (или вычисляемой) форме выражения.

Правило, построенное с помощью tellsimpafter, является обычной Lisp- функцией. Если имя правила - $foorule1, то конструкция :lisp (trace $foorule1) дает трассировку ее вызовов, а :lisp (symbol-function '$foorule1 выводит ее определение.

Функция tellsimpafter не вычисляет свои аргументы. Функция tellsimpafter возвращает список правил для основного оператора шаблона pattern, включая вновь объявленные правила.

См. также matchdeclare, defmatch, defrule, tellsimp, let, kill, remrule и clear_rules.

Примеры:

pattern может быть любым неатомарным выражением в котором главный оператор не является переменной шаблона.

(%i1) matchdeclare (aa, atom, [ll, mm], listp, xx, true)$
(%i2) tellsimpafter (sin (ll), map (sin, ll));
(%o2)                 [sinrule1, simp-%sin]
(%i3) sin ([1/6, 1/4, 1/3, 1/2, 1]*%pi);
                    1  sqrt(2)  sqrt(3)
(%o3)              [-, -------, -------, 1, 0]
                    2     2        2
(%i4) tellsimpafter (ll^mm, map ("^", ll, mm));
(%o4)                  [^rule1, simpexpt]
(%i5) [a, b, c]^[1, 2, 3];
                                2   3
(%o5)                      [a, b , c ]
(%i6) tellsimpafter (foo (aa (xx)), aa (foo (xx)));
(%o6)                   [foorule1, false]
(%i7) foo (bar (u - v));
(%o7)                    bar(foo(u - v))

Правила применяются в том порядке в котором они были определены. Если два правила соответствуют выражению, то первым применяется то, которое было определено раньше.

(%i1) matchdeclare (aa, integerp);
(%o1)                         done
(%i2) tellsimpafter (foo (aa), bar_1 (aa));
(%o2)                   [foorule1, false]
(%i3) tellsimpafter (foo (aa), bar_2 (aa));
(%o3)              [foorule2, foorule1, false]
(%i4) foo (42);
(%o4)                       bar_1(42)

Переменные шаблона являются локальными переменные правил упрощения. (Сравни с функцией defmatch, которая рассматривает переменные шаблона, как глобальные).

(%i1) matchdeclare (aa, integerp, bb, atom);
(%o1)                         done
(%i2) tellsimpafter (foo(aa, bb), bar('aa=aa, 'bb=bb));
(%o2)                   [foorule1, false]
(%i3) bb: 12345;
(%o3)                         12345
(%i4) foo (42, %e);
(%o4)                 bar(aa = 42, bb = %e)
(%i5) bb;
(%o5)                         12345

Как и у всех атомов, свойства переменных шаблона являются глобальными даже если их значение локально. В данном примере свойство объявляется при помощи define_variable. Это свойство атома bb является глобальным.

(%i1) matchdeclare (aa, integerp, bb, atom);
(%o1)                         done
(%i2) tellsimpafter (foo(aa, bb), bar('aa=aa, 'bb=bb));
(%o2)                   [foorule1, false]
(%i3) foo (42, %e);
(%o3)                 bar(aa = 42, bb = %e)
(%i4) define_variable (bb, true, boolean);
(%o4)                         true
(%i5) foo (42, %e);
Error: bb was declared mode boolean, has value: %e
 -- an error.  Quitting.  To debug this try debugmode(true);

Правила именуются по имени основного оператора. Имена правил для встроенных и пользовательских операторов являются Lisp-идентификаторами, тогда как имена других функций являются идентификаторами Maxima.

(%i1) tellsimpafter (foo (%pi + %e), 3*%pi);
(%o1)                   [foorule1, false]
(%i2) tellsimpafter (foo (%pi * %e), 17*%e);
(%o2)              [foorule2, foorule1, false]
(%i3) tellsimpafter (foo (%i ^ %e), -42*%i);
(%o3)         [foorule3, foorule2, foorule1, false]
(%i4) tellsimpafter (foo (9) + foo (13), quux (22));
(%o4)                   [+rule1, simplus]
(%i5) tellsimpafter (foo (9) * foo (13), blurf (22));
(%o5)                  [*rule1, simptimes]
(%i6) tellsimpafter (foo (9) ^ foo (13), mumble (22));
(%o6)                  [^rule1, simpexpt]
(%i7) rules;
(%o7) [foorule1, foorule2, foorule3, +rule1, *rule1, ^rule1]
(%i8) foorule_name: first (%o1);
(%o8)                       foorule1
(%i9) plusrule_name: first (%o4);
(%o9)                        +rule1
(%i10) remrule (foo, foorule1);
(%o10)                         foo
(%i11) remrule ("^", ?\^rule1);
(%o11)                          ^
(%i12) rules;
(%o12)        [foorule2, foorule3, +rule1, *rule1]

Рабочий пример: антикоммутативное умножение.

(%i1) gt (i, j) := integerp(j) and i < j;
(%o1)           gt(i, j) := integerp(j) and i < j
(%i2) matchdeclare (i, integerp, j, gt(i));
(%o2)                         done
(%i3) tellsimpafter (s[i]^^2, 1);
(%o3)                 [^^rule1, simpncexpt]
(%i4) tellsimpafter (s[i] . s[j], -s[j] . s[i]);
(%o4)                   [.rule1, simpnct]
(%i5) s[1] . (s[1] + s[2]);
(%o5)                    s  . (s  + s )
                          1     2    1
(%i6) expand (%);
(%o6)                      1 - s  . s
                                2    1
(%i7) factor (expand (sum (s[i], i, 0, 9)^^5));
(%o7) 100 (s  + s  + s  + s  + s  + s  + s  + s  + s  + s )
            9    8    7    6    5    4    3    2    1    0
Функция: clear_rules ()

Исполняет kill (rules) и обнуляет счетчик, т.е. новое правило будет иметь номер 1 вслед за встроенными правилами для операторов суммы +, умножения * и степени ^.


Next: , Previous: Правила преобразования и шаблоны, Up: Top   [Contents][Index]

35 Списки


Next: , Previous: Списки, Up: Списки   [Contents][Index]

35.1 Ведение в работу со списками

Списки являются основными строительными блоками в Maxima и Lisp. Все типы данных, за исключением массивов, хеш-таблиц и чисел, представлены, как Lisp списки. Эти списки имеют вид

((MPLUS) $A 2)

для обозначения a+2. На уровне Maxima мы увидим в инфиксной нотации a+2. Maxima тоже имеет свои собственные списки, которые печатаются как

[1, 2, 7, x+y]

для списка из 4 элементов. Внутренне, это выражение соответствует Lisp списку

((MLIST) 1  2  7  ((MPLUS)  $X $Y ))

Флаг, который обозначает тип выражения Maxima, сам является списком, и после упрощения, данный список приобретет вид

((MLIST SIMP) 1 2 7 ((MPLUS SIMP) $X $Y))

Previous: Ведение в работу со списками, Up: Списки   [Contents][Index]

35.2 Функции и переменные для работы со списками

Функция: append (list_1, ..., list_n)

Возвращает новый список элементов list_1 с последующими элементами list_2 и т.д. append работает и с выражениями общего вида, например, append (f(a,b), f(c,d,e)); дает f(a,b,c,d,e).

См. example(append); для примера.

Функция: assoc (key, list, default)
Функция: assoc (key, list)

Эта функция ищет ключ key в правых частях списка list, имеющего форму [x,y,z,...], где каждый элемент list есть выражение с бинарным оператором и двумя операндами. Например, x=1, 2^3, [a,b] и т.д. Ключ key сравнивается с первым операндом. Если ключ key найден, то assoc возвращает второй операнд. В противном случае возвращается значение default. Параметр default не обязателен и по умолчанию равен false.

Функция: atom (expr)

Возвращает true если expr является атомарным (т.е. число, имя или строка) и false в противном случае. Т.е. atom(5) равно true, тогда как atom(a[1]) и atom(sin(x)) равны false (предполагая, что a[1] и x не имеют значения).

Функция: cons (expr, list)

Возвращает новый список, составленный из первого элемента равного expr с последующими элементами list. Функция cons работает и с произвольными выражениями, например, cons(x, f(a,b,c)); -> f(x,a,b,c).

Функция: copylist (list)

Возвращает копию списка list.

Функция: create_list (form, x_1, list_1, ..., x_n, list_n)

Создает список, вычисляя выражение form с x_1 последовательно равным элементам list_1, x_2 последовательно равным элементам list_2 и т.д. Общее число элементов в результирующем списке равно произведению числа элементов во всех списках. Каждая переменная x_i должна быть символом. Переменные не вычисляются. Списки вычисляются однажды в начале итерации.

(%i1) create_list(x^i,i,[1,3,7]);
                 3   7
(%o1)       [x, x , x ]

Двойная итерация:

(%i1) create_list([i,j],i,[a,b],j,[e,f,h]);
(%o1) [[a, e], [a, f], [a, h], [b, e], [b, f], [b, h]]

Вместо списка list_i можно использовать два параметра, которые должны иметь числовые значения. Они будут рассматриваться как нижняя и верхняя границы итерации (включительно).

(%i1) create_list([i,j],i,[1,2,3],j,1,i);
(%o1) [[1, 1], [2, 1], [2, 2], [3, 1], [3, 2], [3, 3]]

Отметим, что пределы для переменной j могут зависеть от i.

Функция: delete (expr_1, expr_2)
Функция: delete (expr_1, expr_2, n)

Удаляет все элементы, равные expr_1, из expr_2. При этом expr_1 может быть слагаемым expr_2 (если это сумма) или множителем expr_2 (если это произведение).

(%i1) delete(sin(x), x+sin(x)+y);
(%o1)                         y + x

Вызов delete(expr_1, expr_2, n) удаляет первые n случаев expr_1 из expr_2. Если число включений expr_1 в expr_2 меньше n, то будут удалены все.

(%i1) delete(a, f(a,b,c,d,a));
(%o1)                      f(b, c, d)
(%i2) delete(a, f(a,b,a,c,d,a), 2);
(%o2)                     f(b, c, d, a)

Функция: eighth (expr)

Возвращает восьмой элемент выражения или списка expr. См. first по поводу подробностей.

Функция: endcons (expr, list)

Возвращает новый список, состоящий из элементов list с последующим expr. Функция endcons работает и с общими выражениями, например, endcons(x, f(a,b,c)); -> f(a,b,c,x).

Функция: fifth (expr)

Возвращает пятый элемент выражения или списка expr. См. first по поводу подробностей.

Функция: first (expr)

Возвращает первый элемент expr, что может быть первым элементом списка, первой строкой в матрице, первым слагаемым суммы и т.д. Заметим, что first и другие подобные функции, такие как rest и last, работают с внешней (печатной) формой выражения expr, а не с тем, как это выражение было введено. Если значение inflag равно true, то эти функции будут работать с внутренним представлением выражения expr. Отметим, что упрощатель изменяет порядок членов в выражениях. Так, first(x+y) будет равно x, если inflag равна true, и y, если inflag равна false (first(y+x) даст одинаковый результат в обоих случаях). Функции second .. tenth дают со второго по десятый элемент выражения.

Функция: fourth (expr)

Возвращает четвертый элемент выражения или списка expr. См. first по поводу подробностей.

Функция: get (a, i)

Возвращает определенное пользователем свойство атома a, обозначенное i, или false, если атом не имеет свойства i.

Функция get вычисляет свои аргументы.

(%i1) put (%e, 'transcendental, 'type);
(%o1)                    transcendental
(%i2) put (%pi, 'transcendental, 'type)$
(%i3) put (%i, 'algebraic, 'type)$
(%i4) typeof (expr) := block ([q],
        if numberp (expr)
        then return ('algebraic),
        if not atom (expr)
        then return (maplist ('typeof, expr)),
        q: get (expr, 'type),
        if q=false
        then errcatch (error(expr,"is not numeric.")) else q)$
(%i5) typeof (2*%e + x*%pi);
x is not numeric.
(%o5)  [[transcendental, []], [algebraic, transcendental]]
(%i6) typeof (2*%e + %pi);
(%o6)     [transcendental, [algebraic, transcendental]]

Функция: join (l, m)

Возвращает новый список, состоящий из чередующихся элементов списков l и m. Результат будет иметь вид [l[1], m[1], l[2], m[2], ...]. Списки l и m могут иметь элементы любого типа.

Если списки имеют разную длину, то join отбросит последние элементы более длинного списка.

Ситуация, когда либо l, либо m не является списком, считается ошибкой.

Примеры:

(%i1) L1: [a, sin(b), c!, d - 1];
(%o1)                [a, sin(b), c!, d - 1]
(%i2) join (L1, [1, 2, 3, 4]);
(%o2)          [a, 1, sin(b), 2, c!, 3, d - 1, 4]
(%i3) join (L1, [aa, bb, cc, dd, ee, ff]);
(%o3)        [a, aa, sin(b), bb, c!, cc, d - 1, dd]
Функция: last (expr)

Возвращает последний элемент expr (элемент, слагаемое, множитель, строку и т.п.).

Функция: length (expr)

По умолчанию возвращает число частей внешней (печатной) формы выражения expr. Для списка – это число элементов, для матрицы – число строк, для суммы – число слагаемых (см. dispform).

Результат length зависит от переключателя inflag. Например, length(a/(b*c)); дает 2, если inflag равен false (предполагается, что exptdispflag равна true), и дает 3, если inflag равен true, т.к. внутренние представление есть a*b^-1*c^-1.

Управляющая переменная: listarith

Значение по умолчанию: true Если равна false, то все арифметические операции со списками не работают. Если равна true, то все операции список-матрица вызывают преобразование списков в матрицы и дают результат матричного типа. Однако, операции список-список продолжают давать списки.

Функция: listp (expr)

Возвращает true, если expr является списком и false в противном случае.

Функция: makelist (expr, i, i_0, i_1)
Функция: makelist (expr, x, list)

Создает и возвращает список, каждый элемент которого построен из выражения expr.

Вызов makelist (expr, i, i_0, i_1) возвращает список, с j-м элементом равным ev (expr, i=j) для j, пробегающего значения от i_0 до i_1.

Вызов makelist (expr, x, list) возвращает список, с j-м элементом равным ev (expr, x=list[j]) для j, пробегающего значения от 1 до length (list).

Примеры:

(%i1) makelist(concat(x,i),i,1,6);
(%o1)               [x1, x2, x3, x4, x5, x6]
(%i2) makelist(x=y,y,[a,b,c]);
(%o2)                 [x = a, x = b, x = c]

Функция: member (expr_1, expr_2)

Возвращает true если is(expr_1 = a), для некоторого элемента a из args(expr_2), и false в противном случае.

Обычно, expr_2 является списком. В этом случае args(expr_2) = expr_2 и is(expr_1 = a) для некоторого элемента a из expr_2.

Функция member не анализирует составные части аргументов expr_2, и может возвратить false даже если expr_1 является частью какого-либо из аргументов expr_2.

См. также elementp.

Примеры:

(%i1) member (8, [8, 8.0, 8b0]);
(%o1)                         true
(%i2) member (8, [8.0, 8b0]);
(%o2)                         false
(%i3) member (b, [a, b, c]);
(%o3)                         true
(%i4) member (b, [[a, b], [b, c]]);
(%o4)                         false
(%i5) member ([b, c], [[a, b], [b, c]]);
(%o5)                         true
(%i6) F (1, 1/2, 1/4, 1/8);
                               1  1  1
(%o6)                     F(1, -, -, -)
                               2  4  8
(%i7) member (1/8, %);
(%o7)                         true
(%i8) member ("ab", ["aa", "ab", sin(1), a + b]);
(%o8)                         true
Функция: ninth (expr)

Возвращает девятый элемент выражения или списка expr. См. first по поводу подробностей.

Функция: unique (L)

Возвращает уникальные элементы списка L.

Если все элементы списка L уникальны, то unique возвращает копию верхнего уровня списка L, а не сам список L.

Если L не является списком, то unique возвращает L.

Пример:

(%i1) unique ([1, %pi, a + b, 2, 1, %e, %pi, a + b, [1]]);
(%o1)              [1, 2, %e, %pi, [1], b + a]
Функция: rest (expr, n)
Функция: rest (expr)

Возвращает expr без первых n элементов, если n положительно, или без последних - n элементов, если n отрицательно. Если n равен 1, то он может быть опущен. Выражение expr может быть списком, матрицей или выражением.

Функция: reverse (list)

Изменяет порядок членов list (но не сами члены) на обратный. Функция reverse также работает с выражениями общего вида, например, reverse(a=b); дает b=a.

Функция: second (expr)

Возвращает второй элемент выражения или списка expr. См. first по поводу подробностей.

Функция: seventh (expr)

Возвращает седьмой элемент выражения или списка expr. См. first по поводу подробностей.

Функция: sixth (expr)

Возвращает шестой элемент выражения или списка expr. См. first по поводу подробностей.

Функция: sublist_indices (L, P)

Возвращает список индексов элементов x списка L, для которых предикат maybe(P(x)) возвращает true, за исключением элементов unknown и false. Параметр P может быть именем функции или лямбда-выражением. Параметр L должен быть списком.

Примеры:

(%i1) sublist_indices ('[a, b, b, c, 1, 2, b, 3, b],
                       lambda ([x], x='b));
(%o1)                     [2, 3, 7, 9]
(%i2) sublist_indices ('[a, b, b, c, 1, 2, b, 3, b], symbolp);
(%o2)                  [1, 2, 3, 4, 7, 9]
(%i3) sublist_indices ([1 > 0, 1 < 0, 2 < 1, 2 > 1, 2 > 0],
                       identity);
(%o3)                       [1, 4, 5]
(%i4) assume (x < -1);
(%o4)                       [x < - 1]
(%i5) map (maybe, [x > 0, x < 0, x < -2]);
(%o5)                [false, true, unknown]
(%i6) sublist_indices ([x > 0, x < 0, x < -2], identity);
(%o6)                          [2]
Функция: tenth (expr)

Возвращает десятый элемент выражения или списка expr. См. first по поводу подробностей.

Функция: third (expr)

Возвращает третий элемент выражения или списка expr. См. first по поводу подробностей.


Next: , Previous: Списки, Up: Top   [Contents][Index]

36 Множества


Next: , Previous: Множества, Up: Множества   [Contents][Index]

36.1 Введение в работу с множествами

Maxima предоставляет функции, такие как пересечение или объединение, для работы с конечными множествами, определяемыми перечислением элементов. Maxima трактует списки и множества как различные объекты. Это позволяет работать с множествами, элементами которых сами могут быть списками или множествами.

В дополнение к функциям для работы конечными множествами Maxima определяет некоторые функции, относящиеся к комбинаторике, что включает: числа Стирлинга первого и второго рода, числа Белла, мультиномиальные коэффициенты, разбиения неотрицательных целых чисел и некоторые другие. Maxima также определяет дельта-функцию Кронекера.

36.1.1 Использование

Для того, чтобы задать множество с элементами a_1, ..., a_n, следует написать set(a_1, ..., a_n) или {a_1, ..., a_n}; для пустого множества надо написать set() или {}. При вводе формы set(...) и { ... } эквивалентны. При выводе множества всегда печатаются с фигурными скобками.

Если элемент множества присутствует более одного раза, то упрощение удалит повторяющиеся элементы.

(%i1) set();
(%o1)                          {}
(%i2) set(a, b, a);
(%o2)                        {a, b}
(%i3) set(a, set(b));
(%o3)                       {a, {b}}
(%i4) set(a, [b]);
(%o4)                       {a, [b]}
(%i5) {};
(%o5)                          {}
(%i6) {a, b, a};
(%o6)                        {a, b}
(%i7) {a, {b}};
(%o7)                       {a, {b}}
(%i8) {a, [b]};
(%o8)                       {a, [b]}

Два элемента x и y являются повторяющимися (т.е. рассматриваются совпадающими с точки зрения включения в множество), тогда и только тогда, когда is(x = y) дает true. Заметим, что is(equal(x, y)) может давать true, тогда как is(x = y) дает false. В этом случае элементы x и y считаются различными.

(%i1) x: a/c + b/c;
                              b   a
(%o1)                         - + -
                              c   c
(%i2) y: a/c + b/c;
                              b   a
(%o2)                         - + -
                              c   c
(%i3) z: (a + b)/c;
                              b + a
(%o3)                         -----
                                c
(%i4) is (x = y);
(%o4)                         true
(%i5) is (y = z);
(%o5)                         false
(%i6) is (equal (y, z));
(%o6)                         true
(%i7) y - z;
                           b + a   b   a
(%o7)                    - ----- + - + -
                             c     c   c
(%i8) ratsimp (%);
(%o8)                           0
(%i9) {x, y, z};
                          b + a  b   a
(%o9)                    {-----, - + -}
                            c    c   c

Для того, чтобы создать множество из элементов списка, используется setify.

(%i1) setify ([b, a]);
(%o1)                        {a, b}

Элементы множества x и y равны если is(x = y) вычисляется в true. Тогда rat(x) и x являются равными элементами множества, и, следовательно

(%i1) {x, rat(x)};
(%o1)                          {x}

Далее, поскольку is((x - 1)*(x + 1) = x^2 - 1) вычисляется в false, то (x - 1)*(x + 1) и x^2 - 1 есть различные элементы, и

(%i1) {(x - 1)*(x + 1), x^2 - 1};
                                       2
(%o1)               {(x - 1) (x + 1), x  - 1}

Для приведения этого множества к одноэлементному следует применить rat к каждому элементу:

(%i1) {(x - 1)*(x + 1), x^2 - 1};
                                       2
(%o1)               {(x - 1) (x + 1), x  - 1}
(%i2) map (rat, %);
                              2
(%o2)/R/                    {x  - 1}

Для удаления повторов из множеств другого вида может потребоваться применение других упрощающих функций. Вот пример, использующий trigsimp:

(%i1) {1, cos(x)^2 + sin(x)^2};
                            2         2
(%o1)                {1, sin (x) + cos (x)}
(%i2) map (trigsimp, %);
(%o2)                          {1}

Множество является упрощенным, если его элементы не повторяются и упорядочены. Текущая реализация Maxima функций для работы с множествами использует функцию orderlessp для упорядочения, однако будущие версии могут использовать другую упорядочивающую функцию.

Некоторые операции над множествами, такие как подстановки, вызывают автоматическое упрощение. Например,

(%i1) s: {a, b, c}$
(%i2) subst (c=a, s);
(%o2)                        {a, b}
(%i3) subst ([a=x, b=x, c=x], s);
(%o3)                          {x}
(%i4) map (lambda ([x], x^2), set (-1, 0, 1));
(%o4)                        {0, 1}

Maxima рассматривает списки и множества как различные объекты; функции, подобные union и intersection, сигнализируют об ошибке если их аргументы не являются множествами. Если необходимо применить функцию для работы с множествами к списку, то надо сначала использовать setify для преобразования списка в множество. Таким образом

(%i1) union ([1, 2], {a, b});
Function union expects a set, instead found [1,2]
 -- an error.  Quitting.  To debug this try debugmode(true);
(%i2) union (setify ([1, 2]), {a, b});
(%o2)                     {1, 2, a, b}

Для того, чтобы получить все элементы множества s, удовлетворяющие предикату f, используйте subset(s, f) (предикат – функция, дающая логическое значение). Например, чтобы найти в заданном множестве уравнения, которые не зависят от переменной z, используйте

(%i1) subset ({x + y + z, x - y + 4, x + y - 5},
                                    lambda ([e], freeof (z, e)));
(%o1)               {- y + x + 4, y + x - 5}

Раздел Функции и переменные для работы с множествами содержит полный список функций Maxima, предназначенных для работы с множествами.

36.1.2 Итерация по элементам множества

Существует два способа организации цикла по элементам множества. Один способ – использовать map, например:

(%i1) map (f, {a, b, c});
(%o1)                  {f(a), f(b), f(c)}

Другой способ – использовать for x in s do

(%i1) s: {a, b, c};
(%o1)                       {a, b, c}
(%i2) for si in s do print (concat (si, 1));
a1 
b1 
c1 
(%o2)                         done

Maxima функции first и rest правильно работают с множествами. Примененная к множеству, first возвращает первый элемент множества, какой именно – может зависеть от реализации. Если s является множеством, то rest(s) эквивалентно disjoin(first(s), s). В настоящий момент есть другие функции Maxima, корректно работающие с множествами. В будущих версиях функции first и rest могут работать на множествах иначе или не работать вовсе.

36.1.3 Ошибки

Функции для работы с множествами используют Maxima функцию orderlessp для сортировки элементов множества и Lisp функцию like для проверки равенства элементов. Обе эти функции имеют известные ошибки, которые проявляются при попытке использовать множества, элементы которых являются списками или матрицами, включающими выражения в канонической рациональной форме (КРВ). Например

(%i1) {[x], [rat (x)]};
Maxima encountered a Lisp error:

  The value #:X1440 is not of type LIST.

Automatically continuing.
To reenable the Lisp debugger set *debugger-hook* to nil.

Это выражение вызывает ошибку (сообщение об ошибке зависит от версии Lisp и Maxima). Другой пример

(%i1) setify ([[rat(a)], [rat(b)]]);
Maxima encountered a Lisp error:

  The value #:A1440 is not of type LIST.

Automatically continuing.
To reenable the Lisp debugger set *debugger-hook* to nil.

Эти ошибки вызваны ошибками в orderlessp и like, а не ошибками в реализации функций работы с множествами. Для иллюстрации попробуем следующие выражения

(%i1) orderlessp ([rat(a)], [rat(b)]);
Maxima encountered a Lisp error:

  The value #:B1441 is not of type LIST.

Automatically continuing.
To reenable the Lisp debugger set *debugger-hook* to nil.
(%i2) is ([rat(a)] = [rat(a)]);
(%o2)                         false

До тех пор, пока эти ошибки не исправлены, не следует использовать множества с элементами в виде списков и матриц, содержащих выражения в формате КРВ. Множества, просто содержащие выражения КРВ в качестве элементов, не создают проблем.

(%i1) {x, rat (x)};
(%o1)                          {x}

Maxima функция orderlessp имеет еще одну ошибку, которая может создать проблемы при работе с множествами. А именно, упорядочивающий предикат orderlessp не является транзитивным. Простейший известный пример, демонстрирующий это

(%i1) q: x^2$
(%i2) r: (x + 1)^2$
(%i3) s: x*(x + 2)$
(%i4) orderlessp (q, r);
(%o4)                         true
(%i5) orderlessp (r, s);
(%o5)                         true
(%i6) orderlessp (q, s);
(%o6)                         false

Эта ошибка вызывает проблемы со всеми функциями для работы с множествами и даже с другими функциями Maxima. Возможно, но точно не известно, что эту ошибку можно обойти, если все элементы множества или являются КРВ, или упрощены с помощью ratsimp.

Механизмы Maxima orderless и ordergreat не совместимы с функциями для работы с множествами. Если требуется использовать либо orderless, либо ordergreat, то следует вызывать эти функции до формирования множеств, и не следует использовать unorder.

Если вы встретите что-то, что может быть ошибкой в функциях работы с множествами, пожалуйста, сообщите об этом в базу данных ошибок Maxima. См. bug_report.

36.1.4 Авторы

Функции для работы с множествами Maxima и документация к ним написаны Ставросом Макракисом (Stavros Macrakis of Cambridge, Massachusetts) и Бартоном Уиллисом (Barton Willis of the University of Nebraska at Kearney (UNK)).


Previous: Введение в работу с множествами, Up: Множества   [Contents][Index]

36.2 Функции и переменные для работы с множествами

Функция: adjoin (x, a)

Возвращает объединение множества a с {x}.

Функция adjoin вызывает ошибку, если a не является множеством.

Вызовы adjoin(x, a) и union(set(x), a) эквивалентны, однако adjoin может быть несколько быстрее, чем union.

См. также disjoin.

Примеры:

(%i1) adjoin (c, {a, b});
(%o1)                       {a, b, c}
(%i2) adjoin (a, {a, b});
(%o2)                        {a, b}
Функция: belln (n)

Представляет n-ое число Белла. belln(n) есть число разбиений множества с n элементами.

Для неотрицательного целого n, belln(n) упрощается в n-ое число Белла. Для других значений аргумента belln не упрощается.

Функция belln дистрибутивна по отношению к уравнениям, спискам, матрицам и множествам.

Примеры:

Функция belln, примененная к неотрицательным целым числам.

(%i1) makelist (belln (i), i, 0, 6);
(%o1)               [1, 1, 2, 5, 15, 52, 203]
(%i2) is (cardinality (set_partitions ({})) = belln (0));
(%o2)                         true
(%i3) is (cardinality (set_partitions ({1, 2, 3, 4, 5, 6})) =
                       belln (6));
(%o3)                         true

Функция belln, примененная к аргументам, не являющимися неотрицательными целыми числами.

(%i1) [belln (x), belln (sqrt(3)), belln (-9)];
(%o1)        [belln(x), belln(sqrt(3)), belln(- 9)]
Функция: cardinality (a)

Возвращает число различных элементов множества a.

Функция cardinality игнорирует повторяющиеся элементы даже если упрощение отключено.

Примеры:

(%i1) cardinality ({});
(%o1)                           0
(%i2) cardinality ({a, a, b, c});
(%o2)                           3
(%i3) simp : false;
(%o3)                         false
(%i4) cardinality ({a, a, b, c});
(%o4)                           3
Функция: cartesian_product (b_1, ... , b_n)

Возвращает множество списков формы [x_1, ..., x_n], где x_1, ..., x_n есть элементы множеств b_1, ... , b_n соответственно.

Функция cartesian_product вызывает ошибку, если хотя бы один из ее аргументов не является множеством.

Примеры:

(%i1) cartesian_product ({0, 1});
(%o1)                      {[0], [1]}
(%i2) cartesian_product ({0, 1}, {0, 1});
(%o2)           {[0, 0], [0, 1], [1, 0], [1, 1]}
(%i3) cartesian_product ({x}, {y}, {z});
(%o3)                      {[x, y, z]}
(%i4) cartesian_product ({x}, {-1, 0, 1});
(%o4)              {[x, - 1], [x, 0], [x, 1]}
Функция: disjoin (x, a)

Возвращает множество a без элемента x. Если x не является элементом a, то a возвращается неизменным.

Функция disjoin вызывает ошибку, если a не является множеством.

disjoin(x, a), delete(x, a) и setdifference(a, set(x)) эквивалентны. Из этих вариантов disjoin обычно быстрее других.

Примеры:

(%i1) disjoin (a, {a, b, c, d});
(%o1)                       {b, c, d}
(%i2) disjoin (a + b, {5, z, a + b, %pi});
(%o2)                      {5, %pi, z}
(%i3) disjoin (a - b, {5, z, a + b, %pi});
(%o3)                  {5, %pi, b + a, z}
Функция: disjointp (a, b)

Возвращает true тогда и только тогда, когда множества a и b не пересекаются.

Функция disjointp вызывает ошибку, если a или b не являются множествами.

Примеры:

(%i1) disjointp ({a, b, c}, {1, 2, 3});
(%o1)                         true
(%i2) disjointp ({a, b, 3}, {1, 2, 3});
(%o2)                         false
Функция: divisors (n)

Представляет множество делителей n.

Функция divisors(n) упрощается до множества целых чисел, при этом n является ненулевым целым числом. Множество делителей включает 1 и n. Делители отрицательного числа совпадают с таковыми для его абсолютного значения.

Функция divisors дистрибутивна по отношению к уравнениям, спискам, матрицам и множествам.

Примеры:

Мы можем проверить, что число 28 является совершенным, т.е. сумма делителей, за исключением самого числа, равна 28.

(%i1) s: divisors(28);
(%o1)                 {1, 2, 4, 7, 14, 28}
(%i2) lreduce ("+", args(s)) - 28;
(%o2)                          28

Функция divisors является упрощающей. Подстановка 8 для a в divisors(a) дает делители без перевычисления divisors(8).

(%i1) divisors (a);
(%o1)                      divisors(a)
(%i2) subst (8, a, %);
(%o2)                     {1, 2, 4, 8}

Функция divisors дистрибутивна по отношению к уравнениям, спискам, матрицам и множествам.

(%i1) divisors (a = b);
(%o1)               divisors(a) = divisors(b)
(%i2) divisors ([a, b, c]);
(%o2)        [divisors(a), divisors(b), divisors(c)]
(%i3) divisors (matrix ([a, b], [c, d]));
                  [ divisors(a)  divisors(b) ]
(%o3)             [                          ]
                  [ divisors(c)  divisors(d) ]
(%i4) divisors ({a, b, c});
(%o4)        {divisors(a), divisors(b), divisors(c)}
Функция: elementp (x, a)

Возвращает true тогда и только тогда, когда x является элементом множества a.

Функция elementp вызывает ошибку, если a не является множеством.

Примеры:

(%i1) elementp (sin(1), {sin(1), sin(2), sin(3)});
(%o1)                         true
(%i2) elementp (sin(1), {cos(1), cos(2), cos(3)});
(%o2)                         false
Функция: emptyp (a)

Возвращает true тогда и только тогда, когда a есть пустое множество или список.

Примеры:

(%i1) map (emptyp, [{}, []]);
(%o1)                     [true, true]
(%i2) map (emptyp, [a + b, {{}}, %pi]);
(%o2)                 [false, false, false]
Функция: equiv_classes (s, F)

Возвращает множество классов эквивалентности множества s по отношению эквивалентности F.

F – есть функция двух переменных, определенная на Декартовом произведении s на s. Возвращаемое F значение есть true или false, либо выражение expr такое, что is(expr) дает true или false.

Если F не является отношением эквивалентности, то equiv_classes применит его без возражения, но результат будет скорее всего неправильным.

Примеры:

Отношение эквивалентности является лямбда-выражением, возвращающим true или false.

(%i1) equiv_classes ({1, 1.0, 2, 2.0, 3, 3.0},
                        lambda ([x, y], is (equal (x, y))));
(%o1)            {{1, 1.0}, {2, 2.0}, {3, 3.0}}

Отношение эквивалентности есть имя реляционной функции is, дающей true или false.

(%i1) equiv_classes ({1, 1.0, 2, 2.0, 3, 3.0}, equal);
(%o1)            {{1, 1.0}, {2, 2.0}, {3, 3.0}}

Классы эквивалентности – числа отличающиеся на несколько чисел 3.

(%i1) equiv_classes ({1, 2, 3, 4, 5, 6, 7},
                     lambda ([x, y], remainder (x - y, 3) = 0));
(%o1)              {{1, 4, 7}, {2, 5}, {3, 6}}
Функция: every (f, s)
Функция: every (f, L_1, ..., L_n)

Возвращает true, если предикат f дает true для всех аргументов.

Если второй аргумент является множеством, то every(f, s) возвращает true, если is(f(a_i)) возвращает true для всех a_i в s. every может вычислять f для всех a_i в s, а может и не для всех. Т.к. множества не упорядочены, то every может вычислять f(a_i) в произвольном порядке.

Примененная к одному или нескольким спискам, every(f, L_1, ..., L_n) возвращает true, если is(f(x_1, ..., x_n)) возвращает true для всех x_1, ..., x_n в L_1, ..., L_n соответственно. every может вычислять f для всех комбинаций x_1, ..., x_n, а может и не для всех. every вычисляет списки в порядке возрастания индекса.

Для пустого множества {} и пустого списка [] every возвращает false.

Если глобальный флаг maperror равен true, то все списки L_1, ..., L_n должны иметь одинаковую длину. Если maperror равен false, то списки обрезаются до длины самого короткого.

Значение предиката f, который вычисляется посредством is в значение, отличное от true или false, управляется глобальным флагом prederror. Если prederror равен true, то данные значения рассматриваются как false, и возвращаемое every значение есть false. Если prederror равен false, то такие значения рассматриваются как unknown, и возвращаемое every значение равно unknown.

Примеры:

every, примененная к одному списку. Предикат является функцией одного аргумента.

(%i1) every (integerp, {1, 2, 3, 4, 5, 6});
(%o1)                         true
(%i2) every (atom, {1, 2, sin(3), 4, 5 + y, 6});
(%o2)                         false

every, примененная к двум спискам. Предикат – функция двух аргументов.

(%i1) every ("=", [a, b, c], [a, b, c]);
(%o1)                         true
(%i2) every ("#", [a, b, c], [a, b, c]);
(%o2)                         false

Значение предиката f, вычисляемого в значение, отличное от true или false, управляется глобальным флагом prederror.

(%i1) prederror : false;
(%o1)                         false
(%i2) map (lambda ([a, b], is (a < b)), [x, y, z],
                   [x^2, y^2, z^2]);
(%o2)              [unknown, unknown, unknown]
(%i3) every ("<", [x, y, z], [x^2, y^2, z^2]);
(%o3)                        unknown
(%i4) prederror : true;
(%o4)                         true
(%i5) every ("<", [x, y, z], [x^2, y^2, z^2]);
(%o5)                         false
Функция: extremal_subset (s, f, max)
Функция: extremal_subset (s, f, min)

Возвращает подмножество s, на котором функция f принимает минимальное или максимальное значение.

extremal_subset(s, f, max) возвращает подмножество множества или списка s, для которого вещественнозначная функция f принимает максимальное значение.

extremal_subset(s, f, min) возвращает подмножество множества или списка s, для которого вещественнозначная функция f принимает минимальное значение.

Примеры:

(%i1) extremal_subset ({-2, -1, 0, 1, 2}, abs, max);
(%o1)                       {- 2, 2}
(%i2) extremal_subset ({sqrt(2), 1.57, %pi/2}, sin, min);
(%o2)                       {sqrt(2)}
Функция: flatten (expr)

Собирает аргументы подвыражений, имеющих оператор верхнего уровня такой же как у expr, и строит выражение из этих собранных аргументов.

Аргументы, имеющие оператор верхнего уровня отличный от главного оператора expr, копируются без модификации даже если они, в свою очередь, имеют некоторые подвыражения с главным оператором expr.

Возможно, что flatten построит выражение с числом аргументов недопустимым для данного типа оператора, что может привести к ошибке упрощателя или вычислителя. Функция flatten не пытается определить подобные ситуации.

Выражения, имеющие специальные представления, например, канонические рациональные выражения (КРВ), не обрабатываются flatten. В этом случае flatten возвращает аргумент без изменения.

Примеры:

Примененная к списку, flatten собирает все элементы, являющиеся списками.

(%i1) flatten ([a, b, [c, [d, e], f], [[g, h]], i, j]);
(%o1)            [a, b, c, d, e, f, g, h, i, j]

Примененная к множеству, flatten собирает все элементы, являющиеся множествами.

(%i1) flatten ({a, {b}, {{c}}});
(%o1)                       {a, b, c}
(%i2) flatten ({a, {[a], {a}}});
(%o2)                       {a, [a]}

Функция flatten похожа на объявление оператора n-арным. Однако flatten не влияет на подвыражения, имеющие оператор, отличный от главного оператора выражения, тогда как декларация оператора n-арным действует на них.

(%i1) expr: flatten (f (g (f (f (x)))));
(%o1)                     f(g(f(f(x))))
(%i2) declare (f, nary);
(%o2)                         done
(%i3) ev (expr);
(%o3)                      f(g(f(x)))

flatten трактует функции с индексом также как любые другие операторы.

(%i1) flatten (f[5] (f[5] (x, y), z));
(%o1)                      f (x, y, z)
                            5

Функция flatten может составить выражение, в котором число аргументов отличается от объявленного числа аргументов оператора.

(%i1) 'mod (5, 'mod (7, 4));
(%o1)                   mod(5, mod(7, 4))
(%i2) flatten (%);
(%o2)                     mod(5, 7, 4)
(%i3) ''%, nouns;
Wrong number of arguments to mod
 -- an error.  Quitting.  To debug this try debugmode(true);
Функция: full_listify (a)

Заменяет в a все множества на списки и возвращает результат. full_listify заменяет операторы множества на операторы списка во вложенных подвыражениях, даже если главный оператор не есть set.

Функция listify заменяет только главный оператор.

Примеры:

(%i1) full_listify ({a, b, {c, {d, e, f}, g}});
(%o1)               [a, b, [c, [d, e, f], g]]
(%i2) full_listify (F (G ({a, b, H({c, d, e})})));
(%o2)              F(G([a, b, H([c, d, e])]))
Функция: fullsetify (a)

Если a является списком, то fullsetify заменяет оператор списка на оператор множества и применяет fullsetify ко всем членам этого множества. Если аргумент a не является списком, то он возвращается неизменным.

Функция setify заменяет только главный оператор.

Примеры:

В строке (%o2) аргумент f не преобразован в множество, т.к. главный оператор не является списком f([b]).

(%i1) fullsetify ([a, [a]]);
(%o1)                       {a, {a}}
(%i2) fullsetify ([a, f([b])]);
(%o2)                      {a, f([b])}
Функция: identity (x)

Возвращает x для любого аргумента x.

Примеры:

Функция identity может использоваться как предикат, если параметры уже являются логическими значениями.

(%i1) every (identity, [true, true]);
(%o1)                         true
Функция: integer_partitions (n)
Функция: integer_partitions (n, len)

Возвращает целочисленные разбиения n, т.е. списки целых чисел, сумма которых равна n.

Функция integer_partitions(n) возвращает множество всех разбиений n. Каждое разбиение есть список, отсортированный от большего значения к меньшему.

Вызов integer_partitions(n, len) возвращает все разбиения длины len или менее. В этом случае к разбиениям, имеющим число членов меньшее, чем len, добавляются нули, чтобы сделать все возвращаемые разбиения одинаковой длины len.

Список [a_1, ..., a_m] есть разбиение неотрицательного целого числа n, если (1) каждое a_i есть ненулевое положительное число и (2) a_1 + ... + a_m = n. Таким образом, 0 не имеет разбиений.

Примеры:

(%i1) integer_partitions (3);
(%o1)               {[1, 1, 1], [2, 1], [3]}
(%i2) s: integer_partitions (25)$
(%i3) cardinality (s);
(%o3)                         1958
(%i4) map (lambda ([x], apply ("+", x)), s);
(%o4)                         {25}
(%i5) integer_partitions (5, 3);
(%o5) {[2, 2, 1], [3, 1, 1], [3, 2, 0], [4, 1, 0], [5, 0, 0]}
(%i6) integer_partitions (5, 2);
(%o6)               {[3, 2], [4, 1], [5, 0]}

Для того, чтобы найти все разбиения, удовлетворяющие определенному условию, можно использовать функцию subset. В следующем примере находятся все разбиения 10, состоящие из простых чисел.

(%i1) s: integer_partitions (10)$
(%i2) cardinality (s);
(%o2)                          42
(%i3) xprimep(x) := integerp(x) and (x > 1) and primep(x)$
(%i4) subset (s, lambda ([x], every (xprimep, x)));
(%o4) {[2, 2, 2, 2, 2], [3, 3, 2, 2], [5, 3, 2], [5, 5], [7, 3]}
Функция: intersect (a_1, ..., a_n)

Функция intersect идентична intersection.

Функция: intersection (a_1, ..., a_n)

Возвращает множество, содержащие элементы, общие для всех множеств a_1, ..., a_n.

Функция intersection вызывает ошибку, если хотя бы один из аргументов не является множеством.

Примеры:

(%i1) S_1 : {a, b, c, d};
(%o1)                     {a, b, c, d}
(%i2) S_2 : {d, e, f, g};
(%o2)                     {d, e, f, g}
(%i3) S_3 : {c, d, e, f};
(%o3)                     {c, d, e, f}
(%i4) S_4 : {u, v, w};
(%o4)                       {u, v, w}
(%i5) intersection (S_1, S_2);
(%o5)                          {d}
(%i6) intersection (S_2, S_3);
(%o6)                       {d, e, f}
(%i7) intersection (S_1, S_2, S_3);
(%o7)                          {d}
(%i8) intersection (S_1, S_2, S_3, S_4);
(%o8)                          {}
Функция: kron_delta (x, y)

Дельта-функция Кронекера.

kron_delta упрощается в 1, если x и y идентичны или очевидно эквивалентны, и упрощается в 0, если x и y очевидно не эквивалентны. Иначе, если эквивалентность или неэквивалентность x и y не ясна, то kron_delta упрощается в невычисляемую форму (noun). По отношению к числам с плавающей точкой kron_delta реализует осторожный подход. Если разница x - y является числом с плавающей точкой, то kron_delta упрощается в невычисляемую форму, даже когда x по-видимому эквивалентно y.

Функция kron_delta(x, y) упрощается в 1, если is(x = y) равно true. kron_delta тоже упрощается в 1, если sign(abs(x - y)) есть zero и x - y не является числом с плавающей точкой (ни обычное число с плавающей точкой, ни число с плавающей точкой повышенной точности). kron_delta упрощается в 0, если sign(abs(x - y)) равно pos.

Если же sign(abs(x - y)) дает что-то отличное от pos или zero, или zero но x - y есть число с плавающей точкой, то kron_delta возвращает невычисляемое выражение.

Функция kron_delta объявлена симметричной. Т.е. kron_delta(x, y) равно kron_delta(y, x).

Примеры:

Аргументы kron_delta идентичны. kron_delta упрощается в 1.

(%i1) kron_delta (a, a);
(%o1)                           1
(%i2) kron_delta (x^2 - y^2, x^2 - y^2);
(%o2)                           1
(%i3) float (kron_delta (1/10, 0.1));
(%o3)                           1

Аргументы kron_delta эквивалентны, и их разница не есть число с плавающей точкой. kron_delta упрощается в 1.

(%i1) assume (equal (x, y));
(%o1)                     [equal(x, y)]
(%i2) kron_delta (x, y);
(%o2)                           1

Аргументы kron_delta не эквивалентны. kron_delta упрощается в 0.

(%i1) kron_delta (a + 1, a);
(%o1)                           0
(%i2) assume (a > b)$
(%i3) kron_delta (a, b);
(%o3)                           0
(%i4) kron_delta (1/5, 0.7);
(%o4)                           0

Аргументы kron_delta могут быть, а могут и не быть эквивалентны. kron_delta упрощается в невычисляемое выражение.

(%i1) kron_delta (a, b);
(%o1)                   kron_delta(a, b)
(%i2) assume(x >= y)$
(%i3) kron_delta (x, y);
(%o3)                   kron_delta(x, y)

Аргументы kron_delta эквивалентны, но их разница является числом с плавающей точкой. kron_delta упрощается в невычисляемое выражение.

(%i1) 1/4 - 0.25;
(%o1)                          0.0
(%i2) 1/10 - 0.1;
(%o2)                          0.0
(%i3) 0.25 - 0.25b0;
Warning:  Float to bigfloat conversion of 0.25
(%o3)                         0.0b0
(%i4) kron_delta (1/4, 0.25);
                                  1
(%o4)                  kron_delta(-, 0.25)
                                  4
(%i5) kron_delta (1/10, 0.1);
                                  1
(%o5)                  kron_delta(--, 0.1)
                                  10
(%i6) kron_delta (0.25, 0.25b0);
Warning:  Float to bigfloat conversion of 0.25
(%o6)               kron_delta(0.25, 2.5b-1)

Функция kron_delta симметрична.

(%i1) kron_delta (x, y);
(%o1)                   kron_delta(x, y)
(%i2) kron_delta (y, x);
(%o2)                   kron_delta(x, y)
(%i3) kron_delta (x, y) - kron_delta (y, x);
(%o3)                           0
(%i4) is (equal (kron_delta (x, y), kron_delta (y, x)));
(%o4)                         true
(%i5) is (kron_delta (x, y) = kron_delta (y, x));
(%o5)                         true
Функция: listify (a)

Возвращает список с элементами a, если a есть множество. В противном случае listify возвращает a.

Функция full_listify заменяет все операторы множества в a на операторы списка.

Примеры:

(%i1) listify ({a, b, c, d});
(%o1)                     [a, b, c, d]
(%i2) listify (F ({a, b, c, d}));
(%o2)                    F({a, b, c, d})
Функция: lreduce (F, s)
Функция: lreduce (F, s, s_0)

Расширяет бинарную функцию F до n-арной методом композиции. Аргумент s является списком.

lreduce(F, s) возвращает F(... F(F(s_1, s_2), s_3), ... s_n). Если присутствует необязательный аргумент s_0, то результат эквивалентен lreduce(F, cons(s_0, s)).

Функция F сначала применяется к левой паре элементов списка, откуда происходит название "lreduce" (left reduce).

См. также rreduce, xreduce и tree_reduce.

Примеры:

lreduce без необязательного аргумента.

(%i1) lreduce (f, [1, 2, 3]);
(%o1)                     f(f(1, 2), 3)
(%i2) lreduce (f, [1, 2, 3, 4]);
(%o2)                  f(f(f(1, 2), 3), 4)

lreduce с необязательным аргументом.

(%i1) lreduce (f, [1, 2, 3], 4);
(%o1)                  f(f(f(4, 1), 2), 3)

lreduce примененная к встроенным бинарным операторам. / – есть оператор деления.

(%i1) lreduce ("^", args ({a, b, c, d}));
                               b c d
(%o1)                       ((a ) )
(%i2) lreduce ("/", args ({a, b, c, d}));
                                a
(%o2)                         -----
                              b c d
Функция: makeset (expr, x, s)

Возвращает множество с элементами, сгенерированными из выражения expr, где x есть список переменных expr, а s есть множество или список списков. Для определения элемента результирующего списка выражение expr вычисляется при переменных x, равным значениям из s (параллельное присваивание).

Каждый член s должен иметь ту же длину, что и x. Список переменных x должен быть списком символов без индексов. Даже если символ только один, то x должен быть одноэлементным списком, а каждый член s должен быть одноэлементным списком.

См. также makelist.

Примеры:

(%i1) makeset (i/j, [i, j], [[1, a], [2, b], [3, c], [4, d]]);
                           1  2  3  4
(%o1)                     {-, -, -, -}
                           a  b  c  d
(%i2) S : {x, y, z}$
(%i3) S3 : cartesian_product (S, S, S);
(%o3) {[x, x, x], [x, x, y], [x, x, z], [x, y, x], [x, y, y], 
[x, y, z], [x, z, x], [x, z, y], [x, z, z], [y, x, x], 
[y, x, y], [y, x, z], [y, y, x], [y, y, y], [y, y, z], 
[y, z, x], [y, z, y], [y, z, z], [z, x, x], [z, x, y], 
[z, x, z], [z, y, x], [z, y, y], [z, y, z], [z, z, x], 
[z, z, y], [z, z, z]}
(%i4) makeset (i + j + k, [i, j, k], S3);
(%o4) {3 x, 3 y, y + 2 x, 2 y + x, 3 z, z + 2 x, z + y + x, 
                                       z + 2 y, 2 z + x, 2 z + y}
(%i5) makeset (sin(x), [x], {[1], [2], [3]});
(%o5)               {sin(1), sin(2), sin(3)}
Функция: moebius (n)

Представляет функцию Мебиуса.

Если n есть произведение k различных простых чисел, то moebius(n) упрощается до (-1)^k. Если n = 1, то функция упрощается в 1. Для всех остальных положительных целых функция упрощается в 0.

Функция moebius дистрибутивна по отношению к уравнениям, спискам, матрицам и множествам.

Примеры:

(%i1) moebius (1);
(%o1)                           1
(%i2) moebius (2 * 3 * 5);
(%o2)                          - 1
(%i3) moebius (11 * 17 * 29 * 31);
(%o3)                           1
(%i4) moebius (2^32);
(%o4)                           0
(%i5) moebius (n);
(%o5)                      moebius(n)
(%i6) moebius (n = 12);
(%o6)                    moebius(n) = 0
(%i7) moebius ([11, 11 * 13, 11 * 13 * 15]);
(%o7)                      [- 1, 1, 1]
(%i8) moebius (matrix ([11, 12], [13, 14]));
                           [ - 1  0 ]
(%o8)                      [        ]
                           [ - 1  1 ]
(%i9) moebius ({21, 22, 23, 24});
(%o9)                      {- 1, 0, 1}
Функция: multinomial_coeff (a_1, ..., a_n)
Функция: multinomial_coeff ()

Возвращает мультиномиальный коэффициент.

Если каждое a_k есть неотрицательное целое число, то мультиномиальный коэффициент дает число способов положить a_1 + ... + a_n различных объектов в n ящиков с a_k элементами в k-ом ящике. В целом, multinomial_coeff (a_1, ..., a_n) равна (a_1 + ... + a_n)!/(a_1! ... a_n!).

multinomial_coeff() (без аргументов) дает 1.

minfactorial может упрощать значения, возвращаемые multinomial_coeff.

Примеры:

(%i1) multinomial_coeff (1, 2, x);
                            (x + 3)!
(%o1)                       --------
                              2 x!
(%i2) minfactorial (%);
                     (x + 1) (x + 2) (x + 3)
(%o2)                -----------------------
                                2
(%i3) multinomial_coeff (-6, 2);
                             (- 4)!
(%o3)                       --------
                            2 (- 6)!
(%i4) minfactorial (%);
(%o4)                          10
Функция: num_distinct_partitions (n)
Функция: num_distinct_partitions (n, list)

Возвращает число целочисленных разбиений с различными частями для n, если n – неотрицательное целое. Иначе num_distinct_partitions возвращает невычисляемую форму.

num_distinct_partitions(n, list) возвращает список чисел целочисленных разбиений с различными частями для 1, 2, 3, ..., n .

Разбиение числа n с различными частями есть список различных положительных целых k_1, ..., k_m, таких что n = k_1 + ... + k_m.

Примеры:

(%i1) num_distinct_partitions (12);
(%o1)                          15
(%i2) num_distinct_partitions (12, list);
(%o2)      [1, 1, 1, 2, 2, 3, 4, 5, 6, 8, 10, 12, 15]
(%i3) num_distinct_partitions (n);
(%o3)              num_distinct_partitions(n)
Функция: num_partitions (n)
Функция: num_partitions (n, list)

Возвращает число целочисленных разбиений числа n, если n – неотрицательное целое. Иначе num_partitions возвращает невычисляемую форму.

num_partitions(n, list) возвращает список чисел целочисленных разбиений для 1, 2, 3, ..., n.

Для неотрицательного целого n, num_partitions(n) равна cardinality(integer_partitions(n)). На самом деле num_partitions не строит полное множество разбиений и поэтому работает значительно быстрее.

Примеры:

(%i1) num_partitions (5) = cardinality (integer_partitions (5));
(%o1)                         7 = 7
(%i2) num_partitions (8, list);
(%o2)            [1, 1, 2, 3, 5, 7, 11, 15, 22]
(%i3) num_partitions (n);
(%o3)                   num_partitions(n)
Функция: partition_set (a, f)

Разбивает множество a в соответствии с предикатом f.

Функция partition_set возвращает список двух множеств. Первое множество состоит из элементов a, для которых f равен false, а второе включает все остальные элементы a. Функция partition_set не применяет is к возвращаемым f значениям.

partition_set вызывает ошибку, если a не является множеством.

См. также subset.

Примеры:

(%i1) partition_set ({2, 7, 1, 8, 2, 8}, evenp);
(%o1)                   [{1, 7}, {2, 8}]
(%i2) partition_set ({x, rat(y), rat(y) + z, 1},
                     lambda ([x], ratp(x)));
(%o2)/R/              [{1, x}, {y, y + z}]
Функция: permutations (a)

Возвращает множество различных перестановок членов списка или множества a. Каждая перестановка является списком.

Если a является списком, то повторные члены a включаются в перестановки.

permutations вызывает ошибку, если a не является списком или множеством.

См. также random_permutation.

Примеры:

(%i1) permutations ([a, a]);
(%o1)                       {[a, a]}
(%i2) permutations ([a, a, b]);
(%o2)           {[a, a, b], [a, b, a], [b, a, a]}
Функция: powerset (a)
Функция: powerset (a, n)

Возвращает множество всех подмножеств a или подмножество этого множества подмножеств.

powerset(a) возвращает множество всех подмножеств множества a. powerset(a) имеет 2^cardinality(a) членов.

powerset(a, n) возвращает множество подмножеств a, которые имеют мощность n.

powerset вызывает ошибку, если a не является множеством или n не есть целое число.

Примеры:

(%i1) powerset ({a, b, c});
(%o1) {{}, {a}, {a, b}, {a, b, c}, {a, c}, {b}, {b, c}, {c}}
(%i2) powerset ({w, x, y, z}, 4);
(%o2)                    {{w, x, y, z}}
(%i3) powerset ({w, x, y, z}, 3);
(%o3)     {{w, x, y}, {w, x, z}, {w, y, z}, {x, y, z}}
(%i4) powerset ({w, x, y, z}, 2);
(%o4)   {{w, x}, {w, y}, {w, z}, {x, y}, {x, z}, {y, z}}
(%i5) powerset ({w, x, y, z}, 1);
(%o5)                 {{w}, {x}, {y}, {z}}
(%i6) powerset ({w, x, y, z}, 0);
(%o6)                         {{}}
Функция: random_permutation (a)

Возвращает случайную перестановку множества или списка a, построенную при помощи алгоритма тасования Кнута.

Возвращаемое значение есть новый список, который отличен от исходного аргумента даже если все элементы совпадают. Однако элементы списка не копируются.

Примеры:

(%i1) random_permutation ([a, b, c, 1, 2, 3]);
(%o1)                  [c, 1, 2, 3, a, b]
(%i2) random_permutation ([a, b, c, 1, 2, 3]);
(%o2)                  [b, 3, 1, c, a, 2]
(%i3) random_permutation ({x + 1, y + 2, z + 3});
(%o3)                 [y + 2, z + 3, x + 1]
(%i4) random_permutation ({x + 1, y + 2, z + 3});
(%o4)                 [x + 1, y + 2, z + 3]
Функция: rreduce (F, s)
Функция: rreduce (F, s, s_{n + 1})

Расширяет бинарную функцию F до n-арной методом композиции. Аргумент s является списком.

rreduce(F, s) возвращает F(s_1, ... F(s_{n - 2}, F(s_{n - 1}, s_n))). Если присутствует необязательный аргумент s_{n + 1}, то результат эквивалентен rreduce(F, endcons(s_{n + 1}, s)).

Функция F сначала применяется к правой паре элементов списка, откуда происходит название "rreduce" (right reduce).

См. также lreduce, tree_reduce и xreduce.

Примеры:

rreduce без необязательного аргумента.

(%i1) rreduce (f, [1, 2, 3]);
(%o1)                     f(1, f(2, 3))
(%i2) rreduce (f, [1, 2, 3, 4]);
(%o2)                  f(1, f(2, f(3, 4)))

rreduce с необязательным аргументом.

(%i1) rreduce (f, [1, 2, 3], 4);
(%o1)                  f(1, f(2, f(3, 4)))

rreduce примененный к встроенным операторам. / – есть оператор деления.

(%i1) rreduce ("^", args ({a, b, c, d}));
                                 d
                                c
                               b
(%o1)                         a
(%i2) rreduce ("/", args ({a, b, c, d}));
                               a c
(%o2)                          ---
                               b d
Функция: setdifference (a, b)

Возвращает множество, содержащее элементы множества a, которые отсутствуют в множестве b.

setdifference вызывает ошибку, если a или b не являются множествами.

Примеры:

(%i1) S_1 : {a, b, c, x, y, z};
(%o1)                  {a, b, c, x, y, z}
(%i2) S_2 : {aa, bb, c, x, y, zz};
(%o2)                 {aa, bb, c, x, y, zz}
(%i3) setdifference (S_1, S_2);
(%o3)                       {a, b, z}
(%i4) setdifference (S_2, S_1);
(%o4)                     {aa, bb, zz}
(%i5) setdifference (S_1, S_1);
(%o5)                          {}
(%i6) setdifference (S_1, {});
(%o6)                  {a, b, c, x, y, z}
(%i7) setdifference ({}, S_1);
(%o7)                          {}
Функция: setequalp (a, b)

Возвращает true если a и b имеют одинаковое количество элементов, и is(x = y) равно true для x из a и y из b, в порядке, определяемом listify. Иначе setequalp возвращает false.

Примеры:

(%i1) setequalp ({1, 2, 3}, {1, 2, 3});
(%o1)                         true
(%i2) setequalp ({a, b, c}, {1, 2, 3});
(%o2)                         false
(%i3) setequalp ({x^2 - y^2}, {(x + y) * (x - y)});
(%o3)                         false
Функция: setify (a)

Составляет множество из элементов списка a. Повторяющиеся элементы списка a удаляются, а элементы результирующего множества сортируются в соответствии с предикатом orderlessp.

setify вызывает ошибку, если a не является списком.

Примеры:

(%i1) setify ([1, 2, 3, a, b, c]);
(%o1)                  {1, 2, 3, a, b, c}
(%i2) setify ([a, b, c, a, b, c]);
(%o2)                       {a, b, c}
(%i3) setify ([7, 13, 11, 1, 3, 9, 5]);
(%o3)                {1, 3, 5, 7, 9, 11, 13}
Функция: setp (a)

Возвращает true тогда и только тогда, когда a является Maxima множеством.

setp возвращает true как для неупрощенных множеств (т.е. содержащих излишние элементы), так и для упрощенных множеств.

setp is equivalent to the Maxima function setp(a) := not atom(a) and op(a) = 'set.

Примеры:

(%i1) simp : false;
(%o1)                         false
(%i2) {a, a, a};
(%o2)                       {a, a, a}
(%i3) setp (%);
(%o3)                         true
Функция: set_partitions (a)
Функция: set_partitions (a, n)

Возвращает множество разбиений a или подмножество этого множества.

set_partitions(a, n) возвращает множество всех разбиений a в n непустых непересекающихся подмножеств.

set_partitions(a) возвращает множество всех разбиений.

stirling2 возвращает мощность множества всех разбиений множества.

Множество множеств P есть разбиение множества S, если

  1. каждый элемент P есть непустое множество,
  2. различные члены P не пересекаются,
  3. объединение всех членов P равно S.

Примеры:

Пустое множество есть разбиение самого себя, т.к. условия 1 и 2 очевидно выполняются.

(%i1) set_partitions ({});
(%o1)                         {{}}

Мощность множества разбиений может быть определена при помощи stirling2.

(%i1) s: {0, 1, 2, 3, 4, 5}$
(%i2) p: set_partitions (s, 3)$ 
(%i3) cardinality(p) = stirling2 (6, 3);
(%o3)                        90 = 90

Каждый элемент p должен иметь n = 3 члена. Проверим:

(%i1) s: {0, 1, 2, 3, 4, 5}$
(%i2) p: set_partitions (s, 3)$ 
(%i3) map (cardinality, p);
(%o3)                          {3}

Наконец, для каждого члена p объединение всех членов должно совпадать с s. Проверим:

(%i1) s: {0, 1, 2, 3, 4, 5}$
(%i2) p: set_partitions (s, 3)$ 
(%i3) map (lambda ([x], apply (union, listify (x))), p);
(%o3)                 {{0, 1, 2, 3, 4, 5}}
Функция: some (f, a)
Функция: some (f, L_1, ..., L_n)

Возвращает true, если предикат f дает true для одного или более аргументов.

Если второй параметр является множеством, то some(f, s) возвращает true, если is(f(a_i)) дает true для одного или более a_i из s. some может вычислять f для всех или не для всех a_i из s. Т.к. множества не упорядочены, то some может вычислять f(a_i) в любом порядке.

Если аргументы являются одним или несколькими списками, то some(f, L_1, ..., L_n) возвращает true, если is(f(x_1, ..., x_n)) дает true для одного или более x_1, ..., x_n из L_1, ..., L_n соответственно. some может вычислять, а может и не вычислять f для некоторых комбинаций x_1, ..., x_n. some вычисляет списки в порядке возрастания индекса.

Для пустого множества {} или списка [] some возвращает false.

Если глобальный флаг maperror равен true, то все списки L_1, ..., L_n должны иметь одинаковую длину. Если maperror равен false, то списки обрезаются до длины самого короткого.

Значения предиката f (вычисляемое посредством is) отличное от true или false управляется глобальным флагом prederror. Если prederror равен true, то такие значения трактуются как false. Если prederror равен false, то такие значения трактуются как unknown.

Примеры:

Функция some, примененная к одному множеству. Предикат есть функция одного аргумента.

(%i1) some (integerp, {1, 2, 3, 4, 5, 6});
(%o1)                         true
(%i2) some (atom, {1, 2, sin(3), 4, 5 + y, 6});
(%o2)                         true

Функция some, примененная к спискам. Предикат есть функция двух аргументов.

(%i1) some ("=", [a, b, c], [a, b, c]);
(%o1)                         true
(%i2) some ("#", [a, b, c], [a, b, c]);
(%o2)                         false

Значение предиката f, отличное от true или false, управляется глобальным флагом prederror.

(%i1) prederror : false;
(%o1)                         false
(%i2) map (lambda ([a, b], is (a < b)), [x, y, z],
           [x^2, y^2, z^2]);
(%o2)              [unknown, unknown, unknown]
(%i3) some ("<", [x, y, z], [x^2, y^2, z^2]);
(%o3)                        unknown
(%i4) some ("<", [x, y, z], [x^2, y^2, z + 1]);
(%o4)                         true
(%i5) prederror : true;
(%o5)                         true
(%i6) some ("<", [x, y, z], [x^2, y^2, z^2]);
(%o6)                         false
(%i7) some ("<", [x, y, z], [x^2, y^2, z + 1]);
(%o7)                         true
Функция: stirling1 (n, m)

Представляет число Стирлинга первого рода.

Для неотрицательных целых n и m величина stirling1 (n, m) есть число перестановок множества из n элементов, имеющих m циклов. См. книгу Graham, Knuth и Patashnik Concrete Mathematics по поводу деталей. Для определения stirling1 (n, m) с m, меньшим нуля, Maxima использует рекуррентное соотношение. Для n меньших нуля и нецелых аргументов функция не определена.

stirling1 является упрощающей функцией. Maxima знает следующие тождества.

  1. stirling1(0, n) = kron_delta(0, n) (См. [1])
  2. stirling1(n, n) = 1 (См. [1])
  3. stirling1(n, n - 1) = binomial(n, 2) (См. [1])
  4. stirling1(n + 1, 0) = 0 (См. [1])
  5. stirling1(n + 1, 1) = n! (См. [1])
  6. stirling1(n + 1, 2) = 2^n - 1 (См. [1])

Эти тождества применяются, если аргументы являются целыми или символами, которые объявлены целыми, и первый аргумент неотрицателен. Функция stirling1 не упрощается для нецелых аргументов.

Ссылки:

[1] Donald Knuth, The Art of Computer Programming, third edition, Volume 1, Section 1.2.6, Equations 48, 49, and 50.

Примеры:

(%i1) declare (n, integer)$
(%i2) assume (n >= 0)$
(%i3) stirling1 (n, n);
(%o3)                           1

Функция stirling1 не упрощается для нецелых аргументов.

(%i1) stirling1 (sqrt(2), sqrt(2));
(%o1)              stirling1(sqrt(2), sqrt(2))

Maxima применяет тождества для stirling1.

(%i1) declare (n, integer)$
(%i2) assume (n >= 0)$
(%i3) stirling1 (n + 1, n);
                            n (n + 1)
(%o3)                       ---------
                                2
(%i4) stirling1 (n + 1, 1);
(%o4)                          n!
Функция: stirling2 (n, m)

Представляет число Стирлинга второго рода.

Для неотрицательных целых n и m число stirling2 (n, m) есть число способов, которыми множество мощности n может быть разбито на m непересекающихся подмножеств. Для определения stirling2 (n, m) с m, меньшим нуля, Maxima использует рекуррентное соотношение. Для n меньших нуля и нецелых аргументов функция не определена.

stirling2 является упрощающей функцией. Maxima знает следующие тождества.

  1. stirling2(0, n) = kron_delta(0, n) (См. [1])
  2. stirling2(n, n) = 1 (См. [1])
  3. stirling2(n, n - 1) = binomial(n, 2) (См. [1])
  4. stirling2(n + 1, 1) = 1 (См. [1])
  5. stirling2(n + 1, 2) = 2^n - 1 (См. [1])
  6. stirling2(n, 0) = kron_delta(n, 0) (См. [2])
  7. stirling2(n, m) = 0 when m > n (См. [2])
  8. stirling2(n, m) = sum((-1)^(m - k) binomial(m k) k^n,i,1,m) / m! если m и n целые и n неотрицательно. (См. [3])

Эти тождества применяются, если аргументы являются целыми или символами, которые объявлены целыми, и первый аргумент неотрицателен. Функция stirling2 не упрощается для нецелых аргументов.

Ссылки:

[1] Donald Knuth. The Art of Computer Programming, third edition, Volume 1, Section 1.2.6, Equations 48, 49, and 50.

[2] Graham, Knuth, and Patashnik. Concrete Mathematics, Table 264.

[3] Abramowitz and Stegun. Handbook of Mathematical Functions, Section 24.1.4.

Примеры:

(%i1) declare (n, integer)$
(%i2) assume (n >= 0)$
(%i3) stirling2 (n, n);
(%o3)                           1

Функция stirling2 не упрощается для нецелых аргументов.

(%i1) stirling2 (%pi, %pi);
(%o1)                  stirling2(%pi, %pi)

Maxima применяет тождества для stirling2.

(%i1) declare (n, integer)$
(%i2) assume (n >= 0)$
(%i3) stirling2 (n + 9, n + 8);
                         (n + 8) (n + 9)
(%o3)                    ---------------
                                2
(%i4) stirling2 (n + 1, 2);
                              n
(%o4)                        2  - 1
Функция: subset (a, f)

Возвращает подмножество множества a, которое удовлетворяет предикату f.

Функция subset возвращает множество, состоящее из элементов a, для которых f возвращает любое значение, отличное от false. Функция subset не применяет is к значению, возвращаемому f.

Функция subset вызывает ошибку, если a не является множеством.

См. также partition_set.

Примеры:

(%i1) subset ({1, 2, x, x + y, z, x + y + z}, atom);
(%o1)                     {1, 2, x, z}
(%i2) subset ({1, 2, 7, 8, 9, 14}, evenp);
(%o2)                      {2, 8, 14}
Функция: subsetp (a, b)

Возвращает true тогда и только тогда, когда a есть подмножество b.

Функция subsetp вызывает ошибку, если a или b не являются множествами.

Примеры:

(%i1) subsetp ({1, 2, 3}, {a, 1, b, 2, c, 3});
(%o1)                         true
(%i2) subsetp ({a, 1, b, 2, c, 3}, {1, 2, 3});
(%o2)                         false
Функция: symmdifference (a_1, ..., a_n)

Возвращает симметричную разницу, т.е. множество, элементы которого присутствуют только в одном множестве a_k.

При задании двух аргументов, symmdifference(a, b) эквивалентно union ( setdifference (a, b ), setdifference (b, a)).

Функция symmdifference вызывает ошибку, если любой из ее аргументов не является множеством.

Примеры:

(%i1) S_1 : {a, b, c};
(%o1)                       {a, b, c}
(%i2) S_2 : {1, b, c};
(%o2)                       {1, b, c}
(%i3) S_3 : {a, b, z};
(%o3)                       {a, b, z}
(%i4) symmdifference ();
(%o4)                          {}
(%i5) symmdifference (S_1);
(%o5)                       {a, b, c}
(%i6) symmdifference (S_1, S_2);
(%o6)                        {1, a}
(%i7) symmdifference (S_1, S_2, S_3);
(%o7)                        {1, z}
(%i8) symmdifference ({}, S_1, S_2, S_3);
(%o8)                        {1, z}
Функция: tree_reduce (F, s)
Функция: tree_reduce (F, s, s_0)

Расширяет бинарную функцию F до n-арной методом композиции. Аргумент s является множеством или списком.

Функция tree_reduce действует следующим образом: F применяется к последовательным парам элементов, чтобы сформировать новый список [F(s_1, s_2), F(s_3, s_4), ...]. При этом если число элементов нечетно, то последний элемент остается неизменным. Затем процесс повторяется до тех пор, пока не останется только один элемент списка, который и возвращается в качестве значения.

Если присутствует необязательный элемент s_0, то результат эквивалентен tree_reduce(F, cons(s_0, s).

Для сложения чисел с плавающей точкой tree_reduce может возвращать сумму с меньшей ошибкой округления, чем rreduce или lreduce.

Элементы s и частичные результаты могут быть представлены в виде бинарного дерева минимальной глубины, откуда происходит название "tree_reduce".

Примеры:

Функция tree_reduce, примененная к списку с четным числом элементов.

(%i1) tree_reduce (f, [a, b, c, d]);
(%o1)                  f(f(a, b), f(c, d))

Функция tree_reduce, примененная к списку с нечетным числом элементов.

(%i1) tree_reduce (f, [a, b, c, d, e]);
(%o1)               f(f(f(a, b), f(c, d)), e)
Функция: union (a_1, ..., a_n)

Возвращает объединение множеств от a_1 до a_n.

Вызов union() (без аргументов) возвращает пустое множество.

Функция union возвращает ошибку, если любой из ее аргументов не является множеством.

Примеры:

(%i1) S_1 : {a, b, c + d, %e};
(%o1)                   {%e, a, b, d + c}
(%i2) S_2 : {%pi, %i, %e, c + d};
(%o2)                 {%e, %i, %pi, d + c}
(%i3) S_3 : {17, 29, 1729, %pi, %i};
(%o3)                {17, 29, 1729, %i, %pi}
(%i4) union ();
(%o4)                          {}
(%i5) union (S_1);
(%o5)                   {%e, a, b, d + c}
(%i6) union (S_1, S_2);
(%o6)              {%e, %i, %pi, a, b, d + c}
(%i7) union (S_1, S_2, S_3);
(%o7)       {17, 29, 1729, %e, %i, %pi, a, b, d + c}
(%i8) union ({}, S_1, S_2, S_3);
(%o8)       {17, 29, 1729, %e, %i, %pi, a, b, d + c}
Функция: xreduce (F, s)
Функция: xreduce (F, s, s_0)

Расширяет функцию F до n-арной методом композиции или, если F уже n-арная, применяет F к s. Если F не является n-арной, то xreduce работает также, как lreduce. Аргумент s является списком.

Известны следующие n-арные функции: сложение +, умножение *, and, or, max, min и append. Функции могут быть объявлены n-арными при помощи declare(F, nary). Для таких функций, xreduce работает быстрее, чем rreduce или lreduce.

Если задан необязательный аргумент s_0, то результат эквивалентен xreduce(s, cons(s_0, s)).

Сложение чисел с плавающей точкой, строго говоря, не является ассоциативным. Функция xreduce применяет n-арное сложение, если s содержит числа с плавающей точкой.

Примеры:

Функция xreduce, примененная к n-арной функции. F вызывается однажды со всеми аргументами.

(%i1) declare (F, nary);
(%o1)                         done
(%i2) F ([L]) := L;
(%o2)                      F([L]) := L
(%i3) xreduce (F, [a, b, c, d, e]);
(%o3)         [[[[[("[", simp), a], b], c], d], e]

Функция xreduce, примененная к не n-арной функции. G вызывается несколько раз с двумя аргументами каждый раз.

(%i1) G ([L]) := L;
(%o1)                      G([L]) := L
(%i2) xreduce (G, [a, b, c, d, e]);
(%o2)         [[[[[("[", simp), a], b], c], d], e]
(%i3) lreduce (G, [a, b, c, d, e]);
(%o3)                 [[[[a, b], c], d], e]

Next: , Previous: Множества, Up: Top   [Contents][Index]

37 Определение функций


Next: , Previous: Определение функций, Up: Определение функций   [Contents][Index]

37.1 Введение в определение функций


Next: , Previous: Введение в определение функций, Up: Определение функций   [Contents][Index]

37.2 Функции

37.2.1 Обычные функции

Для определения функций в Maxima используется оператор :=. Например

f(x) := sin(x)

определяет функцию f. Функции без имени могут быть созданы при помощи lambda. Например

lambda ([i, j], ...)

может быть использовано вместо f, и

f(i,j) := block ([], ...);
map (lambda ([i], i+1), l)

возвращает список с каждым элементом увеличенным на 1.

Можно определить функцию с переменным числом аргументов, присваивая последнему аргументу список дополнительных параметров:

(%i1) f ([u]) := u;
(%o1)                      f([u]) := u
(%i2) f (1, 2, 3, 4);
(%o2)                     [1, 2, 3, 4]
(%i3) f (a, b, [u]) := [a, b, u];
(%o3)               f(a, b, [u]) := [a, b, u]
(%i4) f (1, 2, 3, 4, 5, 6);
(%o4)                 [1, 2, [3, 4, 5, 6]]

Правая часть определения функции является выражением. Поэтому, если требуется последовательность выражений, то можно определить правую часть следующим образом

f(x) := (expr1, expr2, ...., exprn);

В этом случае, значение, возвращаемое функцией, будет равно значению exprn.

Использование команды возврата return возможно тоько внутри программного блока block. Блок

block ([], expr1, ..., if (a > 10) then return(a), ..., exprn)

сам по себе является выражением и может использоваться в правой части определения функции. При этом, команда возврата может быть выполнена раньше достижения последнего выражения.

Первый элемент блока [] может содержать список переменных и присваиваемых им значений, например, такой как [a: 3, b, c: []]. В результате, три переменные a,b и c не будут ссылаться на свои глобальные значения, а будут иметь локальные значения внутри блока или внутри функций, вызываемых из этого блока. Это называется термином динамическое связывание, поскольку локальные переменные сохраняются от начала выполнения блока до его завершения. Как только выполнение возвращается из блока, или его выполнение прерывается, то старое значения переменных (если существуют) восстанавливаются. Это хороший метод защиты значения переменных. Отметим, что присваивание начальных значений переменных в блоке выполняется параллельно. Это означает, что если сделать c: a, в вышеизложенном примере, то значение c будет равно значению a до входа в блок и до присваивания a локального значения. Поэтому, выполнение кода

block ([a: a], expr1, ... a: a+3, ..., exprn)

защитит внешнее значение переменной a от изменения внутри блока, и, с другой стороны, обеспечит доступ к этому значению. Иными словами, правая часть присваивания вычисляется до выполнения каких-либо присваиваний. Простое использование block ([x], ... приводит к тому, что x внутри блока равна сама себе, как при запуске новой сессии Maxima.

Фактические параметры функции трактуются точно так же, как локальные переменные в блоке. Таким образом, при определении

f(x) := (expr1, ..., exprn);

и вызове

f(1);

создается контекст, аналогичный

block ([x: 1], expr1, ..., exprn)

Внутри функций, если правая часть определения функции может вычисляться во время выполнения, полезно использовать define и, возможно, buildq.

37.2.2 Функции-массивы

Функции-массивы сохраняют значение функции при первом вызове с определенными значениями параметров, и возвращают сохраненное значение без перевычисления при последующих вызовах с теми же параметрами. Такие функции часто называются “функции с памятью”.

Имена функций-массивов добавляются к глобальной переменной arrays (не к глобальной переменной functions). Функция arrayinfo возвращает для таких функций список сохраненных элементов, а функция listarray возвращает сохраненные значения. Функции dispfun и fundef возвращают определения функций-массива.

Функция arraymake создает вызов функции-массива, аналогично тому как funmake делает для обычных функций. Функция arrayapply применяет функцию-массив к аргументам, аналогично тому как apply делает для обычных функций. Не существует полного аналога функции map для функций-массивов, но map(lambda([x], a[x]), L) или makelist(a[x], x, L), где L – список, действует очень похоже.

Функция remarray удаляет определение функции-массива (включая сохраненные значения), аналогично тому как remfunction делает для обычных функций.

Вызов kill(a[x]) удаляет сохраненное значение функции-массива a для аргумента x. При следующем вызове a с аргументом x, функция будет перевычислена. Не существует способа сразу удалить все сохраненные значения функции-массива кроме как вызов kill(a) или remarray(a), что также удаляет определение функции.


Next: , Previous: Функции, Up: Определение функций   [Contents][Index]

37.3 Макросы

Функция: buildq (L, expr)

Подставляет значения переменных, определяемых списком L, в выражение expr параллельно без перевычисления expr. Результирующее выражение упрощается, но не вычисляется после выполнения buildq.

Элементы списка L являются символами или операторами присваивания symbol: value, вычисляемые параллельно. Т.е. значение переменных в правой части присваиваний вычисляются в контексте, в котором вызван buildq, но не в контексте списка присваиваний L. Если для некоторых переменных в списке L не задано значений, то для них сохраняются значения из контекста вызова buildq.

Переменные из списка L подставляются в expr параллельно. Т.е. значение каждой подстановки определяется до подстановки, и одна переменная не оказывает никакого влияния на другую.

Если переменная x присутствует в expr в виде splice (x), то x должна иметь значение в форме списка, и этот список будет вместо подстановки интерполирован в expr.

Любые другие переменные в expr, не присутствующие в L, переносятся в результат буквально без изменения, даже в том случае, когда имеют значение в контексте вызова buildq.

Примеры:

Переменной a явно присвоено значение x, тогда как b имеет значение (а именно 29) из контекста вызова, а c сохраняется неизменным. Результат остается невычисленным до явного применения ''%.

(%i1) (a: 17, b: 29, c: 1729)$
(%i2) buildq ([a: x, b], a + b + c);
(%o2)                      x + c + 29
(%i3) ''%;
(%o3)                       x + 1758

Переменная e равна списку, который подставляется в foo и интерполируется в bar.

(%i1) buildq ([e: [a, b, c]], foo (x, e, y));
(%o1)                 foo(x, [a, b, c], y)
(%i2) buildq ([e: [a, b, c]], bar (x, splice (e), y));
(%o2)                  bar(x, a, b, c, y)

Результат подстановки упрощается. Если бы упрощение выполнилось до подстановки, то нижеследующие результаты совпали бы.

(%i1) buildq ([e: [a, b, c]], splice (e) + splice (e));
(%o1)                    2 c + 2 b + 2 a
(%i2) buildq ([e: [a, b, c]], 2 * splice (e));
(%o2)                        2 a b c

Значения переменных в L присваиваются параллельно, при последовательном присваивании первый результат был бы равен foo (b, b). Подстановки осуществляются параллельно. Сравните второй результат с результатом функции subst, которая выполняет подстановки последовательно.

(%i1) buildq ([a: b, b: a], foo (a, b));
(%o1)                       foo(b, a)
(%i2) buildq ([u: v, v: w, w: x, x: y, y: z, z: u],
              bar (u, v, w, x, y, z));
(%o2)                 bar(v, w, x, y, z, u)
(%i3) subst ([u=v, v=w, w=x, x=y, y=z, z=u],
             bar (u, v, w, x, y, z));
(%o3)                 bar(u, u, u, u, u, u)

Составим список уравнений с переменными в левой части и со значениями этих переменных в правой. Функция macroexpand выводит выражение, возвращаемое show_values.

(%i1) show_values ([L]) ::= buildq ([L], map ("=", 'L, L));
(%o1)   show_values([L]) ::= buildq([L], map("=", 'L, L))
(%i2) (a: 17, b: 29, c: 1729)$
(%i3) show_values (a, b, c - a - b);
(%o3)          [a = 17, b = 29, c - b - a = 1683]
(%i4) macroexpand (show_values (a, b, c - a - b));
(%o4)    map(=, '([a, b, c - b - a]), [a, b, c - b - a])

Используя функцию нескольких аргументов, создадим другую функцию, у которой некоторые аргументы имеют фиксированное значение.

(%i1) curry (f, [a]) :=
        buildq ([f, a], lambda ([[x]], apply (f, append (a, x))))$
(%i2) by3 : curry ("*", 3);
(%o2)        lambda([[x]], apply(*, append([3], x)))
(%i3) by3 (a + b);
(%o3)                       3 (b + a)
Функция: macroexpand (expr)

Если expr является вызовом макро-функции, то macroexpand возвращает макро-расширение expr без его вычисления. В противном случае, macroexpand возвращает expr.

Если макро-расширение expr само является макро-вызовом, то оно тоже раскрывается.

Функция macroexpand не вычисляет свои аргументы. Но если раскрытие макро-функций приводит к побочным эффектам, то эти эффекты выполняются.

См. также ::=, macros и macroexpand1.

Примеры

(%i1) g (x) ::= x / 99;
                                    x
(%o1)                      g(x) ::= --
                                    99
(%i2) h (x) ::= buildq ([x], g (x - a));
(%o2)            h(x) ::= buildq([x], g(x - a))
(%i3) a: 1234;
(%o3)                         1234
(%i4) macroexpand (h (y));
                              y - a
(%o4)                         -----
                               99
(%i5) h (y);
                            y - 1234
(%o5)                       --------
                               99
Функция: macroexpand1 (expr)

Если expr является вызовом макро-функции, то macroexpand1 возвращает макро-расширение expr без его вычисления. В противном случае, macroexpand1 возвращает expr.

Функция macroexpand1 не вычисляет свои аргументы. Но если раскрытие макро-функций приводит к побочным эффектам, то эти эффекты выполняются.

Если макро-расширение expr само является макро-вызовом, то оно не раскрывается.

См. также ::=, macros и macroexpand.

Примеры:

(%i1) g (x) ::= x / 99;
                                    x
(%o1)                      g(x) ::= --
                                    99
(%i2) h (x) ::= buildq ([x], g (x - a));
(%o2)            h(x) ::= buildq([x], g(x - a))
(%i3) a: 1234;
(%o3)                         1234
(%i4) macroexpand1 (h (y));
(%o4)                       g(y - a)
(%i5) h (y);
                            y - 1234
(%o5)                       --------
                               99
Глобальная переменная: macros

Значение по умолчанию: []

macros есть список всех определенных пользователем макро-функций. Оператор определения макро-функции ::= добавляет новую макро-функцию к этому списку, а kill, remove и remfunction удаляют ее из него.

См.также infolists.

Функция: splice (a)

Интерполирует список, обозначенный атомом a в выражение, но только если splice присутствует внутри buildq. В противном случае splice рассматривается как неопределенная функция. Если переменная a присутствует внутри buildq сама по себе без splice, то вместо a подставляется (не интерполируется) соответствующий список. Аргументом splice может быть только атом, но не явный список или выражение, дающее список в качестве значения.

Обычно, splice применяется для задания аргументов функции или оператора. Для функции f, выражение f (splice (a)) внутри buildq преобразуется в f (a[1], a[2], a[3], ...). Для оператора o, выражение "o" (splice (a) внутри buildq преобразуется в "o" (a[1], a[2], a[3], ...), где o может быть оператором любого вида (обычно оператором с многими аргументами). Обратите внимание, что оператор должен быть заключен в двойные кавычки ".

Примеры:

(%i1) buildq ([x: [1, %pi, z - y]], foo (splice (x)) / length (x));
                       foo(1, %pi, z - y)
(%o1)                -----------------------
                     length([1, %pi, z - y])
(%i2) buildq ([x: [1, %pi]], "/" (splice (x)));
                                1
(%o2)                          ---
                               %pi
(%i3) matchfix ("<>", "<>");
(%o3)                          <>
(%i4) buildq ([x: [1, %pi, z - y]], "<>" (splice (x)));
(%o4)                   <>1, %pi, z - y<>

Previous: Макросы, Up: Определение функций   [Contents][Index]

37.4 Функции и переменные для определения функций

Функция: apply (F, [x_1, ..., x_n])

Составляет и вычисляет выражение F(arg_1, ..., arg_n).

Функция apply не пытается различить функцию-массив и обычную функцию, и если F есть имя функции-массива, то apply вычисляет F(...) (т.е. обычный вызов функции с круглыми а не с квадратными скобками). Функция arrayapply вычисляет вызов функции с квадратными скобками.

Примеры:

Функция apply вычисляет свои аргументы. В этом примере, min применяется к значению L.

(%i1) L : [1, 5, -10.2, 4, 3];
(%o1)                 [1, 5, - 10.2, 4, 3]
(%i2) apply (min, L);
(%o2)                        - 10.2

Функция apply вычисляет свои аргументы даже если функция F не вычисляет их.

(%i1) F (x) := x / 1729;
                                   x
(%o1)                     F(x) := ----
                                  1729
(%i2) fname : F;
(%o2)                           F
(%i3) dispfun (F);
                                   x
(%t3)                     F(x) := ----
                                  1729

(%o3)                         [%t3]
(%i4) dispfun (fname);
fname is not the name of a user function.
 -- an error.  Quitting.  To debug this try debugmode(true);
(%i5) apply (dispfun, [fname]);
                                   x
(%t5)                     F(x) := ----
                                  1729

(%o5)                         [%t5]

Функция apply вычисляет имя функции F. Одиночная кавычка ' блокирует это вычисление. demoivre является именем глобальной переменной и, одновременно, именем функции.

(%i1) demoivre;
(%o1)                         false
(%i2) demoivre (exp (%i * x));
(%o2)                  %i sin(x) + cos(x)
(%i3) apply (demoivre, [exp (%i * x)]);
demoivre evaluates to false
Improper name or value in functional position.
 -- an error.  Quitting.  To debug this try debugmode(true);
(%i4) apply ('demoivre, [exp (%i * x)]);
(%o4)                  %i sin(x) + cos(x)
Функция: block ([v_1, ..., v_m], expr_1, ..., expr_n)
Функция: block (expr_1, ..., expr_n)

Функция block последовательно вычисляет expr_1, ..., expr_n и возвращает значение последнего вычисленного выражения. Последовательность вычисления может быть изменена при помощи функций go, throw и return. Последнее выражение expr_n вычисляется если не используется return или вычисляется выражение, содержащие throw. Некоторые переменные v_1, ..., v_m могут быть объявлены локальными в блоке, и они отличаются от глобальных переменных с теми же именами. Если не требуется определять локальные переменные, то список может быть опущен. Внутри блока, все другие переменные, отличные от v_1, ..., v_m, являются глобальными.

block сохраняет текущие значения переменных v_1, ..., v_m (если таковые существуют) при входе в блок, и затем удаляет их значения, так чтобы эти переменные вычислялись сами в себя. Локальные переменные могут принимать любые значения внутри блока, но пр выходе из него сохраненные значения восстанавливаются, а локальные в блоке значения теряются.

Блок может существовать внутри другого блока. Локальные переменные определяются всякий раз как вычисляется новый block. Локальные переменные объемлющего блока выглядят как глобальные для внутреннего блока. Если переменная не локальна в блоке, то ее значение равно последнему, присвоенному в объемлющем блоке, если таковое существует, и значению переменной в глобальном окружении в противном случае. Эта политика совпадает с обычным понятием "динамической области определения".

Если необходимо сохранять и восстанавливать другие локальные свойства, кроме value, такие как array (кроме полных массивов), function, dependencies, atvalue, matchdeclare, atomgrad, constant и nonscalar, то следует использовать функцию local внутри блока с именем функции в качестве параметра.

Значением блока является значение последнего выражения или значение аргумента функции return, которая может быть использована для явного выхода из блока. Функция go используется для передачи управления на команду блока, помеченную аргументом go. Для того, чтобы пометить команду нужно поместить перед ней метку в виде атома. Например: block ([x], x:1, loop, x: x+1, ..., go(loop), ...). Аргументом go должна быть метка, определенная в текущем блоке. Невозможно использовать go для передачи управления в блок отличный от того, в котором находится вызов go.

Блоки обычно применяются в правых частях определения функций, но могут быть использованы и в других местах.

Функция: break (expr_1, ..., expr_n)

Вычисляет и печатает выражения expr_1, ..., expr_n и затем вызывает прерывание Maxima с тем, чтобы пользователь мог исследовать и изменить окружение. Ввод exit; возобновляет вычисление.

Функция: catch (expr_1, ..., expr_n)

Вычисляет expr_1, ..., expr_n одно за другими и, если одно из них приводит к вычислению выражения throw (arg), то значением catch становится значение аргумента throw (arg), и дальнейшее вычисление не производится. Такой "нелокальный возврат" осуществляется из любого уровня вложенности до первого объемлющего catch. Если нет объемлющего catch, то throw вызывает ошибку.

Если вычисление аргументов не приводит к вычислению throw, то значение catch равно значению expr_n.

(%i1) lambda ([x], if x < 0 then throw(x) else f(x))$
(%i2) g(l) := catch (map (''%, l))$
(%i3) g ([1, 2, 3, 7]);
(%o3)               [f(1), f(2), f(3), f(7)]
(%i4) g ([1, 2, -3, 7]);
(%o4)                          - 3

Здесь, если список l содержит только неотрицательные числа, то функция g возвращает список функций f, примененных к элементам l, иначе, g "ловит" первое отрицательное число в l и "бросает" его вверх.

Функция: compfile (filename, f_1, ..., f_n)
Функция: compfile (filename, functions)
Функция: compfile (filename, all)

Транслирует функции Maxima в Lisp и записывает полученный код в файл filename.

Вызов compfile(filename, f_1, ..., f_n) транслирует только заданные функции. Вызов compfile(filename, functions) или вызов compfile(filename, all) транслирует все определенные пользователем функции.

Код Lisp не вычисляется, а результирующий файл не обрабатывается компилятором Lisp. Функция translate создает и вычисляет Lisp код. Функция compile_file транслирует код Maxima в Lisp, и затем выполняет компилятор Lisp.

См. также translate, translate_file и compile_file.

Функция: compile (f_1, ..., f_n)
Функция: compile (functions)
Функция: compile (all)

Транслирует определения Maxima функций f_1, ..., f_n в Lisp, вычисляет Lisp код и вызывает Lisp функцию COMPILE на каждую транслированную функцию. Функция compile возвращает список скомпилированных функций.

Вызов compile (all) или compile (functions) компилирует все определенные пользователем функции.

Функция compile не вычисляет свои аргументы. Оператор кавычка-кавычка '' может быть использован для их вычисления.

Функция: define (f(x_1, ..., x_n), expr)
Функция: define (f[x_1, ..., x_n], expr)
Функция: define (funmake (f, [x_1, ..., x_n]), expr)
Функция: define (arraymake (f, [x_1, ..., x_n]), expr)
Функция: define (ev (expr_1), expr_2)

Определяет функцию с именем f, аргументами x_1, ..., x_n и телом функции expr. Функция define всегда вычисляет свой второй аргумент (если вычисление не экранировано, т.е. блокировано явным образом). Функция, определенная данным образом, может быть обычной функцией Maxima (с аргументами в круглых скобках) или функцией-массивом (с аргументам в квадратных скобках).

Если последний аргумент x_n является одноэлементным списком, то функция, определенная define, принимает произвольное число аргументов. Фактические параметры присваиваются по одному формальным параметрам x_1, ..., x_(n - 1), а все последующие фактические параметры, если таковые есть, присваиваются x_n одним списком.

Если первый параметр define имеет форму f(x_1, ..., x_n) или f[x_1, ..., x_n], то аргументы функции вычисляются, а f нет, даже если уже есть функция или переменная с таким именем.

Если же первый параметр является выражением с оператором funmake, arraymake или ev, то первый аргумент вычисляется. Это позволяет вычислять как имя функции так и ее тело.

Все определяемые функции действуют в одном пространстве имен, т.е. если функция f определена внутри другой функции g, то действие f не ограничено функцией g.

Если некоторый формальный параметр x_k является экранированным символом (после вычисления), то функция, определенная define, не будет вычислять соответствующий фактический параметр. Все остальные фактические параметры вычисляются.

См. также := и ::=.

Примеры:

Функция define всегда вычисляет свой второй аргумент (если вычисление не блокировано явным образом).

(%i1) expr : cos(y) - sin(x);
(%o1)                    cos(y) - sin(x)
(%i2) define (F1 (x, y), expr);
(%o2)              F1(x, y) := cos(y) - sin(x)
(%i3) F1 (a, b);
(%o3)                    cos(b) - sin(a)
(%i4) F2 (x, y) := expr;
(%o4)                   F2(x, y) := expr
(%i5) F2 (a, b);
(%o5)                    cos(y) - sin(x)

Функция, определяемая define, может быть обычной функцией Maxima или функцией-массивом.

(%i1) define (G1 (x, y), x.y - y.x);
(%o1)               G1(x, y) := x . y - y . x
(%i2) define (G2 [x, y], x.y - y.x);
(%o2)                G2     := x . y - y . x
                       x, y

Если последний аргумент x_n является одноэлементным списком, то определенная define функция принимает произвольное число аргументов.

(%i1) define (H ([L]), '(apply ("+", L)));
(%o1)                H([L]) := apply("+", L)
(%i2) H (a, b, c);
(%o2)                       c + b + a

Если первый параметр является выражением с оператором funmake, arraymake или ev, то первый аргумент вычисляется.

(%i1) [F : I, u : x];
(%o1)                        [I, x]
(%i2) funmake (F, [u]);
(%o2)                         I(x)
(%i3) define (funmake (F, [u]), cos(u) + 1);
(%o3)                  I(x) := cos(x) + 1
(%i4) define (arraymake (F, [u]), cos(u) + 1);
(%o4)                   I  := cos(x) + 1
                         x
(%i5) define (foo (x, y), bar (y, x));
(%o5)                foo(x, y) := bar(y, x)
(%i6) define (ev (foo (x, y)), sin(x) - cos(y));
(%o6)             bar(y, x) := sin(x) - cos(y)
Функция: define_variable (name, default_value, mode)

Определяет глобальную переменную. define_variable полезна в пользовательских пакетах, которые часто транслируются или компилируются.

Функция define_variable выполняет следующие шаги:

  1. mode_declare (name, mode) декларирует тип переменной name для транслятора. См. mode_declare для списка возможных типов.
  2. Если переменная не имеет значения, то default_value устанавливается равным name.
  3. declare (name, special) объявляет переменную специальной.
  4. Ассоциирует имя name с тестовой функцией, чтобы обеспечить, что name будут присваиваться значения только объявленного типа.

Свойство value_check может быть установлено для любой переменной, определенной при помощи define_variable с типом отличным от any. Значение свойства value_check является лямбда-выражением или именем функции одной переменной. Эта функция вызывается всякий раз, как производится попытка присвоить значение данной переменной. Параметром функции value_check является предполагаемое новое значение переменной.

Функция define_variable вычисляет default_value и не вычисляет name и mode. Функция define_variable возвращает текущее значение name, что есть default_value если name не имела значения до декларации и значение name в противном случае.

Примеры:

foo – логическая переменная с начальным значением true.

(%i1) define_variable (foo, true, boolean);
(%o1)                         true
(%i2) foo;
(%o2)                         true
(%i3) foo: false;
(%o3)                         false
(%i4) foo: %pi;
Error: foo was declared mode boolean, has value: %pi
 -- an error.  Quitting.  To debug this try debugmode(true);
(%i5) foo;
(%o5)                         false

bar – целочисленная переменная, которая должна быть простым числом.

(%i1) define_variable (bar, 2, integer);
(%o1)                           2
(%i2) qput (bar, prime_test, value_check);
(%o2)                      prime_test
(%i3) prime_test (y) := if not primep(y) then
                           error (y, "is not prime.");
(%o3) prime_test(y) := if not primep(y)

                                   then error(y, "is not prime.")
(%i4) bar: 1439;
(%o4)                         1439
(%i5) bar: 1440;
1440 is not prime.
#0: prime_test(y=1440)
 -- an error.  Quitting.  To debug this try debugmode(true);
(%i6) bar;
(%o6)                         1439

baz_quux – переменная, которой нельзя присвоить значение. Тип any_check аналогичен any, но позволяет применять механизм value_check, в то время как тип any этого не позволяет.

(%i1) define_variable (baz_quux, 'baz_quux, any_check);
(%o1)                       baz_quux
(%i2) F: lambda ([y], if y # 'baz_quux then
                 error ("Cannot assign to `baz_quux'."));
(%o2) lambda([y], if y # 'baz_quux

                        then error(Cannot assign to `baz_quux'.))
(%i3) qput (baz_quux, ''F, value_check);
(%o3) lambda([y], if y # 'baz_quux

                        then error(Cannot assign to `baz_quux'.))
(%i4) baz_quux: 'baz_quux;
(%o4)                       baz_quux
(%i5) baz_quux: sqrt(2);
Cannot assign to `baz_quux'.
#0: lambda([y],if y # 'baz_quux then
                 error("Cannot assign to `baz_quux'."))(y=sqrt(2))
 -- an error.  Quitting.  To debug this try debugmode(true);
(%i6) baz_quux;
(%o6)                       baz_quux
Функция: dispfun (f_1, ..., f_n)
Функция: dispfun (all)

Выводит определения пользовательских функций f_1, ..., f_n. Каждый аргумент должен быть именем: макроса (определенного при помощи ::=), обычной функции (определенной := или define), функции-массива (определенной := или define, но с аргументами в квадратных скобках [ ]), функцией с индексом (определенной := или define, но с частью аргументов в квадратных скобках а с другими в круглых ( )), одним из элементов функции с индексом с определенным значением индекса, или функцией с постоянным индексом.

Вызов dispfun (all) выводит все пользовательские функции, которые определяются списками functions, arrays и macros, кроме функций с постоянным индексом.

Функция dispfun создает метки промежуточных выражений (%t1, %t2 и т.д.) для каждой выводимой функции и присваивает определения функций этим меткам. В отличии от этого, fundef возвращает определение функции.

Функция dispfun не вычисляет свои аргументы. Оператор кавычка-кавычка '' может быть использован для их вычисления. Функция dispfun возвращает список меток промежуточных выражений, соответствующих выведенным функциям.

Примеры:

(%i1) m(x, y) ::= x^(-y);
                                     - y
(%o1)                   m(x, y) ::= x
(%i2) f(x, y) :=  x^(-y);
                                     - y
(%o2)                    f(x, y) := x
(%i3) g[x, y] :=  x^(-y);
                                    - y
(%o3)                     g     := x
                           x, y
(%i4) h[x](y) :=  x^(-y);
                                    - y
(%o4)                     h (y) := x
                           x
(%i5) i[8](y) :=  8^(-y);
                                    - y
(%o5)                     i (y) := 8
                           8
(%i6) dispfun (m, f, g, h, h[5], h[10], i[8]);
                                     - y
(%t6)                   m(x, y) ::= x

                                     - y
(%t7)                    f(x, y) := x

                                    - y
(%t8)                     g     := x
                           x, y

                                    - y
(%t9)                     h (y) := x
                           x

                                    1
(%t10)                     h (y) := --
                            5        y
                                    5

                                     1
(%t11)                    h  (y) := ---
                           10         y
                                    10

                                    - y
(%t12)                    i (y) := 8
                           8

(%o12)       [%t6, %t7, %t8, %t9, %t10, %t11, %t12]
(%i12) ''%;
                     - y              - y            - y
(%o12) [m(x, y) ::= x   , f(x, y) := x   , g     := x   , 
                                            x, y
                  - y           1              1             - y
        h (y) := x   , h (y) := --, h  (y) := ---, i (y) := 8   ]
         x              5        y   10         y   8
                                5             10
Системная переменная: functions

Значение по умолчанию: []

Переменная functions есть список всех обычных функций Maxima в текущей сессии. Обычные функции – это функции, определенные при помощи define или :=, и вызываемые с аргументами в круглых скобках (). Функция может быть определена в командной строке Maxima или в файле, загруженном при помощи load или batch.

Функции-массивы (вызываемые с квадратными скобками, т.е. F[x]) и функции с индексом (вызываемые с круглыми и квадратными скобками, т.е. F[x](y)) перечислены в глобальной переменной arrays, а не в functions.

Lisp функции не включаются в список.

Примеры:

(%i1) F_1 (x) := x - 100;
(%o1)                   F_1(x) := x - 100
(%i2) F_2 (x, y) := x / y;
                                      x
(%o2)                    F_2(x, y) := -
                                      y
(%i3) define (F_3 (x), sqrt (x));
(%o3)                   F_3(x) := sqrt(x)
(%i4) G_1 [x] := x - 100;
(%o4)                    G_1  := x - 100
                            x
(%i5) G_2 [x, y] := x / y;
                                     x
(%o5)                     G_2     := -
                             x, y    y
(%i6) define (G_3 [x], sqrt (x));
(%o6)                    G_3  := sqrt(x)
                            x
(%i7) H_1 [x] (y) := x^y;
                                      y
(%o7)                     H_1 (y) := x
                             x
(%i8) functions;
(%o8)              [F_1(x), F_2(x, y), F_3(x)]
(%i9) arrays;
(%o9)                 [G_1, G_2, G_3, H_1]
Функция: fundef (f)

Возвращает определение функции f.

Аргумент должен быть именем: макроса (определенного при помощи ::=), обычной функции (определенной := или define), функции-массива (определенной := или define, но с аргументами в квадратных скобках [ ]), функцией с индексом (определенной := или define, но с частью аргументов в квадратных скобках а с другими в круглых ( )), одним из элементов функции с индексом с определенным значением индекса, или функцией с постоянным индексом.

Функция fundef не вычисляет свои аргументы. Оператор кавычка-кавычка '' может быть использован для их вычисления.

Вызов fundef (f) возвращает определение функции f. В отличии от этого, dispfun (f) присваивает определения функций меткам промежуточных выражений.

Функция: funmake (F, [arg_1, ..., arg_n])

Возвращает выражение F(arg_1, ..., arg_n). Это выражение упрощается но не вычисляется, т.е. функция F не вызывается, даже если она определена.

Функция funmake не различает обычные функции и функции-массивы. Если F есть имя функции-массива, то funmake все равно возвращает F(...) (т.е вызов функции с круглыми а не с квадратными скобками). Для функций-массивом следует использовать arraymake.

Функция funmake вычисляет свои аргументы.

Примеры:

Функция funmake, примененная к обычной Maxima функции.

(%i1) F (x, y) := y^2 - x^2;
                                   2    2
(%o1)                  F(x, y) := y  - x
(%i2) funmake (F, [a + 1, b + 1]);
(%o2)                    F(a + 1, b + 1)
(%i3) ''%;
                              2          2
(%o3)                  (b + 1)  - (a + 1)

Функция funmake, примененная к макросу.

(%i1) G (x) ::= (x - 1)/2;
                                  x - 1
(%o1)                    G(x) ::= -----
                                    2
(%i2) funmake (G, [u]);
(%o2)                         G(u)
(%i3) ''%;
                              u - 1
(%o3)                         -----
                                2

Функция funmake, примененная к функции с индексом.

(%i1) H [a] (x) := (x - 1)^a;
                                        a
(%o1)                   H (x) := (x - 1)
                         a
(%i2) funmake (H [n], [%e]);
                                       n
(%o2)               lambda([x], (x - 1) )(%e)
(%i3) ''%;
                                    n
(%o3)                       (%e - 1)
(%i4) funmake ('(H [n]), [%e]);
(%o4)                        H (%e)
                              n
(%i5) ''%;
                                    n
(%o5)                       (%e - 1)

Функция funmake, примененная к символу, не являющемуся функцией какого-либо типа.

(%i1) funmake (A, [u]);
(%o1)                         A(u)
(%i2) ''%;
(%o2)                         A(u)

Функция funmake вычисляет аргументы, но не результат.

(%i1) det(a,b,c) := b^2 -4*a*c;
                                    2
(%o1)              det(a, b, c) := b  - 4 a c
(%i2) (x : 8, y : 10, z : 12);
(%o2)                          12
(%i3) f : det;
(%o3)                          det
(%i4) funmake (f, [x, y, z]);
(%o4)                    det(8, 10, 12)
(%i5) ''%;
(%o5)                         - 284

Maxima упрощает возвращаемое funmake значение.

(%i1) funmake (sin, [%pi / 2]);
(%o1)                           1
Функция: lambda ([x_1, ..., x_m], expr_1, ..., expr_n)
Функция: lambda ([[L]], expr_1, ..., expr_n)
Функция: lambda ([x_1, ..., x_m, [L]], expr_1, ..., expr_n)

Определяет и возвращает лямбда-выражение (т.е. функцию без имени). Функция может иметь обязательные параметры x_1, ..., x_m и/или необязательные параметры L, представляемые в форме списка. Значение, возвращаемое функцией, равно expr_n. Лямбда-выражение может быть присвоено переменной и вычислено, как обычная функция. Лямбда-выражение может использоваться в тех же контекстах, где ожидается имя функции.

При вычислении функции, создаются неинициализированные локальные переменные x_1, ..., x_m. lambda может использоваться внутри block или другого lambda, и локальные переменные создаются каждый раз, как вычисляется новый блок block или lambda. Локальные переменные выглядят как глобальные для каждого внутреннего блока block или lambda. Если переменная не является локальной, то ее значение равно последнему, присвоенному в объемлющем блоке block или lambda, если таковое существует, и значению переменной в глобальном окружении в противном случае. Эта политика совпадает с обычным понятием "динамической области определения".

После определения локальных переменных, выражения с expr_1 по expr_n последовательно вычисляются. Специальная переменная %% обозначает значение предыдущего выражения. Среди выражение могут применяться throw и catch.

Команда возврата return не может использоваться в лямбда-выражении если только она не заключена в блоке block. В этом случае return определяет значение блока а не лямбда-выражения в целом, за исключением случая, когда блок является последним выражением expr_n. Аналогично, go не может использоваться в лямбда-выражении без объемлющего блока block.

Функция lambda не вычисляет свои параметры. Оператор кавычка-кавычка '' может быть использован для их вычисления.

Примеры:

(%i1) f: lambda ([x], x^2);
                                      2
(%o1)                    lambda([x], x )
(%i2) f(a);
                                2
(%o2)                          a
(%i3) lambda ([x], x^2) (a);
                                2
(%o3)                          a
(%i4) apply (lambda ([x], x^2), [a]);
                                2
(%o4)                          a
(%i5) map (lambda ([x], x^2), [a, b, c, d, e]);
                        2   2   2   2   2
(%o5)                 [a , b , c , d , e ]
(%i6) a: %pi$
(%i7) b: %e$
(%i8) g: lambda ([a], a*b);
(%o8)                   lambda([a], a b)
(%i9) b: %gamma$
(%i10) g(1/2);
                             %gamma
(%o10)                       ------
                               2
(%i11) g2: lambda ([a], a*''b);
(%o11)                lambda([a], a %gamma)
(%i12) b: %e$
(%i13) g2(1/2);
                             %gamma
(%o13)                       ------
                               2
(%i14) h: lambda ([a, b], h2: lambda ([a], a*b), h2(1/2));
                                                   1
(%o14)    lambda([a, b], h2 : lambda([a], a b), h2(-))
                                                   2
(%i15) h(%pi, %gamma);
                             %gamma
(%o15)                       ------
                               2
(%i16) i: lambda ([a], lambda ([x], a*x));
(%o16)            lambda([a], lambda([x], a x))
(%i17) i(1/2);
(%o17)                  lambda([x], a x)
(%i18) i2: lambda([a], buildq([a: a], lambda([x], a*x)));
(%o18)    lambda([a], buildq([a : a], lambda([x], a x)))
(%i19) i2(1/2);
                                     x
(%o19)                   lambda([x], -)
                                     2
(%i20) i2(1/2)(%pi);
                               %pi
(%o20)                         ---
                                2
(%i1) f : lambda ([aa, bb, [cc]], aa * cc + bb);
(%o1)          lambda([aa, bb, [cc]], aa cc + bb)
(%i2) f (foo, %i, 17, 29, 256);
(%o2)       [17 foo + %i, 29 foo + %i, 256 foo + %i]
(%i3) g : lambda ([[aa]], apply ("+", aa));
(%o3)             lambda([[aa]], apply(+, aa))
(%i4) g (17, 29, x, y, z, %e);
(%o4)                  z + y + x + %e + 46
Функция: local (v_1, ..., v_n)

Объявляет переменные v_1, ..., v_n локальными по отношению ко всем свойствам в выражении, где используется local.

Функция local не вычисляет свои аргументы. Функция local возвращает done.

Функция local может использоваться только внутри блока block, в теле функции или лямбда-выражении lambda, в функции ev, и только один раз в каждом случае.

local независима от context.

Управляющая переменная: macroexpansion

Значение по умолчанию: false

Переменная macroexpansion управляет тем, подставляется ли макро-расширение (т.е. возвращаемое значением) вместо вызова макро-функции. Подстановка может ускорить последующие вычисления но за счет увеличения памяти для хранения выражений.

false

Макро-расширение не подставляется вместо вызова макро-функции.

expand

При первом вызове макро-функции, макро-расширение сохраняется. Для последующих вызовов, макро-расширение не перевычисляется. Побочные эффекты (такие как print или присваивание глобальных переменных) осуществляются только при первом вычислении макро-функции. Макро-расширение в выражении не влияет на другие выражения, имеющие такой же вызов макро-функции.

displace

При первом вызове макро-функции, макро-расширение подставляется вместо вызова, изменяя выражение, из которого макро-функция вызывается. Для последующих вызовов, макро-расширение не перевычисляется. Побочные эффекты осуществляются только при первом вычислении макро-функции. Макро-расширение в выражении не влияет на другие выражения, имеющие такой же вызов макро-функции.

Примеры:

Если macroexpansion равна false, то макро-функция вызывается всякий раз, как вычисляется вызывающее выражение, и вызывающее выражение не изменяется.

(%i1) f (x) := h (x) / g (x);
                                  h(x)
(%o1)                     f(x) := ----
                                  g(x)
(%i2) g (x) ::= block (print ("x + 99 is equal to", x),
                       return (x + 99));
(%o2) g(x) ::= block(print("x + 99 is equal to", x), 
                                                  return(x + 99))
(%i3) h (x) ::= block (print ("x - 99 is equal to", x),
                       return (x - 99));
(%o3) h(x) ::= block(print("x - 99 is equal to", x), 
                                                  return(x - 99))
(%i4) macroexpansion: false;
(%o4)                         false
(%i5) f (a * b);
x - 99 is equal to x 
x + 99 is equal to x 
                            a b - 99
(%o5)                       --------
                            a b + 99
(%i6) dispfun (f);
                                  h(x)
(%t6)                     f(x) := ----
                                  g(x)

(%o6)                         done
(%i7) f (a * b);
x - 99 is equal to x 
x + 99 is equal to x 
                            a b - 99
(%o7)                       --------
                            a b + 99

Если macroexpansion равна expand, то макро-функция вызывается один раз, и взывающее выражение не изменяется.

(%i1) f (x) := h (x) / g (x);
                                  h(x)
(%o1)                     f(x) := ----
                                  g(x)
(%i2) g (x) ::= block (print ("x + 99 is equal to", x),
                       return (x + 99));
(%o2) g(x) ::= block(print("x + 99 is equal to", x), 
                                                  return(x + 99))
(%i3) h (x) ::= block (print ("x - 99 is equal to", x),
                       return (x - 99));
(%o3) h(x) ::= block(print("x - 99 is equal to", x), 
                                                  return(x - 99))
(%i4) macroexpansion: expand;
(%o4)                        expand
(%i5) f (a * b);
x - 99 is equal to x 
x + 99 is equal to x 
                            a b - 99
(%o5)                       --------
                            a b + 99
(%i6) dispfun (f);
                                  h(x)
(%t6)                     f(x) := ----
                                  g(x)

(%o6)                         done
(%i7) f (a * b);
                            a b - 99
(%o7)                       --------
                            a b + 99

Если macroexpansion равна expand, то макро-функция вызывается один раз, и взывающее выражение изменяется.

(%i1) f (x) := h (x) / g (x);
                                  h(x)
(%o1)                     f(x) := ----
                                  g(x)
(%i2) g (x) ::= block (print ("x + 99 is equal to", x),
                       return (x + 99));
(%o2) g(x) ::= block(print("x + 99 is equal to", x), 
                                                  return(x + 99))
(%i3) h (x) ::= block (print ("x - 99 is equal to", x),
                       return (x - 99));
(%o3) h(x) ::= block(print("x - 99 is equal to", x), 
                                                  return(x - 99))
(%i4) macroexpansion: displace;
(%o4)                       displace
(%i5) f (a * b);
x - 99 is equal to x 
x + 99 is equal to x 
                            a b - 99
(%o5)                       --------
                            a b + 99
(%i6) dispfun (f);
                                 x - 99
(%t6)                    f(x) := ------
                                 x + 99

(%o6)                         done
(%i7) f (a * b);
                            a b - 99
(%o7)                       --------
                            a b + 99
Управляющая переменная: mode_checkp

Значение по умолчанию: true

Если mode_checkp равна true, то mode_declare проверяет типы переменных, имеющих значение до вызова mode_declare.

Управляющая переменная: mode_check_errorp

Значение по умолчанию: false

Если mode_check_errorp равна true, то mode_declare вызывает ошибку.

Управляющая переменная: mode_check_warnp

Значение по умолчанию: true

Если mode_check_warnp равна true, то выводятся предупреждения о ошибках типизации.

Функция: mode_declare (y_1, mode_1, ..., y_n, mode_n)

Функция mode_declare используется для определения типов переменных или функций для последующей трансляции и компиляции. Вызов mode_declare обычно располагается в начале определения функции, в начале Maxima-программы или выполняется интерактивно в командной строке.

Параметры mode_declare являются парами, состоящими из переменной и ее типа, который может быть boolean, fixnum, number, rational или float. Вместо переменной можно использовать список переменных, которые все будут объявлены однотипными.

Если переменная является массивом, и каждый элемент этого массива, на который будут ссылаться, имеет значение, то для первой декларации границ массива следует использовать array (yi, complete, dim1, dim2, ...) а не

array(yi, dim1, dim2, ...)

Если все элементы массива имеют тип fixnum (float), то следует использовать fixnum (float) вместо complete. Кроме того, если все элементы массива имеют один тип, скажем m, то для эффективной трансляции следует использовать

mode_declare (completearray (yi), m))

Численный код с использованием массивов может работать быстрее при объявлении ожидаемого размера массива, как сделано в

mode_declare (completearray (a [10, 10]), float)

для массива с плавающей точкой размера 10 x 10.

Можно определить тип результата функции при помощи function (f_1, f_2, ...), где f_1, f_2, ... есть имена функций. Например, выражение

mode_declare ([function (f_1, f_2, ...)], fixnum)

объявляет значения, возвращаемые функциями f_1, f_2, ..., целыми числами длиной одно слово.

Функция modedeclare является синонимом mode_declare.

Функция: mode_identity (arg_1, arg_2)

Специальная форма, используемая вместе с mode_declare и macros для объявления, например, списка списков чисел с плавающей точкой или других подобных составных объектов. Первый аргумент mode_identity есть имя типа, как в mode_declare (т.е. одно из float, fixnum, number, list или any), а второй аргумент есть выражение, которое вычисляется и возвращается как значение mode_identity. Если возвращаемое значение недопустимо для декларации типа, указанного в первом аргументе, то случается ошибка или печатается предупреждение. Важно то, что тип выражения для транслятора Maxima в Lisp будет всегда определяться первым аргументом, вне зависимости от того, что происходит со вторым. Например, x: 3.3; mode_identity (fixnum, x); дает ошибку а mode_identity (flonum, x) возвращает 3.3. С этим связан ряд проблем, например, если известно, что first (l) возвращает число, то можно написать mode_identity (number, first (l)). Но более эффективно будет определить новый примитив

firstnumb (x) ::= buildq ([x], mode_identity (number, first(x)));

и использовать firstnumb всякий раз при обращении к первому элементу списка чисел.

Управляющая переменная: transcompile

Значение по умолчанию: true

Если transcompile равно true, то translate и translate_file создают декларации, которые делают транслируемый код более удобным для компиляции.

Функция compfile устанавливает transcompile: true на время своей работы.

Функция: translate (f_1, ..., f_n)
Функция: translate (functions)
Функция: translate (all)

Транслирует определенные пользователем функции f_1, ..., f_n из языка Maxima в Lisp и вычисляет результат трансляции. Обычно, транслированные функции работают быстрее оригиналов.

Вызов translate (all) или translate (functions) транслирует все определенные пользователем функции.

Транслируемые функции должны, где это возможно, содержать в начале кода вызовы mode_declare, для генерации более эффективного кода.

Например:

f (x_1, x_2, ...) := block ([v_1, v_2, ...],
    mode_declare (v_1, mode_1, v_2, mode_2, ...), ...)

где x_1, x_2, ... – параметры функции, а v_1, v_2, ... – локальные переменные.

Имена транслированных функций удаляются из списка functions если значение savedef равно false (см. ниже) и добавляются к списку props.

Не следует транслировать недостаточно отлаженные функции.

При трансляции, выражения предполагаются уже упрощенными. Если это не так, то будет сгенерирован правильный но неоптимальный код. Таким образом, не следует устанавливать переключатель simp равным false, что подавляет упрощение транслируемых выражений.

Если переключатель translate равен true, то все определяемые пользователем функции автоматически транслируются в Lisp.

Отметим, что транслируемые функции могут работать не совсем так, как до трансляции, т.к. существуют некоторые несовместимости между Lisp и Maxima версиями функции. Главным образом, функция rat, имеющая более одного параметра, и функция ratvars не должны использоваться, если некоторые переменные объявлены mode_declare каноническими рациональными выражениями (КРВ). Кроме того, prederror: false не транслируется.

Если savedef равна true, то Maxima версия сохраняется при трансляции. Это позволяет выводить определение функции при помощи dispfun и редактировать его.

Если transrun равна false, то интерпретируемые варианты будут выполняться (если они еще доступны) вместо транслированных для всех вызовов функций.

Функция translate возвращает список транслированных функций.

Функция: translate_file (maxima_filename)
Функция: translate_file (maxima_filename, lisp_filename)

Транслирует файл кода Maxima в файлд кода Lisp. Функция translate_file возвращает список трех имен файлов: имя файла Maxima, имя файла Lisp и имя файла, содержащего дополнительную информацию о трансляции. Функция translate_file вычисляет свои аргументы.

Команды translate_file ("foo.mac"); load("foo.LISP") дают тот же результат, что и batch ("foo.mac") за исключением некоторых ограничений, например, на использование '' и %.

Вызов translate_file (maxima_filename) транслирует файл Maxima maxima_filename в Lisp файл с аналогичным именем. Например, foo.mac транслируется в foo.LISP. Имя файла Maxima может включать имена директорий, и результирующий Lisp файл будет записан в ту же директорию, где располагается исходный файл Maxima.

Вызов translate_file (maxima_filename, lisp_filename) транслирует файл Maxima maxima_filename в Lisp файл lisp_filename. translate_file игнорирует расширение имени файла для lisp_filename, если таковое задано. Расширение Lisp файла всегда будет LISP. Имя Lisp файла может содержать имена директорий, и в этом случае файл будет записан в заданную директорию.

translate_file также записывает файл предупреждений транслятора, разной степени важности. Расширение имени этого файла – UNLISP. Этот файл может содержать ценную информацию, возможно туманную, для обнаружения ошибок в транслированном коде. Файл UNLISP всегда записывается в ту же директорию, где расположен исходный файл Maxima.

translate_file генерирует код, в котором некоторые декларации и определения вступают в силу сразу в процессе компиляции Lisp кода. См. также compile_file по этому поводу.

См. также tr_array_as_ref, tr_bound_function_applyp, tr_exponent, tr_file_tty_messagesp, tr_float_can_branch_complex, tr_function_call_default, tr_numer, tr_optimize_max_loop, tr_semicompile, tr_state_vars, tr_warnings_get, tr_warn_bad_function_calls, tr_warn_fexpr, tr_warn_meval, tr_warn_mode, tr_warn_undeclared, tr_warn_undefined_variable и tr_windy.

Управляющая переменная: transrun

Значение по умолчанию: true

Если transrun равна false, то для всех функций интерпретируемые варианты будут выполняться (если они еще доступны) вместо транслированных.

Управляющая переменная: tr_array_as_ref

Значение по умолчанию: true

Если translate_fast_arrays равна false, то ссылки на массивы в Lisp коде, созданном translate_file, зависят от tr_array_as_ref. Если tr_array_as_ref равна true, то имена массивов вычисляются, иначе они рассматриваются в транслированном коде как буквальные символы.

tr_array_as_ref не действует если translate_fast_arrays равна true.

Управляющая переменная: tr_bound_function_applyp

Значение по умолчанию: true

Если tr_bound_function_applyp равна true, то Maxima выдает предупреждение, если имеющая значение переменная (такая, как аргумент функции) используется как имя функции.

Например, выражение g (f, x) := f (x+1) вызовет предупреждение.

Управляющая переменная: tr_file_tty_messagesp

Значение по умолчанию: false

Если tr_file_tty_messagesp равна true, то сообщения, генерируемые translate_file в процессе трансляции, отображаются на консоли и выводятся в UNLISP файл. Если false, то сообщения выводятся только в UNLISP файл.

Управляющая переменная: tr_float_can_branch_complex

Значение по умолчанию: true

Сообщает Maxima-Lisp транслятору, что функции acos, asin, asec и acsc могут возвращать комплексные значения.

Эффект tr_float_can_branch_complex заключается в следующем. Хотя, явного влияния на результат трансляции нет, но если этот флаг равен true, то acos(x) имеет тип any, даже если x имеет тип float (как определено mode_declare). Если ли же он равен false, то acos(x) имеет тип float тогда и тоько тогда, когда x имеет тип float.

Управляющая переменная: tr_function_call_default

Значение по умолчанию: general

Если равна false, то следует вызывать meval; если expr, то предполагать Lisp функцию с фиксированными аргументами; если general, то генерируется код, подходящий для mexprs и mlexprs но не macros. general обеспечивает правильное связывание переменных в компилируемом коде. В режиме general, при трансляции F(X), если F является связанной переменной, то предполагается apply (f, [x]), и в таком виде транслируется с печатью соответствующего предупреждения. Нет необходимости выключать этот механизм. С установками по умолчанию, отсутствие предупреждений не означает полную совместимость транслированного и интерпретируемого кода.

Управляющая переменная: tr_numer

Значение по умолчанию: false

Если tr_numer равна true, то для атомов, имеющих свойство numer, например, %pi, это свойство принимается во внимание транслятором.

Управляющая переменная: tr_optimize_max_loop

Значение по умолчанию: 100

tr_optimize_max_loop есть максимальное число раз, которое цикл макро-расширения и оптимизации транслятора будет повторен при трансляции формы. Данный предел установлен для обнаружения ошибок макро-расширения и зацикливания оптимизатора.

Управляющая переменная: tr_semicompile

Значение по умолчанию: false

Если tr_semicompile равна true, то translate_file и compfile генерируют формы, которые будут макро-расширены но не скомпилированы в машинный код Lisp компилятором.

Системная переменная: tr_state_vars

Значение по умолчанию:

[transcompile, tr_semicompile, tr_warn_undeclared, tr_warn_meval,
tr_warn_fexpr, tr_warn_mode, tr_warn_undefined_variable,
tr_function_call_default, tr_array_as_ref,tr_numer]

Список переключателей, которые влияют на форму транслированного кода. Эта информация полезна для отладки транслятора. Сравнивая результат трансляции с ожидаемым для данного состояния результатом, можно обнаружить ошибки транслятора.

Функция: tr_warnings_get ()

Печатает список предупреждений, сгенерированных транслятором в процессе текущей трансляции.

Управляющая переменная: tr_warn_bad_function_calls

Значение по умолчанию: true

– выдает предупреждение в случае вызова функции, который может быть неверным из-за неправильных деклараций, сделанных во время трансляции.

Управляющая переменная: tr_warn_fexpr

Значение по умолчанию: compfile

– выдает предупреждение если встречается FEXPR. Обычно, FEXPR не должны присутствовать в транслированном коде.

Управляющая переменная: tr_warn_meval

Значение по умолчанию: compfile

– выдает предупреждение при вызове функции meval. Вызов meval означает проблему в транслированном коде.

Управляющая переменная: tr_warn_mode

Значение по умолчанию: all

– выдает предупреждение, когда переменной присваивается значение, несовместимое с ее типом.

Управляющая переменная: tr_warn_undeclared

Значение по умолчанию: compile

– управляет тем, когда печатать сообщения о необъявленных переменных.

Управляющая переменная: tr_warn_undefined_variable

Значение по умолчанию: all

– печатает предупреждение, когда встречается необъявленная переменная.

Управляющая переменная: tr_windy

Значение по умолчанию: true

– вызывает печать полезных комментариев и советов по программированию.

Функция: compile_file (filename)
Функция: compile_file (filename, compiled_filename)
Функция: compile_file (filename, compiled_filename, lisp_filename)

Транслирует файл Maxima filename в Lisp, выполняет компилятор Lisp и, если трансляция и компиляция успешны, то загружает скомпилированный код в Maxima.

compile_file возвращает список имен четырех файлов: изначального файла кода Maxima, транслированного Lisp файла, файла замечаний по трансляции и файла скомпилированного кода. Если компиляция неуспешна, то последний элемент равен false.

Некоторые декларации и определения активизируются сразу в процессе компиляции Lisp кода (без загрузки скомпилированного кода). Сюда относятся функции, определенные при помощи оператора :=, макросы, определенные при помощи ::=, alias, declare, define_variable, mode_declare и infix, matchfix, nofix, postfix, prefix а также compfile.

Присваивания и вызовы функций не вычисляются до загрузки скомпилированного файла. В частности, присваивания флагам трансляции (tr_numer и т.п.) внутри Maxima файла не оказывают влияния на результат трансляции.

Файл filename не может содержать специальные :lisp команды.

Функция compile_file вычисляет свои аргументы.

Функция: declare_translated (f_1, f_2, ...)

При трансляции кода Maxima в код Lisp, транслятору важно знать, какие функции следует вызывать как транслированные или компилированные, а какие как обычные Maxima функции или неопределенные. Данная декларация, помещенная в начале транслируемого файла, дает транслятору информацию, что хотя f_n и не имеет свойство Lisp функции во время трансляции, но будет иметь таковое в момент вызова. Если транслятор не знает, что fn будет Lisp функцией, то генерируется код (MFUNCTION-CALL fn arg1 arg2 ...).


Next: , Previous: Определение функций, Up: Top   [Contents][Index]

38 Программы Maxima


Next: , Previous: Программы Maxima, Up: Программы Maxima   [Contents][Index]

38.1 Введение в программирование на Maxima

Maxima предоставляет цикл do, для итерации, а также более простые управляющие конструкции, такие как go.


Previous: Введение в программирование на Maxima, Up: Программы Maxima   [Contents][Index]

38.2 Функции и переменные для программирования на Maxima

Функция: backtrace ()
Функция: backtrace (n)

Печатает стек вызовов, т.е. список функций, которые вызывают текущую активную функцию.

Вызов backtrace() печатает весь стек вызовов.

Вызов backtrace (n) печатает n последних функций, включая текущую.

Функция backtrace может вызываться внутри программы, функции или из интерактивного приглашение а не только из контекста отладки.

Примеры:

Специальный оператор: do

Команда do используется для выполнения итераций. Т.к. команда do довольно обща, то она будет описана в двух частях. Сначала будет описана обычная форма, аналогична используемым в нескольких других языках программирования (Fortran, Algol, PL/I и т.д.). Далее будут описаны другие возможности.

Существует три формы команды, отличающиеся только условием завершения. А именно:

(Как альтернатива, команда step может быть задана после условия завершения или границы.)

Параметры initial_value, increment, limit и body могут быть произвольными выражениями. Если приращение равно 1, то команда "step 1" может быть опущена.

Перед выполнение команды do, переменной variable (далее называемой управляющей переменной) присваивается начальное значение initial_value. Далее: (1) если значение управляющей переменной превышает верхнюю границу, задаваемую thru, или если условие unless равно true, или условие while равно false, то do завершается. (2) Вычисляется body. (3) Приращение добавляется к управляющей переменой. Шаги (1) – (3) повторяются до выполнения условия завершения. Можно задавать несколько условий завершения. В этом случае команда do завершается при удовлетворении любого из них.

Обычно тест thru выполняется, когда управляющая переменная становится больше limit, когда приращение increment неотрицательно, или, если переменная становится меньше limit, когда приращение increment отрицательно. Параметры increment и limit могут быть нечисловыми выражениями, если может быть определено их неравенство. Однако, если increment не является синтаксически отрицательным (например, отрицательным числом) в момент начала выполнения команды do, то Maxima предполагает положительность increment во время выполнения do. Если на самом деле increment окажется неположительным, то do может не завершиться надлежащим образом.

Отметим, что limit, increment и условие завершения вычисляются заново для каждой итерации. Таким образом, если какое-либо из этих выражений требует длительного вычисления, но не меняется от итерации к итерации при вычислении body, то будет более эффективным присвоить их значение переменной до выполнения do и использовать эту переменную.

Значение, обычно возвращаемое командой do, есть атом done. Однако, функция return может быть использована внутри body для завершения do и задания возвращаемого значения. Отметим, что вызов return внутри цикла do, расположенного в блоке block, завершает do а не блок block. Функция go не может быть использована для выхода из команды do в объемлющий блок block.

Управляющая переменная всегда локальна в рамках do, т.е. эту переменную можно использовать внутри цикла и это не окажет влияния на переменную с тем же именем вне do. После завершения do, управляющая переменная остается несвязанной.

(%i1) for a:-3 thru 26 step 7 do display(a)$
                             a = - 3

                              a = 4

                             a = 11

                             a = 18

                             a = 25
(%i1) s: 0$
(%i2) for i: 1 while i <= 10 do s: s+i;
(%o2)                         done
(%i3) s;
(%o3)                          55

Отметим, что условие while i <= 10 эквивалентно условию unless i > 10 или условию thru 10.

(%i1) series: 1$
(%i2) term: exp (sin (x))$
(%i3) for p: 1 unless p > 7 do
          (term: diff (term, x)/p, 
           series: series + subst (x=0, term)*x^p)$
(%i4) series;
                  7    6     5    4    2
                 x    x     x    x    x
(%o4)            -- - --- - -- - -- + -- + x + 1
                 90   240   15   8    2

что дает 8 членов ряда Тейлора для e^sin(x).

(%i1) poly: 0$
(%i2) for i: 1 thru 5 do
          for j: i step -1 thru 1 do
              poly: poly + i*x^j$
(%i3) poly;
                  5      4       3       2
(%o3)          5 x  + 9 x  + 12 x  + 14 x  + 15 x
(%i4) guess: -3.0$
(%i5) for i: 1 thru 10 do
          (guess: subst (guess, x, 0.5*(x + 10/x)),
           if abs (guess^2 - 10) < 0.00005 then return (guess));
(%o5)                  - 3.162280701754386

В этом примере вычисляется отрицательный квадратный корень числа 10 с использованием метода Ньютона-Рафсона с максимальным числом итераций 10. Если условие сходимости не будет выполнено, то возвращается значение done.

Вместо добавления значения к управляющей переменной возможен другой способ ее изменения на каждом цикле итерации. В этом случае можно использовать next expression вместо step increment. Что вызывает присваивание управляющей переменной значения expression при каждой итерации.

(%i6) for count: 2 next 3*count thru 20 do display (count)$
                            count = 2

                            count = 6

                           count = 18

Синтаксис for variable from value ...do... может быть использован как альтернатива for variable: value ...do.... Что позволяет располагать from value после значений step или next, или после условия завершения. Если from value опущено, то в качестве начального значения предполагается 1.

Иногда требуется выполнить итерации без использования управляющей переменной. В этом случае можно задать только условие завершения без команд инициализации и изменения управляющей переменной, как сделано в следующем примере, вычисляющем квадратный корень числа 5 при неточном затравочном значении.

(%i1) x: 1000$
(%i2) thru 20 do x: 0.5*(x + 5.0/x)$
(%i3) x;
(%o3)                   2.23606797749979
(%i4) sqrt(5), numer;
(%o4)                   2.23606797749979

Если необходимо, то можно полностью опустить условия завершения и использовать только do body, что вызывает бесконечное вычисление body. В этом случае для завершения do следует использовать return.

(%i1) newton (f, x):= ([y, df, dfx], df: diff (f ('x), 'x),
          do (y: ev(df), x: x - f(x)/y, 
              if abs (f (x)) < 5e-6 then return (x)))$
(%i2) sqr (x) := x^2 - 5.0$
(%i3) newton (sqr, 1000);
(%o3)                   2.236068027062195

(Заметим, что return вызывает возвращение текущего значения x в качестве значения do. Блок block завершается, и значение do возвращается в качестве значения блока, т.к. do является последней командой block.)

В Maxima доступна еще одна форма команды do. Ее синтаксис:

for variable in list end_tests do body

Элементы списка list (произвольные выражения) последовательно присваиваются переменной variable Для каждой итерации вычисления body. Необязательное условие end_tests может использоваться для завершения do, иначе цикл завершится при исчерпании list или при выполнении return внутри body. (На самом деле, list может быть любым неатомарным выражением, последовательные части которого будут использованы в итерации.)

(%i1)  for f in [log, rho, atan] do ldisp(f(1))$
(%t1)                                  0
(%t2)                                rho(1)
                                     %pi
(%t3)                                 ---
                                      4
(%i4) ev(%t3,numer);
(%o4)                             0.78539816
Функция: errcatch (expr_1, ..., expr_n)

Вычисляет одно за другим выражения expr_1, ..., expr_n и, если не возникает ошибок, возвращает [expr_n] (список). Если при вычислении одного из аргументов возникает ошибка, то errcatch предотвращает дальнейшее распространение ошибки и возвращает пустой список [] без дальнейшего вычисления аргументов.

Функция errcatch полезна в пакетных batch файлах, если ожидается возможное возникновение ошибки, что без перехвата ошибки приводит к завершению batch.

Функция: error (expr_1, ..., expr_n)
Системная переменная: error

Вычисляет и печатает expr_1, ..., expr_n, и затем вызывает ошибку, что возвращает управление на верхний уровень Maxima или ближайшему объемлющему errcatch.

Значением переменной error является список, описывающий ошибку. Первый элемент error – строка форматирования, которая объединяет все строки из параметров expr_1, ..., expr_n, остальные элементы – есть значения нестроковых аргументов.

Функция errormsg() форматирует и печатает error, что повторяет печать самой последней ошибки.

Функция: errormsg ()

Повторяет печать самой последней ошибки. Информация об ошибке содержится в переменной error, и errormsg форматирует и печатает ее.

Специальный оператор: for

Используется в циклах. См. do для описания средств Maxima для организации итераций.

Функция: go (tag)

Используется внутри блока block для передачи управления на команду, помеченную параметром go. Для пометки команды в блоке, перед ней помещают другую команду в виде атома (метки). Например:

block ([x], x:1, loop, x+1, ..., go(loop), ...)

Аргументом go должна быть метка, определенная в том же блоке block. Нельзя использовать go для передачи управления на метку в блоке отличном от того, где находится сама команда go.

Специальный оператор: if

Условное вычисление. Существуют различные формы условного выражения if.

if cond_1 then expr_1 else expr_0 вычисляет и возвращает значение expr_1, если значение cond_1 равно true, иначе вычисляет и возвращает значение expr_0.

if cond_1 then expr_1 elseif cond_2 then expr_2 elseif ... else expr_0 вычисляет и возвращает значение expr_k, если cond_k равно true а все предыдущие условия равны false. Если не одно из условий не равно true, то вычисляется и возвращается значение expr_0.

Если завершающее else отсутствует, то в конце подразумевается else false. Т.е. if cond_1 then expr_1 эквивалентно if cond_1 then expr_1 else false, а if cond_1 then expr_1 elseif ... elseif cond_n then expr_n эквивалентно if cond_1 then expr_1 elseif ... elseif cond_n then expr_n else false.

Альтернативы expr_0, ..., expr_n могут быть произвольными выражениями Maxima, включая вложенные if выражения. Альтернативы не упрощаются и не вычисляются до тех пор пока соответствующее условие не равно true.

Условия cond_1, ..., cond_n являются выражениями, которые потенциально или фактически вычисляются в true или false. Если значение условия не равно ни true, ни false, то поведение if управляется глобальной переменной prederror. Если prederror равна true, то любое значение условия, отличное от true или false, считается ошибкой. Иначе, условия, которые не вычисляются в true или false, считаются допустимыми и результатом вычисления является условное выражение.

Вместе с другими элементами, условия могут включать следующие логические операторы и операторы отношения.

Операция                    Символ      Тип
 
меньше                      <           отношение, инфиксный
меньше или равно            <=          отношение, инфиксный
равенство (синтаксическое)  =           отношение, инфиксный
отрицание =                 #           отношение, инфиксный
равенство (значение)        equal       отношение, функция
отрицане equal              notequal    отношение, функция
больше или равно            >=          отношение, инфиксный
больше                      >           отношение, инфиксный
и                           and         логический, инфиксный
или                         or          логический, инфиксный
нет                         not         логический, префиксный
Функция: map (f, expr_1, ..., expr_n)

Возвращает выражение, с оператором верхнего уровня таким же как у выражений expr_1, ..., expr_n но аргументы которого являются результатами применения f к соответствующим аргументам выражений expr_i. Здесь, f – либо функция n аргументов, либо lambda выражение с n аргументами.

Если переменная maperror равна false, то map: (1) остановится на самом коротком выражении expr_i, если не все expr_i имеют одинаковую длину; (2) применит f к [expr_1, expr_2,...], если не все expr_i имеют одинаковый тип. Если maperror равна true, то в оба вышеуказанных случая считаются ошибкой.

Одним из применений функции map является применение какой-либо функции (например, partfrac) к каждому члену большого выражения вместо применения ее к выражению целиком, что может привести к слишком сложным вычислениям и, как следствие, к нехватке памяти.

(%i1) map(f,x+a*y+b*z);
(%o1)                        f(b z) + f(a y) + f(x)
(%i2) map(lambda([u],partfrac(u,x)),x+1/(x^3+4*x^2+5*x+2));
                           1       1        1
(%o2)                     ----- - ----- + -------- + x
                         x + 2   x + 1          2
                                         (x + 1)
(%i3) map(ratsimp, x/(x^2+x)+(y^2+y)/y);
                                      1
(%o3)                            y + ----- + 1
                                    x + 1
(%i4) map("=",[a,b],[-0.5,3]);
(%o4)                          [a = - 0.5, b = 3]


Функция: mapatom (expr)

Возвращает true тогда и только тогда, когда выражение expr рассматривается map-процедурами как атомарное выражение. К таким "mapatoms" относятся атомы, числа (включая рациональные) и переменные с индексом.

Управляющая переменная: maperror

Значение по умолчанию: true

Если переменная maperror равна false, то все map функции, например:

map (f, expr_1, expr_2, ...)

(1) остановится на самом коротком выражении expr_i, если не все expr_i имеют одинаковую длину; (2) применит f к [expr_1, expr_2,...], если не все expr_i имеют одинаковый тип.

Если maperror равна true, то в оба вышеуказанных случая считаются ошибками.

Управляющая переменная: mapprint

Значение по умолчанию: true

Если переменная mapprint равна true, то функции map, mapl и fullmap в определенных ситуациях выдают различные сообщения. Включая ситуации, когда map использует apply или map обрезает до самого короткого списка.

Если mapprint равна false, то данные сообщения подавляются.

Функция: maplist (f, expr_1, ..., expr_n)

Возвращает список с f, примененной к частям выражений expr_1, ..., expr_n. f – есть имя функции или лямбда-выражение.

Функция maplist отличается от map (f, expr_1, ..., expr_n), которая возвращает выражение с главным оператором, одним для всех выражений expr_i (за исключеним упрощений и случая, когда map выполняет apply).

Управляющая переменная: prederror

Значение по умолчанию: false

Если prederror равна true, то ошибка случается всякий раз, как только вычисленное значение предиката команды if или функции is отлично от true или false.

Если false, то в этом случае возвращается unknown. Работа с prederror: false не поддерживается транслированном коде. Однако, maybe поддерживается в транслированном коде.

См. также is и maybe.

Функция: return (value)

Используется для явного выхода из блока, делая value значением этого блока. См. block для более детального описания.

Функция: scanmap (f, expr)
Функция: scanmap (f, expr, bottomup)

Применяет функцию f к expr рекурсивно начиная с верхнего уровня и глубже. Это может быть полезно, если, например, требуется полная факторизация:

(%i1) exp:(a^2+2*a+1)*y + x^2$
(%i2) scanmap(factor,exp);
                                    2      2
(%o2)                         (a + 1)  y + x

Отметим, что то, как scanmap применяет данную функцию factor к подвыражениям expr, зависит от формы этого выражения. И если дана другая форма expr, то результат scanmap может быть другим. Так, %o2 не получится, если scanmap применить к раскрытому варианту exp:

(%i3) scanmap(factor,expand(exp));
                           2                  2
(%o3)                      a  y + 2 a y + y + x

Еще один пример рекурсивного применения scanmap ко всем подвыражениям, включая экспоненты:

(%i4) expr : u*v^(a*x+b) + c$
(%i5) scanmap('f, expr);
                    f(f(f(a) f(x)) + f(b))
(%o5) f(f(f(u) f(f(v)                      )) + f(c))

scanmap (f, expr, bottomup) применяет f к expr с самого глубокого уровня вверх. Например, для неопределенной функции f,

scanmap(f,a*x+b) ->
   f(a*x+b) -> f(f(a*x)+f(b)) -> f(f(f(a)*f(x))+f(b))
scanmap(f,a*x+b,bottomup) -> f(a)*f(x)+f(b)
    -> f(f(a)*f(x))+f(b) ->
     f(f(f(a)*f(x))+f(b))

В данном случае результат одинаков для обоих вариантов вызова.

Функция: throw (expr)

Вычисляет выражение expr и "бросает" его значение вверх до ближайшего catch. Функции throw и catch реализуют механизм нелокального возврата.

Специальный оператор: while
Специальный оператор: unless

См. do.

Функция: outermap (f, a_1, ..., a_n)

Применяет функцию f к каждому элементу внешнего произведения a_1 x a_2 ... x a_n.

f – есть имя функции с n аргументами или лямбда-выражение с n аргументами. Каждый элемент a_k может быть списком, списком списков, матрицей или любым другим выражением.

Значение outermap является вложенной структурой. Пусть x является возвращаемым значением. Тогда x имеет ту же структуру, как первый аргумент (список, список списков или матрица), x[i_1]...[i_m] имеет ту же структуру, как второй аргумент (список, список списков или матрица), x[i_1]...[i_m][j_1]...[j_n] имеет ту же структуру, как третий аргумент (список, список списков или матрица), и т.д., где m, n, ... – есть число индексов, необходимых для для доступа к элементам каждого из аргументов (один для списка, два для матрицы, еще один для вложенного списка). Аргументы, не являющиеся списками и матрицами, не оказывают влияния на возвращаемое значение.

Отметим, что результат outermap отличается от применения f ко всем элементам внешнего произведения, возвращаемого cartesian_product. Функция outermap сохраняет структуру аргументов в возвращаемом значении, а cartesian_product нет.

Функция outermap вычисляет свои аргументы.

См. также map, maplist и apply.

Примеры:

Простые примеры outermap. Для прояснения комбинации аргументов, F оставлена неопределенной.

(%i1) outermap (F, [a, b, c], [1, 2, 3]);
(%o1) [[F(a, 1), F(a, 2), F(a, 3)], [F(b, 1), F(b, 2), F(b, 3)], 
                                     [F(c, 1), F(c, 2), F(c, 3)]]
(%i2) outermap (F, matrix ([a, b], [c, d]), matrix ([1, 2], [3, 4]));
         [ [ F(a, 1)  F(a, 2) ]  [ F(b, 1)  F(b, 2) ] ]
         [ [                  ]  [                  ] ]
         [ [ F(a, 3)  F(a, 4) ]  [ F(b, 3)  F(b, 4) ] ]
(%o2)    [                                            ]
         [ [ F(c, 1)  F(c, 2) ]  [ F(d, 1)  F(d, 2) ] ]
         [ [                  ]  [                  ] ]
         [ [ F(c, 3)  F(c, 4) ]  [ F(d, 3)  F(d, 4) ] ]
(%i3) outermap (F, [a, b], x, matrix ([1, 2], [3, 4]));
       [ F(a, x, 1)  F(a, x, 2) ]  [ F(b, x, 1)  F(b, x, 2) ]
(%o3) [[                        ], [                        ]]
       [ F(a, x, 3)  F(a, x, 4) ]  [ F(b, x, 3)  F(b, x, 4) ]
(%i4) outermap (F, [a, b], matrix ([1, 2]), matrix ([x], [y]));
       [ [ F(a, 1, x) ]  [ F(a, 2, x) ] ]
(%o4) [[ [            ]  [            ] ], 
       [ [ F(a, 1, y) ]  [ F(a, 2, y) ] ]
                              [ [ F(b, 1, x) ]  [ F(b, 2, x) ] ]
                              [ [            ]  [            ] ]]
                              [ [ F(b, 1, y) ]  [ F(b, 2, y) ] ]
(%i5) outermap ("+", [a, b, c], [1, 2, 3]);
(%o5) [[a + 1, a + 2, a + 3], [b + 1, b + 2, b + 3], 
                                           [c + 1, c + 2, c + 3]]

Более детальное исследование работы outermap. Первый, второй и третий аргументы являются матрицей, списком и матрицей соответственно. Возвращаемое значение является матрицей. Каждый элемент этой матрицы есть список, и каждый элемент данного списка – матрица.

(%i1) arg_1 :  matrix ([a, b], [c, d]);
                            [ a  b ]
(%o1)                       [      ]
                            [ c  d ]
(%i2) arg_2 : [11, 22];
(%o2)                       [11, 22]
(%i3) arg_3 : matrix ([xx, yy]);
(%o3)                      [ xx  yy ]
(%i4) xx_0 : outermap (lambda ([x, y, z], x / y + z), arg_1, 
                                                     arg_2, arg_3);
               [  [      a        a  ]  [      a        a  ]  ]
               [ [[ xx + --  yy + -- ], [ xx + --  yy + -- ]] ]
               [  [      11       11 ]  [      22       22 ]  ]
(%o4)  Col 1 = [                                              ]
               [  [      c        c  ]  [      c        c  ]  ]
               [ [[ xx + --  yy + -- ], [ xx + --  yy + -- ]] ]
               [  [      11       11 ]  [      22       22 ]  ]
                 [  [      b        b  ]  [      b        b  ]  ]
                 [ [[ xx + --  yy + -- ], [ xx + --  yy + -- ]] ]
                 [  [      11       11 ]  [      22       22 ]  ]
         Col 2 = [                                              ]
                 [  [      d        d  ]  [      d        d  ]  ]
                 [ [[ xx + --  yy + -- ], [ xx + --  yy + -- ]] ]
                 [  [      11       11 ]  [      22       22 ]  ]
(%i5) xx_1 : xx_0 [1][1];
           [      a        a  ]  [      a        a  ]
(%o5)     [[ xx + --  yy + -- ], [ xx + --  yy + -- ]]
           [      11       11 ]  [      22       22 ]
(%i6) xx_2 : xx_0 [1][1] [1];
                      [      a        a  ]
(%o6)                 [ xx + --  yy + -- ]
                      [      11       11 ]
(%i7) xx_3 : xx_0 [1][1] [1] [1][1];
                                  a
(%o7)                        xx + --
                                  11
(%i8) [op (arg_1), op (arg_2), op (arg_3)];
(%o8)                  [matrix, [, matrix]
(%i9) [op (xx_0), op (xx_1), op (xx_2)];
(%o9)                  [matrix, [, matrix]

Функция outermap сохраняет структуру аргументов в возвращаемом значении, а cartesian_product нет.

(%i1) outermap (F, [a, b, c], [1, 2, 3]);
(%o1) [[F(a, 1), F(a, 2), F(a, 3)], [F(b, 1), F(b, 2), F(b, 3)], 
                                     [F(c, 1), F(c, 2), F(c, 3)]]
(%i2) setify (flatten (%));
(%o2) {F(a, 1), F(a, 2), F(a, 3), F(b, 1), F(b, 2), F(b, 3), 
                                       F(c, 1), F(c, 2), F(c, 3)}
(%i3) map (lambda ([L], apply (F, L)), 
(%o3) {F(a, 1), F(a, 2), F(a, 3), F(b, 1), F(b, 2), F(b, 3), 
                                       F(c, 1), F(c, 2), F(c, 3)}
(%i4) is (equal (%, %th (2)));
(%o4)                         true

Next: , Previous: Программы Maxima, Up: Top   [Contents][Index]

39 Отладка


Next: , Up: Отладка   [Contents][Index]

39.1 Отладка на уровне исходного кода

Maxima имеет отладчик исходного кода. Пользователь может определить в функции точку останова и и продолжить выполнение с этой точки строка за строкой. При этом возможно анализировать стек вызовов и переменные, имеющие значение на данном уровне.

Команда :help, или просто :h, выводит список команд отладчика. (Команды могут быть сокращены, если сокращение однозначно. Если оно неоднозначно, то будет выведен список альтернатив.) В отладчике пользователь может также использовать обычные команды Maxima для исследования, определения и манипулирования переменными и выражениями.

Точка останова задается командой :br в командной строке Maxima. В отладчике, пользователь может продвигаться по одной строке за раз с помощью команды :n (“next”). Команда :bt (“backtrace”) выводит список кадров стека. Команда :r (“resume”) завершает отладчик и продолжает выполнение программы. Данные команды проиллюстрированы в следующем примере.

(%i1) load ("/tmp/foobar.mac");

(%o1)                           /tmp/foobar.mac

(%i2) :br foo
Turning on debugging debugmode(true)
Bkpt 0 for foo (in /tmp/foobar.mac line 1) 

(%i2) bar (2,3);
Bkpt 0:(foobar.mac 1)
/tmp/foobar.mac:1::

(dbm:1) :bt                        <-- :bt выводим обратную трассировку вызовов
#0: foo(y=5)(foobar.mac line 1)
#1: bar(x=2,y=3)(foobar.mac line 9)

(dbm:1) :n                         <-- :n продвигаем выполнение на одну строку
(foobar.mac 2)
/tmp/foobar.mac:2::

(dbm:1) :n                         <-- :n продвигаем выполнение на одну строку
(foobar.mac 3)
/tmp/foobar.mac:3::

(dbm:1) u;                         <-- Исследуем знасение переменной u
28

(dbm:1) u: 33;                     <-- Устанавливаем значение u равным 33
33

(dbm:1) :r                         <-- :r to возобновляем выполнение программы

(%o2)                                1094

Содержимое файла /tmp/foobar.mac:

foo(y) := block ([u:y^2],
  u: u+3,
  u: u^2,
  u);
 
bar(x,y) := (
  x: x+2,
  y: y+2,
  x: foo(y),
  x+y);

Использование Отладчика в Редакторе Emacs

Если пользователь выполняет программу в командном окне отладчика (dbl) редактора GNU emacs или в графической оболочке Xmaxima, то при достижении точки останова в другой части окна будет показан участок исходного кода с текущей строкой, выделенной либо красным цветом, либо маленькой стрелкой. Пользователь может продолжить выполнение программы построчно, нажимая M-n (Alt-n).

Для использования в Emacs отладчика dbl требуется файл dbl.el, расположенный в директории elisp. Убедитесь, что файлы elisp установлены или добавьте директорию elisp программы Maxima к пути: например, добавте следующие строки к файлу .emacs или файлу site-init.el

(setq load-path (cons "/usr/share/maxima/5.9.1/emacs" load-path))
(autoload 'dbl "dbl")

После этого при вводе

M-x dbl

в emacs должно открываться командное окно, в котором можно выполнять программы, например, Maxima, gcl, gdb и т.д. Это командное окно “знает” об отладке исходного кода, который открыт в другом окне редактора.

Пользователь может установить точку останова в определенной строке кода, нажав на C-x space. При этом производится анализ: в какой функции находится данная строка и на какой по порядку строке этой функции стоит курсор. Если курсор расположен, скажем, на строке 2 функции foo, тогда в командном окно будет введена команда “:br foo 2”, которая задает точку останова на второй строке функции foo. Для того, чтобы все это работало необходимо, чтобы в окне файла foobar.mac был включен режим maxima-mode.el. Существуют еще дополнительные команды, доступные в таком окне, такие как вычисление функций Maxima при нажатии Alt-Control-x.


Next: , Previous: Отладка исходного кода, Up: Отладка   [Contents][Index]

39.2 Специальные команды

Специальные команды, это ключевые слова, которые не интерпретируются Maxima как обычные выражения. Специальные команды вводятся в командной строке Maxima или отладчика, но не в точке останова. Все специальные команды начинаются с двоеточия ’:’. Например, для вычисления Lisp формы можно ввести :lisp с последующей формой.

(%i1) :lisp (+ 2 3) 
5

Число параметров зависит от конкретной команды. Кроме того, не обязательно вводить всю команду целиком, достаточно ввести столько, чтобы сделать команду однозначно определенной среди всех ключевых слов. Таким образом, для :break достаточно ввести :br.

Специальные команды перечислены ниже:

:break F n

Задает точку останова в функции F на строке номер n от ее начала. Если F является строкой, тогда он рассматривается как файл и смещение n отсчитывается от начала этого файла. Смещение является необязательным. Если оно не указано, то предполагается равным нулю (первая строка функции или файла).

:bt

Выводит обратную трассировку кадров стека

:continue

Продолжает вычисление

:delete

Удаляет заданную точку останова или все, если ни одна не задана

:disable

Деактивирует заданную точку останова или все, если ни одна не задана

:enable

Активирует заданную точку останова или все, если ни одна не задана

:frame n

Выводит кадр стека номер n или текущий кадр, если номер не указан

:help

Печатает справку по указанной команде или по всем если ни одна не задана

:info

Печатает информацию об элементе

:lisp some-form

Вычисляет some-form в качестве Lisp формы

:lisp-quiet some-form

Вычисляет Lisp форму some-form без вывода результата

:next

Как :step, но :next пропускает вызовы функций

:quit

Выход из текущего уровня отладчика без завершение вычислений

:resume

Продолжает вычисление

:step

Продолжает вычисление до достижения новой строки

:top

Возвращает на уровень командного приглашения Maxima с любого уровня отладчика без завершения вычислений


Previous: Специальные команды, Up: Отладка   [Contents][Index]

39.3 Функции и переменные для отладки

Управляющая переменная: refcheck

Значение по умолчанию: false

Если refcheck равна true, то Maxima печатает сообщение каждый раз как имеющая значение переменная используется в вычислении первый раз.

Управляющая переменная: setcheck

Значение по умолчанию: false

Если setcheck равно списку переменных (возможно с индексом), то Maxima печатает сообщение всякий раз как переменным, или переменным с индексом, присваивается значение при помощи обычного оператора присваивания :, или оператора присваивания ::, или при связывании параметров функций, но не при определении функций := или макросов ::=. Сообщение содержит имя переменной и присваиваемое значение.

Переменной setcheck может быть присвоено значение all или true, что подразумевает все переменные.

Каждое присваивание setcheck устанавливает новый список контролируемых переменных и все переменные, которые ранее были в списке setcheck, забываются.

Переменные, присваиваемые setcheck должны быть экранированы, иначе они могут быть вычислены. Например, если переменные x, y и z уже имеют значения, тогда

setcheck: ['x, 'y, 'z]$

устанавливает контроль присваивания для этих переменных.

Сообщение не выводится, если переменной, включенной в список setcheck, присваивается значение равное ей самой, например, X: 'X.

Управляющая переменная: setcheckbreak

Значение по умолчанию: false

Если setcheckbreak равно true, то Maxima генерирует прерывание всякий раз как переменной из списка setcheck присваивается новое значение. Прерывание случается до присваивания нового значения. В этот момент, переменная setval содержит новое значение переменной. Таким образом, возможно присвоить переменной другое значение путем присваивания его переменной setval.

См. также setcheck и setval.

Системная переменная: setval

Содержит новое значение, которое будет присвоено переменной, если случается прерывание, контролируемое setcheckbreak. Таким образом, возможно присвоить переменной другое значение путем присваивания его переменной setval.

См. также setcheck и setcheckbreak.

Функция: timer (f_1, ..., f_n)
Функция: timer (all)
Функция: timer ()

Добавляет функции f_1, ..., f_n к списку функций, для которых собирается статистика тайминга. Последовательные вызовы timer(f)$ timer(g)$ сначала добавляют к списку f а затем g, т.е. список пополняется от одного вызова timer к другому.

timer(all) добавляет все пользовательские функции, которые определяются глобальной переменной functions, к списку контролируемых функций.

Без аргументов, timer возвращает список контролируемых функций.

Maxima сохраняет информацию о времени выполнения контролируемых функций. Функция timer_info возвращает статистику тайминга, включающую: среднее время выполнения, число вызовов и полное время выполнения. Функция untimer удаляет функцию из списка контролируемых функций.

timer не вычисляет свои аргументы. Команды f(x) := x^2$ g:f$ timer(g)$ не добавят f к списку тайминг-контроля.

Если действует трассировка trace(f), то timer(f) не работает, т.к. trace и timer не могут действовать одновременно.

См. также timer_devalue.

Функция: untimer (f_1, ..., f_n)
Функция: untimer ()

Удаляет функции f_1, ..., f_n из списка тайминг-контроля.

Без аргументов, untimer удаляет все функции из списка тайминг-контроля.

После выполнения untimer (f), функция timer_info (f) продолжает содержать ранее собранную статистику, хотя timer_info() (без аргументов) не возвращает информацию о функциях, которые на данный момент не включены в список тайминг-контроля. Вызов timer (f) обнуляет всю предыдущую статистику и снова добавляет f к списку тайминг-контроля.

Управляющая переменная: timer_devalue

Значение по умолчанию: false

Если timer_devalue равно true, то Maxima вычитает из статистики контролируемой функции время выполнения других контролируемых функций. В противном случае, статистика каждой функции включает время, затраченное на выполнение других функций. Заметим, что время, затраченное на выполнение неконтролируемых функций, не вычитается из общего времени.

См. также timer и timer_info.

Функция: timer_info (f_1, ..., f_n)
Функция: timer_info ()

Для функций f_1, ..., f_n, возвращает матрицу, содержащую информацию о тайминге каждой из функций. Без аргументов, timer_info возвращает информацию для всех контролируемых функций.

Матрица, возвращаемая timer_info, содержит: имя функции, среднее время вызова функции, число вызовов, общее время и gctime, что обозначает "время сборки мусора" в Macsyma, но сейчас это время всегда равно нулю.

Данные, сообщаемые timer_info, могут быть получены другим способом при помощи функции get:

get(f, 'calls);  get(f, 'runtime);  get(f, 'gctime);

См. также timer.

Функция: trace (f_1, ..., f_n)
Функция: trace (all)
Функция: trace ()

Устанавливает трассировку для функций f_1, ..., f_n, т.е. Maxima будет печатать отладочную информацию при каждом вызове любой из этих функций. Последовательные вызовы trace(f)$ trace(g)$ сначала включает трассировку f а затем трассировку g, т.е. список трассируемых функций пополняется от одного вызова trace к другому.

trace(all) включает трассировку для всех пользовательских функций, которые определяются глобальной переменной functions.

Без аргументов, trace возвращает список всех трассируемых функций.

Функция untrace отменяет трассировку. См. также trace_options.

Функция trace не вычисляет свои аргументы. Команды f(x) := x^2$ g:f$ trace(g)$ не добавят f к списку трассируемых функций.

Если функция переопределяется, то она удаляется из списка трассируемых функций. Т.е. после timer(f)$ f(x) := x^2$, функция f трассироваться не будет.

Если действует timer (f), то trace (f) не работает; т.к. trace и timer не могут действовать одновременно.

Функция: trace_options (f, option_1, ..., option_n)
Функция: trace_options (f)

Устанавливает опции трассировки для функции f. Любые предыдущие опции переопределяются. trace_options (f, ...) не действует если не включена трассировка trace (f) (либо до, либо после вызова trace_options).

trace_options (f) возвращает все опции в значение "по умолчанию".

Существуют следующие ключевые слова опций трассировки:

Опции трассировки могут задаваться двумя способами. Одно ключевое слово включает соответствующую опцию безусловно. Заметим, что для включения опции foo не следует указывать foo: true, кроме того, опции не надо экранировать. Ключевое слово с предикатом включает опцию условно в зависимости от значения предиката.

Существуют следующие аргументы предиката [level, direction, function, item], где level есть уровень рекурсии; direction есть либо enter, либо exit; function есть имя функции; и item есть список аргументов (при входе) или возвращаемое значение (при выходе).

Пример применения безусловных опций трассировки:

(%i1) ff(n) := if equal(n, 0) then 1 else n * ff(n - 1)$

(%i2) trace (ff)$

(%i3) trace_options (ff, lisp_print, break)$

(%i4) ff(3);

Ниже, та же функция условной опцией трассировки break:

(%i5) trace_options (ff, break(pp))$

(%i6) pp (level, direction, function, item) := block (print (item),
    return (function = 'ff and level = 3 and direction = exit))$

(%i7) ff(6);
Функция: untrace (f_1, ..., f_n)
Функция: untrace ()

Отменяет трассировку функций f_1, ..., f_n, установленную ранее при помощи trace. Без аргументов, untrace отменяет трассировку всех функций.

Функция untrace возвращает список функций, для которых была отменена трассировка.


Next: , Previous: Отладка, Up: Top   [Contents][Index]

40 Пакет augmented_lagrangian


Previous: Пакет augmented_lagrangian, Up: Пакет augmented_lagrangian   [Contents][Index]

40.1 Функции и переменные пакета augmented_lagrangian

Функция: augmented_lagrangian_method (FOM, xx, C, yy)
Функция: augmented_lagrangian_method (FOM, xx, C, yy, optional_args)

Возвращает приближенный минимум выражения FOM по переменным xx, при связях C, равных нулю. yy – список затравочных начальных значений xx. Для нахождения минимума используется метод расширенного лагранжиана (см. [1] и [2]).

optional_args – дополнительные аргументы, задаваемые в форме symbol = value. Допустимы следующие дополнительные аргументы:

niter

Число итераций алгоритма расширенного лагранжиана

lbfgs_tolerance

Допустимое отклонение для LBFGS

iprint

Параметр IPRINT (список двух целых чисел, которые управляют уровнем вывода) для LBFGS

%lambda

Начальное значение %lambda для вычисления расширенного лагранжиана

Данная реализация минимизирует расширенный лагранжиан методом BFGS с ограничением памяти (LBFGS), являющимся квази-нюьтоновым алгоритмом.

Команда load("augmented_lagrangian") загружает данную функцию.

См. также lbfgs.

Ссылки:

[1] http://www-fp.mcs.anl.gov/otc/Guide/OptWeb/continuous/constrained/nonlinearcon/auglag.html

[2] http://www.cs.ubc.ca/spider/ascher/542/chap10.pdf

Пример:

(%i1) load ("lbfgs");
(%o1)     /maxima/share/lbfgs/lbfgs.mac
(%i2) load ("augmented_lagrangian");
(%o2) 
   /maxima/share/contrib/augmented_lagrangian.mac
(%i3) FOM: x^2 + 2*y^2;
                               2    2
(%o3)                       2 y  + x
(%i4) xx: [x, y];
(%o4)                        [x, y]
(%i5) C: [x + y - 1];
(%o5)                      [y + x - 1]
(%i6) yy: [1, 1];
(%o6)                        [1, 1]
(%i7) augmented_lagrangian_method(FOM, xx, C, yy, iprint=[-1,0]);
(%o7) [[x = 0.66665984108002, y = 0.33334027245545], 
                                 %lambda = [- 1.333337940892525]]

Next: , Previous: Пакет augmented_lagrangian, Up: Top   [Contents][Index]

41 Пакет bode


Previous: Пакет bode, Up: Пакет bode   [Contents][Index]

41.1 Функции и переменные пакета bode

Функция: bode_gain (H, range, ...plot_opts...)

Функция для построения амплитудной диаграммы Боде.

Примеры (c 1 по 7 из

8 от Ron Crummett):

(%i1) load("bode")$

(%i2) H1 (s) := 100 * (1 + s) / ((s + 10) * (s + 100))$

(%i3) bode_gain (H1 (s), [w, 1/1000, 1000])$

(%i4) H2 (s) := 1 / (1 + s/omega0)$

(%i5) bode_gain (H2 (s), [w, 1/1000, 1000]), omega0 = 10$

(%i6) H3 (s) := 1 / (1 + s/omega0)^2$

(%i7) bode_gain (H3 (s), [w, 1/1000, 1000]), omega0 = 10$

(%i8) H4 (s) := 1 + s/omega0$

(%i9) bode_gain (H4 (s), [w, 1/1000, 1000]), omega0 = 10$

(%i10) H5 (s) := 1/s$

(%i11) bode_gain (H5 (s), [w, 1/1000, 1000])$

(%i12) H6 (s) := 1/((s/omega0)^2 + 2 * zeta * (s/omega0) + 1)$

(%i13) bode_gain (H6 (s), [w, 1/1000, 1000]), 
                  omega0 = 10, zeta = 1/10$

(%i14) H7 (s) := (s/omega0)^2 + 2 * zeta * (s/omega0) + 1$

(%i15) bode_gain (H7 (s), [w, 1/1000, 1000]),
                  omega0 = 10, zeta = 1/10$

(%i16) H8 (s) := 0.5 / (0.0001 * s^3 + 0.002 * s^2 + 0.01 * s)$

(%i17) bode_gain (H8 (s), [w, 1/1000, 1000])$

Для использования этой функции необходимо сначала выполнить load("bode"). См. также bode_phase

Функция: bode_phase (H, range, ...plot_opts...)

Функция для построения фазовой диаграммы Боде.

Примеры (с 1 по 7 из

8 от Ron Crummett):

(%i1) load("bode")$

(%i2) H1 (s) := 100 * (1 + s) / ((s + 10) * (s + 100))$

(%i3) bode_phase (H1 (s), [w, 1/1000, 1000])$

(%i4) H2 (s) := 1 / (1 + s/omega0)$

(%i5) bode_phase (H2 (s), [w, 1/1000, 1000]), omega0 = 10$

(%i6) H3 (s) := 1 / (1 + s/omega0)^2$

(%i7) bode_phase (H3 (s), [w, 1/1000, 1000]), omega0 = 10$

(%i8) H4 (s) := 1 + s/omega0$

(%i9) bode_phase (H4 (s), [w, 1/1000, 1000]), omega0 = 10$

(%i10) H5 (s) := 1/s$

(%i11) bode_phase (H5 (s), [w, 1/1000, 1000])$

(%i12) H6 (s) := 1/((s/omega0)^2 + 2 * zeta * (s/omega0) + 1)$

(%i13) bode_phase (H6 (s), [w, 1/1000, 1000]), 
                   omega0 = 10, zeta = 1/10$

(%i14) H7 (s) := (s/omega0)^2 + 2 * zeta * (s/omega0) + 1$

(%i15) bode_phase (H7 (s), [w, 1/1000, 1000]), 
                   omega0 = 10, zeta = 1/10$

(%i16) H8 (s) := 0.5 / (0.0001 * s^3 + 0.002 * s^2 + 0.01 * s)$

(%i17) bode_phase (H8 (s), [w, 1/1000, 1000])$

(%i18) block ([bode_phase_unwrap : false],
              bode_phase (H8 (s), [w, 1/1000, 1000]));

(%i19) block ([bode_phase_unwrap : true], 
              bode_phase (H8 (s), [w, 1/1000, 1000]));

Для использования этой функции необходимо сначала выполнить load("bode"). См. также bode_gain


Next: , Previous: Пакет bode, Up: Top   [Contents][Index]

42 Пакет contrib_ode


Next: , Previous: Пакет contrib_ode, Up: Пакет contrib_ode   [Contents][Index]

42.1 Введение в пакет contrib_ode

Стандартная процедура Maxima для решения обычных дифференциальных уравнений (ОДУ) ode2 решает элементарные линейные ОДУ первого и второго порядка. Функция contrib_ode расширяет ode2 дополнительными методами для линейных и нелинейных ОДУ первого порядка и линейных однородных ОДУ второго порядка. Даная программа находится в состоянии развития и форма вызова функций может измениться в последующих релизах. После стабилизации код может быть перемещен из директории contrib и интегрирован в ядро Maxima.

Для использования пакет должен быть загружен с помощью команды load("contrib_ode").

Функция contrib_ode вызывается также, как ode2. Она имеет три аргумента: ОДУ (если правая часть уравнения равна 0, то достаточно задать только левые части уравнений), зависимая переменная и независимая переменная. В случае успеха возвращается список решений.

Представление решений отличается от такового для ode2. Т.к. нелинейные уравнения могут иметь множественные решения., то contrib_ode возвращает список решений. Решение может иметь несколько различных форм:

%c представляет константу интегрирования для уравнений первого порядка. %k1 и %k2 – константы интегрирования для уравнений второго порядка. Если contrib_ode не может получить решение, то возвращается false, возможно, после печати сообщения об ошибке.

Необходимо возвращать список решений, т.к. нелинейные ОДУ первого порядка могут иметь множественные решения. Например:

(%i1) load("contrib_ode")$

(%i2) eqn:x*'diff(y,x)^2-(1+x*y)*'diff(y,x)+y=0;

                    dy 2             dy
(%o2)            x (--)  - (x y + 1) -- + y = 0
                    dx               dx
(%i3) contrib_ode(eqn,y,x);

                                             x
(%o3)             [y = log(x) + %c, y = %c %e ]
(%i4) method;

(%o4)                        factor

Нелинейные ОДУ могут иметь особые решения, не имеющие констант интегрирования, как второе решение в следующем примере:

(%i1) load("contrib_ode")$

(%i2) eqn:'diff(y,x)^2+x*'diff(y,x)-y=0;

                       dy 2     dy
(%o2)                 (--)  + x -- - y = 0
                       dx       dx
(%i3) contrib_ode(eqn,y,x);

                                           2
                                 2        x
(%o3)              [y = %c x + %c , y = - --]
                                          4
(%i4) method;

(%o4)                       clairault

Следующее ОДУ имеет два параметрических решение в терминах переменной %t. Из этих параметрических решений можно получить явные решения.

(%i1) load("contrib_ode")$

(%i2) eqn:'diff(y,x)=(x+y)^2;

                          dy          2
(%o2)                     -- = (y + x)
                          dx
(%i3) contrib_ode(eqn,y,x);

(%o3) [[x = %c - atan(sqrt(%t)), y = - x - sqrt(%t)], 
                     [x = atan(sqrt(%t)) + %c, y = sqrt(%t) - x]]
(%i4) method;

(%o4)                       lagrange

Следующий пример (Камке 1.112) демонстрирует неявное решение.

(%i1) load("contrib_ode")$

(%i2) assume(x>0,y>0);

(%o2)                    [x > 0, y > 0]
(%i3) eqn:x*'diff(y,x)-x*sqrt(y^2+x^2)-y;

                     dy           2    2
(%o3)              x -- - x sqrt(y  + x ) - y
                     dx
(%i4) contrib_ode(eqn,y,x);

                                  y
(%o4)                  [x - asinh(-) = %c]
                                  x
(%i5) method;

(%o5)                          lie

Следующее уравнение Рикатти преобразуется в линейное ОДУ второго порядка для переменной %u. Maxima не может решить новое уравнение, и оно возвращается нерешенным.

(%i1) load("contrib_ode")$

(%i2) eqn:x^2*'diff(y,x)=a+b*x^n+c*x^2*y^2;

                    2 dy      2  2      n
(%o2)              x  -- = c x  y  + b x  + a
                      dx
(%i3) contrib_ode(eqn,y,x);

               d%u
               ---                            2
               dx        2     n - 2   a     d %u
(%o3)  [[y = - ----, %u c  (b x      + --) + ---- c = 0]]
               %u c                     2      2
                                       x     dx
(%i4) method;

(%o4)                        riccati

Для ОДУ первого порядка contrib_ode вызывает ode2. Затем применяются методы: факторизации, Клеро, Лагранжа, Рикатти, Абеля и метод симметрий Ли. Метод Ли не применяется к уравнениям Абеля, если метод Абеля не дает результата, но применяется если метод Рикатти возвращает нерешенное ОДУ второго порядка.

Для ОДУ второго порядка contrib_ode вызывает ode2, а затем odelin.

Если выполнена команда put('contrib_ode,true,'verbose), то печатается подробная отладочная информация.


Next: , Previous: Введение в пакет contrib_ode, Up: Пакет contrib_ode   [Contents][Index]

42.2 Функции и переменные пакета contrib_ode

Функция: contrib_ode (eqn, y, x)

Возвращает список решение ОДУ eqn с независимой переменной x и зависимой переменной y.

Функция: odelin (eqn, y, x)

Функция odelin решает линейные однородные ОДУ первого и второго порядка с независимой переменной x и зависимой переменной y. Она возвращает фундаментальный набор решений ОДУ.

Для ОДУ второго порядка odelin использует метод Бронштейна-Лафаля, который ищет решение в терминах заданных специальных функций.

(%i1) load("contrib_ode");

(%i2) odelin(x*(x+1)*'diff(y,x,2)+(x+5)*'diff(y,x,1)+(-4)*y,y,x);
...trying factor method
...solving 7 equations in 4 variables
...trying the Bessel solver
...solving 1 equations in 2 variables
...trying the F01 solver
...solving 1 equations in 3 variables
...trying the spherodial wave solver
...solving 1 equations in 4 variables
...trying the square root Bessel solver
...solving 1 equations in 2 variables
...trying the 2F1 solver
...solving 9 equations in 5 variables
       gauss_a(- 6, - 2, - 3, - x)  gauss_b(- 6, - 2, - 3, - x)
(%o2) {---------------------------, ---------------------------}
                    4                            4
                   x                            x

Функция: ode_check (eqn, soln)

Возвращает значение ОДУ eqn после подстановки в него возможного решения soln. Значение эквивалентно нулю, если soln является решением eqn.

(%i1) load("contrib_ode")$

(%i2) eqn:'diff(y,x,2)+(a*x+b)*y;

                         2
                        d y
(%o2)                   --- + (a x + b) y
                          2
                        dx
(%i3) ans:[y = bessel_y(1/3,2*(a*x+b)^(3/2)/(3*a))*%k2*sqrt(a*x+b)
         +bessel_j(1/3,2*(a*x+b)^(3/2)/(3*a))*%k1*sqrt(a*x+b)];

                                  3/2
                    1  2 (a x + b)
(%o3) [y = bessel_y(-, --------------) %k2 sqrt(a x + b)
                    3       3 a
                                          3/2
                            1  2 (a x + b)
                 + bessel_j(-, --------------) %k1 sqrt(a x + b)]
                            3       3 a
(%i4) ode_check(eqn,ans[1]);

(%o4)                           0
Системная переменная: method

Переменной method присваивается название метода успешного решения ОДУ.

Переменная: %c

%c – константа интегрирования для ОДУ первого порядка.

Переменная: %k1

%k1 – первая константа интегрирования для ОЛУ второго порядка.

Переменная: %k2

%k2 – вторая константа интегрирования для ОЛУ второго порядка.

Функция: gauss_a (a, b, c, x)

Функции gauss_a(a,b,c,x) и gauss_b(a,b,c,x) есть 2F1 гипергеометрические функции. Они представляют собой два независимых решения гипергеометрического уравнения x(1-x) diff(y,x,2) + [c-(a+b+1)x diff(y,x) - aby = 0 (A&S 15.5.1).

Эти функции используются только в решениях ОДУ, возвращаемых odelin и contrib_ode. Определение и использование этих функций может измениться в последующих релизах Maxima.

См. также gauss_b, dgauss_a и gauss_b.

Функция: gauss_b (a, b, c, x)

См. gauss_a.

Функция: dgauss_a (a, b, c, x)

Производная gauss_a(a, b, c, x) по x.

Функция: dgauss_b (a, b, c, x)

Производная gauss_b(a, b, c, x) по x.

Функция: kummer_m (a, b, x)

M-функция Куммера, как она определена в Abramowitz и Stegun, Handbook of Mathematical Functions, Section 13.1.2.

Эта функция используются только в решениях ОДУ, возвращаемых odelin и contrib_ode. Определение и использование этой функции может измениться в последующих релизах Maxima.

См. также kummer_u, dkummer_m и dkummer_u.

Функция: kummer_u (a, b, x)

U-функция Куммера, как она определена в Abramowitz и Stegun, Handbook of Mathematical Functions, Section 13.1.3.

См. kummer_m.

Функция: dkummer_m (a, b, x)

Производная kummer_m(a, b, x) по x.

Функция: dkummer_u (a, b, x)

Производная kummer_u(a, b, x) по x.


Next: , Previous: Функции и переменные пакета contrib_ode, Up: Пакет contrib_ode   [Contents][Index]

42.3 Возможные улучшения пакета contrib_ode

Данные процедуры находятся в процессе разработки. Необходимо:


Next: , Previous: Возможные улучшения пакета contrib_ode, Up: Пакет contrib_ode   [Contents][Index]

42.4 Тесты пакета contrib_ode

Процедуры были протестированы на приблизительно одной тысяче примеров из книг Murphy, Kamke, Zwillinger и других. Эти тесты включены в директорию tests.


Previous: Тесты пакета contrib_ode, Up: Пакет contrib_ode   [Contents][Index]

42.5 Ссылки для пакета contrib_ode

  1. E. Kamke, Differentialgleichungen Losungsmethoden und Losungen, Vol 1, Geest & Portig, Leipzig, 1961
  2. G. M. Murphy, Ordinary Differential Equations and Their Solutions, Van Nostrand, New York, 1960
  3. D. Zwillinger, Handbook of Differential Equations, 3rd edition, Academic Press, 1998
  4. F. Schwarz, Symmetry Analysis of Abel’s Equation, Studies in Applied Mathematics, 100:269-294 (1998)
  5. F. Schwarz, Algorithmic Solution of Abel’s Equation, Computing 61, 39-49 (1998)
  6. E. S. Cheb-Terrab, A. D. Roche, Symmetries and First Order ODE Patterns, Computer Physics Communications 113 (1998), p 239. (http://lie.uwaterloo.ca/papers/ode_vii.pdf)
  7. E. S. Cheb-Terrab, T. Koloknikov, First Order ODEs, Symmetries and Linear Transformations, European Journal of Applied Mathematics, Vol. 14, No. 2, pp. 231-246 (2003). (http://arxiv.org/abs/math-ph/0007023, http://lie.uwaterloo.ca/papers/ode_iv.pdf)
  8. G. W. Bluman, S. C. Anco, Symmetry and Integration Methods for Differential Equations, Springer, (2002)
  9. M. Bronstein, S. Lafaille, Solutions of linear ordinary differential equations in terms of special functions, Proceedings of ISSAC 2002, Lille, ACM Press, 23-28. (http://www-sop.inria.fr/cafe/Manuel.Bronstein/publications/issac2002.pdf)

Next: , Previous: Пакет contrib_ode, Up: Top   [Contents][Index]

43 Пакет descriptive


Next: , Previous: Пакет descriptive, Up: Пакет descriptive   [Contents][Index]

43.1 Введение в пакет descriptive

Пакет descriptive содержит набор функций для выполнения вычислений и визуализации данных в рамках описательной статистики. Вместе с исходным кодом пакета Maxima включает также три набора данных: pidigits.data, wind.data и biomed.data.

Для справки по функциям пакета descriptive можно использовать любое статистическое руководство.

Для комментариев, сообщений об ошибках и предложений обращайтесь к автору пакета по адресу ’mario AT edu DOT xunta DOT es’.

Ниже приведен простой пример использования функций пакета descriptive в зависимости от природы своих аргументов

(%i1) load ("descriptive")$
(%i2) /* univariate sample */   mean ([a, b, c]);
                            c + b + a
(%o2)                       ---------
                                3
(%i3) matrix ([a, b], [c, d], [e, f]);
                            [ a  b ]
                            [      ]
(%o3)                       [ c  d ]
                            [      ]
                            [ e  f ]
(%i4) /* multivariate sample */ mean (%);
                      e + c + a  f + d + b
(%o4)                [---------, ---------]
                          3          3

Отметим, что для многомерной выборки среднее вычисляется для каждой колонки.

В случае нескольких выборок, возможно различного размера, для получения результата для каждой выборки можно использовать функцию map

(%i1) load ("descriptive")$
(%i2) map (mean, [[a, b, c], [d, e]]);
                        c + b + a  e + d
(%o2)                  [---------, -----]
                            3        2

В этом случае в списке находятся две выборки длины 3 и 2.

Одномерные выборки представляются списками

(%i1) s1 : [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
(%o1)           [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

а многомерные выборки, матрицами

(%i1) s2 : matrix ([13.17, 9.29], [14.71, 16.88], [18.50, 16.88],
             [10.58, 6.63], [13.33, 13.25], [13.21,  8.12]);
                        [ 13.17  9.29  ]
                        [              ]
                        [ 14.71  16.88 ]
                        [              ]
                        [ 18.5   16.88 ]
(%o1)                   [              ]
                        [ 10.58  6.63  ]
                        [              ]
                        [ 13.33  13.25 ]
                        [              ]
                        [ 13.21  8.12  ]

В этом случае число колонок равно размерности случайной переменной, а число строк есть размер выборки.

Данные могут быть введены в ручную, но большие выборки обычно хранятся в текстовых файлах. Например, файл pidigits.data содержит первые 100 цифр числа %pi:

      3
      1
      4
      1
      5
      9
      2
      6
      5
      3 ...

Для загрузки этих данных в Maxima следует делать так

(%i1) load ("numericalio")$
(%i2) s1 : read_list (file_search ("pidigits.data"))$
(%i3) length (s1);
(%o3)                          100

С другой стороны, файл wind.data содержит дневные средние значения скорости ветра для 5 метеорологических станций в Ирландии (Это часть данных, взятых с 12 метеорологических станций. Исходные данные свободно доступны в StatLib Data Repository и их анализ обсуждается в Haslett, J., Raftery, A. E. (1989) Space-time Modelling with Long-memory Dependence: Assessing Ireland’s Wind Power Resource, with Discussion. Applied Statistics 38, 1-50). Данные загружаются при помощи:

(%i1) load ("numericalio")$
(%i2) s2 : read_matrix (file_search ("wind.data"))$
(%i3) length (s2);
(%o3)                          100
(%i4) s2 [%]; /* last record */
(%o4)            [3.58, 6.0, 4.58, 7.62, 11.25]

Некоторые выборки содержат нечисловые данные. Например, файл biomed.data (являющийся частью другого большого набора данных из StatLib Data Repository) содержит четыре измерения крови взятые от двух групп пациентов разного возраста A и B

(%i1) load ("numericalio")$
(%i2) s3 : read_matrix (file_search ("biomed.data"))$
(%i3) length (s3);
(%o3)                          100
(%i4) s3 [1]; /* first record */
(%o4)            [A, 30, 167.0, 89.0, 25.6, 364]

Первый пациент принадлежит группе A, возраст 30 лет, и его/ее измерения крови есть 167.0, 89.0, 25.6 и 364.

При работе с категоризированными данными следует соблюдать осторожность. В следующем примере символу a присвоено значение до задания катигоризированной выборки

(%i1) a : 1$
(%i2) matrix ([a, 3], [b, 5]);
                            [ 1  3 ]
(%o2)                       [      ]
                            [ b  5 ]

Next: , Previous: Введение в пакет descriptive, Up: Пакет descriptive   [Contents][Index]

43.2 Функции и переменные для манипулирования данными

Функция: continuous_freq (list)
Функция: continuous_freq (list, m)

Аргумент continuous_freq должен быть списком чисел, которые группируются в интервалы и вычисляется число чисел в каждом из интервалов. Необязательный второй аргумент continuous_freq задает число интервалов, по умолчанию 10,

(%i1) load ("numericalio")$
(%i2) load ("descriptive")$
(%i3) s1 : read_list (file_search ("pidigits.data"))$
(%i4) continuous_freq (s1, 5);
(%o4) [[0, 1.8, 3.6, 5.4, 7.2, 9.0], [16, 24, 18, 17, 25]]

Первый список содержит границы интервалов, а второй содержит число чисел в соответствующем интервале: 16 цифр в интервале [0, 1.8], что есть 0 или 1, 24 цифры в интервале (1.8, 3.6], что есть 2 и 3, и т.д.

Функция: discrete_freq (list)

Вычисляет абсолютные частоты для дискретной выборки, как числовой так и категоризированной. Ее единственный аргумент является списком

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s1 : read_list (file_search ("pidigits.data"));
(%o3) [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3, 8, 
4, 6, 2, 6, 4, 3, 3, 8, 3, 2, 7, 9, 5, 0, 2, 8, 8, 4, 1, 9, 7, 
1, 6, 9, 3, 9, 9, 3, 7, 5, 1, 0, 5, 8, 2, 0, 9, 7, 4, 9, 4, 4, 
5, 9, 2, 3, 0, 7, 8, 1, 6, 4, 0, 6, 2, 8, 6, 2, 0, 8, 9, 9, 8, 
6, 2, 8, 0, 3, 4, 8, 2, 5, 3, 4, 2, 1, 1, 7, 0, 6, 7]
(%i4) discrete_freq (s1);
(%o4) [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 
                             [8, 8, 12, 12, 10, 8, 9, 8, 12, 13]]

Первый список значения в выборке, а второй их абсолютные частоты. Команды ? col и ? transpose должны помочь понять последний ввод.

Функция: subsample (data_matrix, logical_expression)
Функция: subsample (data_matrix, logical_expression, col_num1, col_num2, ...)

Является некоторым вариантом Maxima функции submatrix. Первый аргумент – имя матрицы данных, второй – экранированное логическое выражение, необязательные последующие аргументы – номера колонок, которые необходимо выбрать. Работу функции лучше всего проиллюстрировать на примерах

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s2 : read_matrix (file_search ("wind.data"))$
(%i4) subsample (s2, '(%c[1] > 18));
              [ 19.38  15.37  15.12  23.09  25.25 ]
              [                                   ]
              [ 18.29  18.66  19.08  26.08  27.63 ]
(%o4)         [                                   ]
              [ 20.25  21.46  19.95  27.71  23.38 ]
              [                                   ]
              [ 18.79  18.96  14.46  26.38  21.84 ]

Это многомерная выборка в которой скорость ветра в первой метеорологической станции превышает 18. В экранированном логическом выражении i-й компонент данных обозначается %c[i]. Символ %c[i] используется внутри subsample, что вызывает проблемы если этот символ используется для обозначения категории в категоризированных данных. В следующем примере мы затребуем только первую, вторую и пятую компоненту записей, для которых скорость ветра больше или равна 16 на станции номер 1 и менее 25 узлов на станции номер 4

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s2 : read_matrix (file_search ("wind.data"))$
(%i4) subsample (s2, '(%c[1] >= 16 and %c[4] < 25), 1, 2, 5);
                     [ 19.38  15.37  25.25 ]
                     [                     ]
                     [ 17.33  14.67  19.58 ]
(%o4)                [                     ]
                     [ 16.92  13.21  21.21 ]
                     [                     ]
                     [ 17.25  18.46  23.87 ]

Далле приведен пример с категоризированными переменными из biomed.data. Мы выбираем записи, которые соответствуют пациентам в группе B старше 38 лет

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s3 : read_matrix (file_search ("biomed.data"))$
(%i4) subsample (s3, '(%c[1] = B and %c[2] > 38));
                [ B  39  28.0  102.3  17.1  146 ]
                [                               ]
                [ B  39  21.0  92.4   10.3  197 ]
                [                               ]
                [ B  39  23.0  111.5  10.0  133 ]
                [                               ]
                [ B  39  26.0  92.6   12.3  196 ]
(%o4)           [                               ]
                [ B  39  25.0  98.7   10.0  174 ]
                [                               ]
                [ B  39  21.0  93.2   5.9   181 ]
                [                               ]
                [ B  39  18.0  95.0   11.3  66  ]
                [                               ]
                [ B  39  39.0  88.5   7.6   168 ]

Вероятно статистический анализ будет включать только измерения крови

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s3 : read_matrix (file_search ("biomed.data"))$
(%i4) subsample (s3, '(%c[1] = B and %c[2] > 38), 3, 4, 5, 6);
                   [ 28.0  102.3  17.1  146 ]
                   [                        ]
                   [ 21.0  92.4   10.3  197 ]
                   [                        ]
                   [ 23.0  111.5  10.0  133 ]
                   [                        ]
                   [ 26.0  92.6   12.3  196 ]
(%o4)              [                        ]
                   [ 25.0  98.7   10.0  174 ]
                   [                        ]
                   [ 21.0  93.2   5.9   181 ]
                   [                        ]
                   [ 18.0  95.0   11.3  66  ]
                   [                        ]
                   [ 39.0  88.5   7.6   168 ]

Это многомерное среднее значение s3

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s3 : read_matrix (file_search ("biomed.data"))$
(%i4) mean (s3);
       65 B + 35 A  317          6 NA + 8145.0
(%o4) [-----------, ---, 87.178, -------------, 18.123, 
           100      10                100
                                                    3 NA + 19587
                                                    ------------]
                                                        100

Здесь, первая компонента бессмыслена, т.к. A и B представляют категории, вторая компонента – средний возраст пациентов в форме рационального числа, а четвертая и последняя компоненты демонстрируют странное поведение. Это потому, что символ NA используется для случая, когда данные недоступны (non available), а следовательно эти два средних значения бессмысленны. Возможным решением является исключение из матрицы строк с символами NA, хотя это и приводит к некоторой потере данных

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s3 : read_matrix (file_search ("biomed.data"))$
(%i4) mean(subsample(s3, '(%c[4] # NA and %c[6] # NA), 3,4,5,6));
(%o4) [79.4923076923077, 86.2032967032967, 16.93186813186813, 
                                                            2514
                                                            ----]
                                                             13

Next: , Previous: Функции и переменные для манипулирования данными, Up: Пакет descriptive   [Contents][Index]

43.3 Функции и переменные для описательной статистики

Функция: mean (list)
Функция: mean (matrix)

Среднее значение выборки, определяемое как

                       n
                     ====
             _   1   \
             x = -    >    x
                 n   /      i
                     ====
                     i = 1

Пример:

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s1 : read_list (file_search ("pidigits.data"))$
(%i4) mean (s1);
                               471
(%o4)                          ---
                               100
(%i5) %, numer;
(%o5)                         4.71
(%i6) s2 : read_matrix (file_search ("wind.data"))$
(%i7) mean (s2);
(%o7)     [9.9485, 10.1607, 10.8685, 15.7166, 14.8441]
Функция: var (list)
Функция: var (matrix)

Дисперсия выборки, определяемая как

                     n
                   ====
           2   1   \          _ 2
          s  = -    >    (x - x)
               n   /       i
                   ====
                   i = 1

Пример:

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s1 : read_list (file_search ("pidigits.data"))$
(%i4) var (s1), numer;
(%o4)                   8.425899999999999

См. также функцию var1.

Функция: var1 (list)
Функция: var1 (matrix)

Дисперсия выборки, определяемая как

                     n
                   ====
               1   \          _ 2
              ---   >    (x - x)
              n-1  /       i
                   ====
                   i = 1

Пример:

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s1 : read_list (file_search ("pidigits.data"))$
(%i4) var1 (s1), numer;
(%o4)                    8.5110101010101
(%i5) s2 : read_matrix (file_search ("wind.data"))$
(%i6) var1 (s2);
(%o6) [17.39586540404041, 15.13912778787879, 15.63204924242424, 
                            32.50152569696971, 24.66977392929294]

См. также функцию var.

Функция: std (list)
Функция: std (matrix)

Стандартное отклонение выборки, или квадратный корень функции var, дисперсии с знаменателем n.

Пример:

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s1 : read_list (file_search ("pidigits.data"))$
(%i4) std (s1), numer;
(%o4)                   2.902740084816414
(%i5) s2 : read_matrix (file_search ("wind.data"))$
(%i6) std (s2);
(%o6) [4.149928523480858, 3.871399812729241, 3.933920277534866, 
                            5.672434260526957, 4.941970881136392]

См. также функции var и std1.

Функция: std1 (list)
Функция: std1 (matrix)

Квадратный корень функции var1, дисперсии с знаменателем n-1.

Пример:

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s1 : read_list (file_search ("pidigits.data"))$
(%i4) std1 (s1), numer;
(%o4)                   2.917363553109228
(%i5) s2 : read_matrix (file_search ("wind.data"))$
(%i6) std1 (s2);
(%o6) [4.17083509672109, 3.89090320978032, 3.953738641137555, 
                            5.701010936401517, 4.966867617451963]

См. также функции var1 и std.

Функция: noncentral_moment (list, k)
Функция: noncentral_moment (matrix, k)

Нецентральный момент порядка k, определенный как

                       n
                     ====
                 1   \      k
                 -    >    x
                 n   /      i
                     ====
                     i = 1

Пример:

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s1 : read_list (file_search ("pidigits.data"))$
(%i4) noncentral_moment (s1, 1), numer; /* the mean */
(%o4)                         4.71
(%i6) s2 : read_matrix (file_search ("wind.data"))$
(%i7) noncentral_moment (s2, 5);
(%o7) [319793.8724761506, 320532.1923892463, 391249.5621381556, 
                            2502278.205988911, 1691881.797742255]

См. также функцию central_moment.

Функция: central_moment (list, k)
Функция: central_moment (matrix, k)

Центральный момент порядка k, определенный как

                    n
                  ====
              1   \          _ k
              -    >    (x - x)
              n   /       i
                  ====
                  i = 1

Пример:

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s1 : read_list (file_search ("pidigits.data"))$
(%i4) central_moment (s1, 2), numer; /* the variance */
(%o4)                   8.425899999999999
(%i6) s2 : read_matrix (file_search ("wind.data"))$
(%i7) central_moment (s2, 3);
(%o7) [11.29584771375004, 16.97988248298583, 5.626661952750102, 
                             37.5986572057918, 25.85981904394192]

См. также функции central_moment и mean.

Функция: cv (list)
Функция: cv (matrix)

Коэффициент дисперсии есть отношение стандартного отклонения std к среднему значению mean,

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s1 : read_list (file_search ("pidigits.data"))$
(%i4) cv (s1), numer;
(%o4)                   .6193977819764815
(%i5) s2 : read_matrix (file_search ("wind.data"))$
(%i6) cv (s2);
(%o6) [.4192426091090204, .3829365309260502, 0.363779605385983, 
                            .3627381836021478, .3346021393989506]

См. также функции std и mean.

Функция: mini (list)
Функция: mini (matrix)

Минимальное значение выборки list,

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s1 : read_list (file_search ("pidigits.data"))$
(%i4) mini (s1);
(%o4)                           0
(%i5) s2 : read_matrix (file_search ("wind.data"))$
(%i6) mini (s2);
(%o6)             [0.58, 0.5, 2.67, 5.25, 5.17]

См. также функцию maxi.

Функция: maxi (list)
Функция: maxi (matrix)

Максимальное значение выборки list,

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s1 : read_list (file_search ("pidigits.data"))$
(%i4) maxi (s1);
(%o4)                           9
(%i5) s2 : read_matrix (file_search ("wind.data"))$
(%i6) maxi (s2);
(%o6)          [20.25, 21.46, 20.04, 29.63, 27.63]

См. также функцию mini.

Функция: range (list)
Функция: range (matrix)

Разница между экстремальными значениями выборки.

Пример:

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s1 : read_list (file_search ("pidigits.data"))$
(%i4) range (s1);
(%o4)                           9
(%i5) s2 : read_matrix (file_search ("wind.data"))$
(%i6) range (s2);
(%o6)          [19.67, 20.96, 17.37, 24.38, 22.46]
Функция: quantile (list, p)
Функция: quantile (matrix, p)

Есть p-квантиль выборки list, где p есть число в пределах [0, 1]. Хотя существует несколько определений квантили (Hyndman, R. J., Fan, Y. (1996) Sample quantiles in statistical packages. American Statistician, 50, 361-365), в пакете descriptive используется определение, основанное на линейной интерполяции.

Пример:

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s1 : read_list (file_search ("pidigits.data"))$
(%i4) /* 1st and 3rd quartiles */
         [quantile (s1, 1/4), quantile (s1, 3/4)], numer;
(%o4)                      [2.0, 7.25]
(%i5) s2 : read_matrix (file_search ("wind.data"))$
(%i6) quantile (s2, 1/4);
(%o6)    [7.2575, 7.477500000000001, 7.82, 11.28, 11.48]
Функция: median (list)
Функция: median (matrix)

Когда выборка упорядочена, то, если размер выборки нечетен, что медиана есть центральное значение, иначе она есть среднее двух центральных значений.

Пример:

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s1 : read_list (file_search ("pidigits.data"))$
(%i4) median (s1);
                                9
(%o4)                           -
                                2
(%i5) s2 : read_matrix (file_search ("wind.data"))$
(%i6) median (s2);
(%o6)         [10.06, 9.855, 10.73, 15.48, 14.105]

Медиана есть 1/2-квантиль.

См. также функцию quantile.

Функция: qrange (list)
Функция: qrange (matrix)

Интерквартильный размах есть разница между третьей и первой квартилью quantile(list,3/4) - quantile(list,1/4),

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s1 : read_list (file_search ("pidigits.data"))$
(%i4) qrange (s1);
                               21
(%o4)                          --
                               4
(%i5) s2 : read_matrix (file_search ("wind.data"))$
(%i6) qrange (s2);
(%o6) [5.385, 5.572499999999998, 6.0225, 8.729999999999999, 
                                               6.650000000000002]

См. также функцию quantile.

Функция: mean_deviation (list)
Функция: mean_deviation (matrix)

Среднее отклонение, определяемое как

                     n
                   ====
               1   \          _
               -    >    |x - x|
               n   /       i
                   ====
                   i = 1

Пример:

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s1 : read_list (file_search ("pidigits.data"))$
(%i4) mean_deviation (s1);
                               51
(%o4)                          --
                               20
(%i5) s2 : read_matrix (file_search ("wind.data"))$
(%i6) mean_deviation (s2);
(%o6) [3.287959999999999, 3.075342, 3.23907, 4.715664000000001, 
                                               4.028546000000002]

См. также функцию mean.

Функция: median_deviation (list)
Функция: median_deviation (matrix)

Медианное отклонение, определенное как

                 n
               ====
           1   \
           -    >    |x - med|
           n   /       i
               ====
               i = 1

где med есть медиана выборки list.

Пример:

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s1 : read_list (file_search ("pidigits.data"))$
(%i4) median_deviation (s1);
                                5
(%o4)                           -
                                2
(%i5) s2 : read_matrix (file_search ("wind.data"))$
(%i6) median_deviation (s2);
(%o6)           [2.75, 2.755, 3.08, 4.315, 3.31]

См. также функцию mean.

Функция: harmonic_mean (list)
Функция: harmonic_mean (matrix)

Гармоническое среднее, определенное как

                  n
               --------
                n
               ====
               \     1
                >    --
               /     x
               ====   i
               i = 1

Пример:

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) y : [5, 7, 2, 5, 9, 5, 6, 4, 9, 2, 4, 2, 5]$
(%i4) harmonic_mean (y), numer;
(%o4)                   3.901858027632205
(%i5) s2 : read_matrix (file_search ("wind.data"))$
(%i6) harmonic_mean (s2);
(%o6) [6.948015590052786, 7.391967752360356, 9.055658197151745, 
                            13.44199028193692, 13.01439145898509]

См. также функции mean и geometric_mean.

Функция: geometric_mean (list)
Функция: geometric_mean (matrix)

Геометрическое среднее, определенное как

                 /  n      \ 1/n
                 | /===\   |
                 |  ! !    |
                 |  ! !  x |
                 |  ! !   i|
                 | i = 1   |
                 \         /

Пример:

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) y : [5, 7, 2, 5, 9, 5, 6, 4, 9, 2, 4, 2, 5]$
(%i4) geometric_mean (y), numer;
(%o4)                   4.454845412337012
(%i5) s2 : read_matrix (file_search ("wind.data"))$
(%i6) geometric_mean (s2);
(%o6) [8.82476274347979, 9.22652604739361, 10.0442675714889, 
                            14.61274126349021, 13.96184163444275]

См. также функции mean и harmonic_mean.

Функция: kurtosis (list)
Функция: kurtosis (matrix)

Коэффициент куртозиса, определенный как

                    n
                  ====
            1     \          _ 4
           ----    >    (x - x)  - 3
              4   /       i
           n s    ====
                  i = 1

Пример:

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s1 : read_list (file_search ("pidigits.data"))$
(%i4) kurtosis (s1), numer;
(%o4)                  - 1.273247946514421
(%i5) s2 : read_matrix (file_search ("wind.data"))$
(%i6) kurtosis (s2);
(%o6) [- .2715445622195385, 0.119998784429451, 
   - .4275233490482866, - .6405361979019522, - .4952382132352935]

См. также функции mean, var и skewness.

Функция: skewness (list)
Функция: skewness (matrix)

Коэффициент асимметрии, определенный как

                    n
                  ====
            1     \          _ 3
           ----    >    (x - x)
              3   /       i
           n s    ====
                  i = 1

Пример:

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s1 : read_list (file_search ("pidigits.data"))$
(%i4) skewness (s1), numer;
(%o4)                  .009196180476450306
(%i5) s2 : read_matrix (file_search ("wind.data"))$
(%i6) skewness (s2);
(%o6) [.1580509020000979, .2926379232061854, .09242174416107717, 
                            .2059984348148687, .2142520248890832]

См. также функции mean, var и kurtosis.

Функция: pearson_skewness (list)
Функция: pearson_skewness (matrix)

Коэффициент асимметрии Парсона, определенные как

                _
             3 (x - med)
             -----------
                  s

где med – медиана list.

Пример:

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s1 : read_list (file_search ("pidigits.data"))$
(%i4) pearson_skewness (s1), numer;
(%o4)                   .2159484029093895
(%i5) s2 : read_matrix (file_search ("wind.data"))$
(%i6) pearson_skewness (s2);
(%o6) [- .08019976629211892, .2357036272952649, 
         .1050904062491204, .1245042340592368, .4464181795804519]

См. также функции mean, var и median.

Функция: quartile_skewness (list)
Функция: quartile_skewness (matrix)

Коэффициент квартильной асимметрии, определенный как

               c    - 2 c    + c
                3/4      1/2    1/4
               --------------------
                   c    - c
                    3/4    1/4

где c_p есть p-квартиль выборки list.

Пример:

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s1 : read_list (file_search ("pidigits.data"))$
(%i4) quartile_skewness (s1), numer;
(%o4)                  .04761904761904762
(%i5) s2 : read_matrix (file_search ("wind.data"))$
(%i6) quartile_skewness (s2);
(%o6) [- 0.0408542246982353, .1467025572005382, 
       0.0336239103362392, .03780068728522298, 0.210526315789474]

См. также функцию quantile.


Next: , Previous: Функции и переменные для описательной статистики, Up: Пакет descriptive   [Contents][Index]

43.4 Функции и переменные для многомерной описательной статистики

Функция: cov (matrix)

Матрица ковариации многомерной выборки, определенная как

              n
             ====
          1  \           _        _
      S = -   >    (X  - X) (X  - X)'
          n  /       j        j
             ====
             j = 1

где X_j есть j-й столбец матрицы выборки.

Пример:

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s2 : read_matrix (file_search ("wind.data"))$
(%i4) fpprintprec : 7$  /* change precision for pretty output */
(%i5) cov (s2);
      [ 17.22191  13.61811  14.37217  19.39624  15.42162 ]
      [                                                  ]
      [ 13.61811  14.98774  13.30448  15.15834  14.9711  ]
      [                                                  ]
(%o5) [ 14.37217  13.30448  15.47573  17.32544  16.18171 ]
      [                                                  ]
      [ 19.39624  15.15834  17.32544  32.17651  20.44685 ]
      [                                                  ]
      [ 15.42162  14.9711   16.18171  20.44685  24.42308 ]

См. также функцию cov1.

Функция: cov1 (matrix)

Матрица ковариации многомерной выборки, определенная как

              n
             ====
         1   \           _        _
   S  = ---   >    (X  - X) (X  - X)'
    1   n-1  /       j        j
             ====
             j = 1

где X_j есть j-й столбец матрицы выборки.

Пример:

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s2 : read_matrix (file_search ("wind.data"))$
(%i4) fpprintprec : 7$ /* change precision for pretty output */
(%i5) cov1 (s2);
      [ 17.39587  13.75567  14.51734  19.59216  15.5774  ]
      [                                                  ]
      [ 13.75567  15.13913  13.43887  15.31145  15.12232 ]
      [                                                  ]
(%o5) [ 14.51734  13.43887  15.63205  17.50044  16.34516 ]
      [                                                  ]
      [ 19.59216  15.31145  17.50044  32.50153  20.65338 ]
      [                                                  ]
      [ 15.5774   15.12232  16.34516  20.65338  24.66977 ]

См. также функцию cov.

Функция: global_variances (matrix)
Функция: global_variances (matrix, logical_value)

Функция global_variances возвращает список глобальных измерений дисперсии:

где p есть размерность многомерной случайной переменной а S_1 есть матрица ковариации, возвращаемая cov1.

Пример:

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s2 : read_matrix (file_search ("wind.data"))$
(%i4) global_variances (s2);
(%o4) [105.338342060606, 21.06766841212119, 12874.34690469686, 
         113.4651792608502, 6.636590811800794, 2.576158149609762]

Функция global_variances имеет необязательный логический аргумент: global_variances(x,true) сообщает Maxima, что x есть матрица данных, что дает результат идентичный global_variances(x). С другой стороны, global_variances(x,false) означает, что x не является матрицей данных а является матрицей ковариации, что позволяет избежать перевычисления

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s2 : read_matrix (file_search ("wind.data"))$
(%i4) s : cov1 (s2)$
(%i5) global_variances (s, false);
(%o5) [105.338342060606, 21.06766841212119, 12874.34690469686, 
         113.4651792608502, 6.636590811800794, 2.576158149609762]

См. также cov и cov1.

Функция: cor (matrix)
Функция: cor (matrix, logical_value)

Матрица корреляции многомерной выборки.

Пример:

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) fpprintprec:7$
(%i4) s2 : read_matrix (file_search ("wind.data"))$
(%i5) cor (s2);
      [   1.0     .8476339  .8803515  .8239624  .7519506 ]
      [                                                  ]
      [ .8476339    1.0     .8735834  .6902622  0.782502 ]
      [                                                  ]
(%o5) [ .8803515  .8735834    1.0     .7764065  .8323358 ]
      [                                                  ]
      [ .8239624  .6902622  .7764065    1.0     .7293848 ]
      [                                                  ]
      [ .7519506  0.782502  .8323358  .7293848    1.0    ]

Функция cor имеет необязательный логический аргумент: cor(x,true) сообщает Maxima, что x есть матрица данных, что дает результат идентичный cor(x). С другой стороны, cor(x,false) означает, что x не является матрицей данных а является матрицей ковариации, что позволяет избежать перевычисления

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) fpprintprec:7$
(%i4) s2 : read_matrix (file_search ("wind.data"))$
(%i5) s : cov1 (s2)$
(%i6) cor (s, false); /* this is faster */
      [   1.0     .8476339  .8803515  .8239624  .7519506 ]
      [                                                  ]
      [ .8476339    1.0     .8735834  .6902622  0.782502 ]
      [                                                  ]
(%o6) [ .8803515  .8735834    1.0     .7764065  .8323358 ]
      [                                                  ]
      [ .8239624  .6902622  .7764065    1.0     .7293848 ]
      [                                                  ]
      [ .7519506  0.782502  .8323358  .7293848    1.0    ]

См. также cov и cov1.

Функция: list_correlations (matrix)
Функция: list_correlations (matrix, logical_value)

Функция list_correlations возвращает список мер корреляции:

Пример:

(%i1) load ("descriptive")$
(%i2) load ("numericalio")$
(%i3) s2 : read_matrix (file_search ("wind.data"))$
(%i4) z : list_correlations (s2)$
(%i5) fpprintprec : 5$ /* for pretty output */
(%i6) z[1];  /* precision matrix */
      [  .38486   - .13856   - .15626   - .10239    .031179  ]
      [                                                      ]
      [ - .13856   .34107    - .15233    .038447   - .052842 ]
      [                                                      ]
(%o6) [ - .15626  - .15233    .47296    - .024816  - .10054  ]
      [                                                      ]
      [ - .10239   .038447   - .024816   .10937    - .034033 ]
      [                                                      ]
      [ .031179   - .052842  - .10054   - .034033   .14834   ]
(%i7) z[2];  /* multiple correlation vector */
(%o7)       [.85063, .80634, .86474, .71867, .72675]
(%i8) z[3];  /* partial correlation matrix */
       [  - 1.0     .38244   .36627   .49908   - .13049 ]
       [                                                ]
       [  .38244    - 1.0    .37927  - .19907   .23492  ]
       [                                                ]
(%o8)  [  .36627    .37927   - 1.0    .10911    .37956  ]
       [                                                ]
       [  .49908   - .19907  .10911   - 1.0     .26719  ]
       [                                                ]
       [ - .13049   .23492   .37956   .26719    - 1.0   ]

Функция list_correlations имеет необязательный логический аргумент: list_correlations(x,true) сообщает Maxima, что x есть матрица данных, что дает результат идентичный list_correlations(x). С другой стороны, list_correlations(x,false) означает, что x не является матрицей данных а является матрицей ковариации, что позволяет избежать перевычисления

См. также cov и cov1.


Previous: Функции и переменные для многомерной описательной статистики, Up: Пакет descriptive   [Contents][Index]

43.5 Функции и переменные для статистических графиков

Функция: histogram (list)
Функция: histogram (list, option_1, option_2, ...)
Функция: histogram (one_column_matrix)
Функция: histogram (one_column_matrix, option_1, option_2, ...)
Функция: histogram (one_row_matrix)
Функция: histogram (one_row_matrix, option_1, option_2, ...)

Эта функция строит гистограмму для непрерывной выборки. Данные выборки должны быть представлены в виде списка или одномерной матрицы.

Доступны следующие опции:

См. также discrete_freq и continuous_freq для подсчета данных, и bars и barsplot для построения гистограмм непрерывных данных.

Примеры:

Простая гистограмма с восемью классами.

(%i1) load ("descriptive")$
(%i2) s1 : read_list (file_search ("pidigits.data"))$
(%i3) histogram (
        s1,
        nclasses     = 8,
        title        = "pi digits",
        xlabel       = "digits",
        ylabel       = "Absolute frequency",
        fill_color   = grey,
        fill_density = 0.6)$
Функция: scatterplot (list)
Функция: scatterplot (list, option_1, option_2, ...)
Функция: scatterplot (matrix)
Функция: scatterplot (matrix, option_1, option_2, ...)

Строит корреляционную диаграмму (scatter diagrams) для одномерной (list) или многомерной (matrix) выборки.

Доступны следующие опции:

Примеры:

Одномерная корреляционная диаграмма для гауссовой выборки.

(%i1) load ("descriptive")$
(%i2) load ("distrib")$
(%i3) scatterplot(
        random_normal(0,1,200),
        xaxis      = true,
        point_size = 2,
        terminal   = eps,
        eps_width  = 10,
        eps_height = 2)$

Двумерная корреляционная диаграмма.

(%i1) load ("descriptive")$
(%i2) s2 : read_matrix (file_search ("wind.data"))$
(%i3) scatterplot(
        submatrix(s2, 1,2,3),
        title      = "Data from stations #4 and #5",
        point_type = diamant,
        point_size = 2,
        color      = blue)$

Трехмерная корреляционная диаграмма.

(%i1) load ("descriptive")$
(%i2) s2 : read_matrix (file_search ("wind.data"))$
(%i3) scatterplot(submatrix (s2, 1,2))$

Пятимерная корреляционная диаграмма, с гистограммой, содержащей пать классов.

(%i1) load ("descriptive")$
(%i2) s2 : read_matrix (file_search ("wind.data"))$
(%i3) scatterplot(
        s2,
        nclasses     = 5,
        fill_color   = blue,
        fill_density = 0.3,
        xtics        = 5)$

По поводу построения точек в двух или трех измерениях, соединенных линиями, см. points. См. bars по поводу опций, управляющих выводом гистограмм.

См. также histogram.

Функция: barsplot (list)
Функция: barsplot (list, option_1, option_2, ...)
Функция: barsplot (one_column_matrix)
Функция: barsplot (one_column_matrix, option_1, option_2, ...)
Функция: barsplot (one_row_matrix)
Функция: barsplot (one_row_matrix, option_1, option_2, ...)

Аналогична histogram но для дискретных, численных или категоризированных, статистических переменных.

Доступны следующие опции:

Пример:

(%i1) load ("descriptive")$
(%i2) s3 : read_matrix (file_search ("biomed.data"))$
(%i3) barsplot(col(s3,2),
         title        = "Ages",
         xlabel       = "years",
         box_width    = 1/2,
         fill_density = 0.3)$

По поводу опций, управляющих выводом диаграмм, см. bars пакета draw. См. также функции histogram и piechart.

Функция: piechart (list)
Функция: piechart (list, option_1, option_2, ...)
Функция: piechart (one_column_matrix)
Функция: piechart (one_column_matrix, option_1, option_2, ...)
Функция: piechart (one_row_matrix)
Функция: piechart (one_row_matrix, option_1, option_2, ...)

Аналогична barsplot, но вместо прямоугольников строит сектора, т.е. круговую диаграмму.

Доступны следующие опции:

Пример:

(%i1) load ("descriptive")$
(%i2) s1 : read_list (file_search ("pidigits.data"))$
(%i3) piechart(
        s1,
        xrange      = [-1.1, 1.3],
        yrange      = [-1.1, 1.1],
        axis_top    = false,
        axis_right  = false,
        axis_left   = false,
        axis_bottom = false,
        xtics       = none,
        ytics       = none,
        title       = "Digit frequencies in pi")$

См. также barsplot.

Функция: boxplot (data)
Функция: boxplot (data, option_1, option_2, ...)

Эта функция строит диаграмму типа "ящик-с-усами" (box-and-whishker). Аргумент data может быть списком, что не представляет большого интереса, т.к. подобные диаграммы в основном используются для сравнения различных выборок или матриц, чтобы сравнить две или более компонент многомерной выборки. Но data также может быть списком выборок, возможно различной длины (это единственная функция в пакете descriptive, которая допускает такой тип данных).

Доступны следующие опции:

Примеры:

Диаграмма "ящик-с-усами" для многомерной выборки.

(%i1) load ("descriptive")$
(%i2) s2 : read_matrix(file_search("wind.data"))$
(%i3) boxplot(s2,
        box_width  = 0.2,
        title      = "Windspeed in knots",
        xlabel     = "Stations",
        color      = red,
        line_width = 2) $

Диаграмма "ящик-с-усами" для трех выборок различной длины.

(%i1) load ("descriptive")$
(%i2) A :
       [[6, 4, 6, 2, 4, 8, 6, 4, 6, 4, 3, 2],
        [8, 10, 7, 9, 12, 8, 10],
        [16, 13, 17, 12, 11, 18, 13, 18, 14, 12]]$
(%i3) boxplot (A)$

Next: , Previous: Пакет descriptive, Up: Top   [Contents][Index]

44 Пакет diag


Previous: Пакет diag, Up: Пакет diag   [Contents][Index]

44.1 Функции и переменные пакета diag

Функция: diag (lm)

Строит квадратную матрицу с матрицами из lm на диагонали. Здесь, lm есть список матриц или скаляров.

Пример:

(%i1) load("diag")$

(%i2) a1:matrix([1,2,3],[0,4,5],[0,0,6])$

(%i3) a2:matrix([1,1],[1,0])$

(%i4) diag([a1,x,a2]);
                   [ 1  2  3  0  0  0 ]
                   [                  ]
                   [ 0  4  5  0  0  0 ]
                   [                  ]
                   [ 0  0  6  0  0  0 ]
(%o4)              [                  ]
                   [ 0  0  0  x  0  0 ]
                   [                  ]
                   [ 0  0  0  0  1  1 ]
                   [                  ]
                   [ 0  0  0  0  1  0 ]

Для использования функцию следует загрузить командой load("diag").

Функция: JF (lambda,n)

Возвращает жорданову клетку порядка n с собственными значениями lambda.

Пример:

(%i1) load("diag")$

(%i2) JF(2,5);
                    [ 2  1  0  0  0 ]
                    [               ]
                    [ 0  2  1  0  0 ]
                    [               ]
(%o2)               [ 0  0  2  1  0 ]
                    [               ]
                    [ 0  0  0  2  1 ]
                    [               ]
                    [ 0  0  0  0  2 ]
(%i3) JF(3,2);
                         [ 3  1 ]
(%o3)                    [      ]
                         [ 0  3 ]

Для использования функцию следует загрузить командой load("diag").

Функция: jordan (mat)

Возвращает жорданову форму матрицы mat, но представленную в форме списка Maxima. Для получения матрицы к результату функции jordan следует применить функцию dispJordan.

Пример:

(%i1) load("diag")$

(%i3) a:matrix([2,0,0,0,0,0,0,0],
               [1,2,0,0,0,0,0,0],
               [-4,1,2,0,0,0,0,0],
               [2,0,0,2,0,0,0,0],
               [-7,2,0,0,2,0,0,0],
               [9,0,-2,0,1,2,0,0],
               [-34,7,1,-2,-1,1,2,0],
               [145,-17,-16,3,9,-2,0,3])$

(%i34) jordan(a);
(%o4)             [[2, 3, 3, 1], [3, 1]]
(%i5) dispJordan(%);
                [ 2  1  0  0  0  0  0  0 ]
                [                        ]
                [ 0  2  1  0  0  0  0  0 ]
                [                        ]
                [ 0  0  2  0  0  0  0  0 ]
                [                        ]
                [ 0  0  0  2  1  0  0  0 ]
(%o5)           [                        ]
                [ 0  0  0  0  2  1  0  0 ]
                [                        ]
                [ 0  0  0  0  0  2  0  0 ]
                [                        ]
                [ 0  0  0  0  0  0  2  0 ]
                [                        ]
                [ 0  0  0  0  0  0  0  3 ]

Для использования функцию следует загрузить командой load("diag"). См. dispJordan и minimalPoly.

Функция: dispJordan (l)

Возвращает жорданову матрицу, соответствующую представлению в виде Maxima списка l, возвращаемого функцией jordan.

Пример:

(%i1) load("diag")$

(%i2) b1:matrix([0,0,1,1,1],
                [0,0,0,1,1],
                [0,0,0,0,1],
                [0,0,0,0,0],
                [0,0,0,0,0])$

(%i3) jordan(b1);
(%o3)                  [[0, 3, 2]]
(%i4) dispJordan(%);
                    [ 0  1  0  0  0 ]
                    [               ]
                    [ 0  0  1  0  0 ]
                    [               ]
(%o4)               [ 0  0  0  0  0 ]
                    [               ]
                    [ 0  0  0  0  1 ]
                    [               ]
                    [ 0  0  0  0  0 ]

Для использования функцию следует загрузить командой load("diag"). См. jordan и minimalPoly.

Функция: minimalPoly (l)

Возвращает минимальный многочлен, соответствующий представлению в виде Maxima списка l, возвращаемого функцией jordan.

Пример:

(%i1) load("diag")$

(%i2) a:matrix([2,1,2,0],
               [-2,2,1,2],
               [-2,-1,-1,1],
               [3,1,2,-1])$

(%i3) jordan(a);
(%o3)               [[- 1, 1], [1, 3]]
(%i4) minimalPoly(%);
                            3
(%o4)                (x - 1)  (x + 1)

Для использования функцию следует загрузить командой load("diag"). См. jordan и dispJordan.

Функция: ModeMatrix (A,l)

Возвращает матрицу M, такую что (M^^-1).A.M=J, где J есть жорданова форма A. Список l является представлением жордановой формы матрицы, возвращаемым функцией jordan.

Пример:

(%i1) load("diag")$

(%i2) a:matrix([2,1,2,0],
          [-2,2,1,2],
          [-2,-1,-1,1],
          [3,1,2,-1])$

(%i3) jordan(a);
(%o3)               [[- 1, 1], [1, 3]]
(%i4) M: ModeMatrix(a,%);
                  [  1    - 1   1   1 ]
                  [                   ]
                  [   1               ]
                  [ - -   - 1   0   0 ]
                  [   9               ]
                  [                   ]
(%o4)             [   13              ]
                  [ - --   1   - 1  0 ]
                  [   9               ]
                  [                   ]
                  [  17               ]
                  [  --   - 1   1   1 ]
                  [  9                ]
(%i5) is(  (M^^-1).a.M = dispJordan(%o3)  );
(%o5)                      true

Отметим, что dispJordan(%o3) есть жорданова форма матрицы a.

Для использования функцию следует загрузить командой load("diag"). См. jordan и dispJordan.

Функция: mat_function (f,mat)

Возвращает f(mat), где f есть аналитическая функция а mat – матрица. Вычисление основано на интегральной формуле Коши, которая утверждает, что, если f(x) является аналитической функцией и

mat = diag([JF(m1,n1),...,JF(mk,nk)]),

то

f(mat) = ModeMatrix*diag([f(JF(m1,n1)), ..., f(JF(mk,nk))])
                                              *ModeMatrix^^(-1)

Отметим, что существует 6 или 8 методов выполнения данного вычисления.

Пример 1:

(%i1) load("diag")$

(%i2) b2:matrix([0,1,0], [0,0,1], [-1,-3,-3])$

(%i3) mat_function(exp,t*b2);
               2   - t
              t  %e          - t     - t
(%o3) matrix([-------- + t %e    + %e   ,
                 2
        - t     - t                           - t
 2    %e      %e        - t           - t   %e
t  (- ----- - ----- + %e   ) + t (2 %e    - -----)
        t       2                             t
               t
                         - t          - t     - t
       - t       - t   %e        2  %e      %e
 + 2 %e   , t (%e    - -----) + t  (----- - -----)
                         t            2       t
               2   - t            - t     - t
     - t      t  %e        2    %e      %e        - t
 + %e   ], [- --------, - t  (- ----- - ----- + %e   ),
                 2                t       2
                                         t
        - t     - t      2   - t
   2  %e      %e        t  %e          - t
- t  (----- - -----)], [-------- - t %e   ,
        2       t          2
        - t     - t                           - t
 2    %e      %e        - t           - t   %e
t  (- ----- - ----- + %e   ) - t (2 %e    - -----),
        t       2                             t
               t
      - t     - t                 - t
 2  %e      %e            - t   %e
t  (----- - -----) - t (%e    - -----)])
      2       t                   t
(%i4) ratsimp(%);
               [   2              - t ]
               [ (t  + 2 t + 2) %e    ]
               [ -------------------- ]
               [          2           ]
               [                      ]
               [         2   - t      ]
(%o4)  Col 1 = [        t  %e         ]
               [      - --------      ]
               [           2          ]
               [                      ]
               [     2          - t   ]
               [   (t  - 2 t) %e      ]
               [   ----------------   ]
               [          2           ]
         [      2        - t    ]
         [    (t  + t) %e       ]
         [                      ]
 Col 2 = [     2            - t ]
         [ - (t  - t - 1) %e    ]
         [                      ]
         [     2          - t   ]
         [   (t  - 3 t) %e      ]
         [        2   - t       ]
         [       t  %e          ]
         [       --------       ]
         [          2           ]
         [                      ]
         [      2          - t  ]
 Col 3 = [    (t  - 2 t) %e     ]
         [  - ----------------  ]
         [           2          ]
         [                      ]
         [   2              - t ]
         [ (t  - 4 t + 2) %e    ]
         [ -------------------- ]
         [          2           ]

Пример 2:

(%i5) b1:matrix([0,0,1,1,1],
                [0,0,0,1,1],
                [0,0,0,0,1],
                [0,0,0,0,0],
                [0,0,0,0,0])$

(%i6) mat_function(exp,t*b1);
                  [              2     ]
                  [             t      ]
                  [ 1  0  t  t  -- + t ]
                  [             2      ]
                  [                    ]
(%o6)             [ 0  1  0  t    t    ]
                  [                    ]
                  [ 0  0  1  0    t    ]
                  [                    ]
                  [ 0  0  0  1    0    ]
                  [                    ]
                  [ 0  0  0  0    1    ]
(%i7) minimalPoly(jordan(b1));
                             3
(%o7)                       x
(%i8) ident(5)+t*b1+1/2*(t^2)*b1^^2;
                  [              2     ]
                  [             t      ]
                  [ 1  0  t  t  -- + t ]
                  [             2      ]
                  [                    ]
(%o8)             [ 0  1  0  t    t    ]
                  [                    ]
                  [ 0  0  1  0    t    ]
                  [                    ]
                  [ 0  0  0  1    0    ]
                  [                    ]
                  [ 0  0  0  0    1    ]
(%i9) mat_function(exp,%i*t*b1);
             [                           2 ]
             [                          t  ]
             [ 1  0  %i t  %i t  %i t - -- ]
             [                          2  ]
             [                             ]
(%o9)        [ 0  1   0    %i t    %i t    ]
             [                             ]
             [ 0  0   1     0      %i t    ]
             [                             ]
             [ 0  0   0     1        0     ]
             [                             ]
             [ 0  0   0     0        1     ]
(%i10) mat_function(cos,t*b1)+%i*mat_function(sin,t*b1);
              [                           2 ]
              [                          t  ]
              [ 1  0  %i t  %i t  %i t - -- ]
              [                          2  ]
              [                             ]
(%o10)        [ 0  1   0    %i t    %i t    ]
              [                             ]
              [ 0  0   1     0      %i t    ]
              [                             ]
              [ 0  0   0     1        0     ]
              [                             ]
              [ 0  0   0     0        1     ]

Пример 3:

(%i11) a1:matrix([2,1,0,0,0,0],
                 [-1,4,0,0,0,0],
                 [-1,1,2,1,0,0],
                 [-1,1,-1,4,0,0],
                 [-1,1,-1,1,3,0],
                 [-1,1,-1,1,1,2])$

(%i12) fpow(x):=block([k],declare(k,integer),x^k)$

(%i13) mat_function(fpow,a1);
                [  k      k - 1 ]         [      k - 1    ]
                [ 3  - k 3      ]         [   k 3         ]
                [               ]         [               ]
                [       k - 1   ]         [  k      k - 1 ]
                [  - k 3        ]         [ 3  + k 3      ]
                [               ]         [               ]
                [       k - 1   ]         [      k - 1    ]
                [  - k 3        ]         [   k 3         ]
(%o13)  Col 1 = [               ] Col 2 = [               ]
                [       k - 1   ]         [      k - 1    ]
                [  - k 3        ]         [   k 3         ]
                [               ]         [               ]
                [       k - 1   ]         [      k - 1    ]
                [  - k 3        ]         [   k 3         ]
                [               ]         [               ]
                [       k - 1   ]         [      k - 1    ]
                [  - k 3        ]         [   k 3         ]
         [       0       ]         [       0       ]
         [               ]         [               ]
         [       0       ]         [       0       ]
         [               ]         [               ]
         [  k      k - 1 ]         [      k - 1    ]
         [ 3  - k 3      ]         [   k 3         ]
         [               ]         [               ]
 Col 3 = [       k - 1   ] Col 4 = [  k      k - 1 ]
         [  - k 3        ]         [ 3  + k 3      ]
         [               ]         [               ]
         [       k - 1   ]         [      k - 1    ]
         [  - k 3        ]         [   k 3         ]
         [               ]         [               ]
         [       k - 1   ]         [      k - 1    ]
         [  - k 3        ]         [   k 3         ]
         [    0    ]
         [         ]         [ 0  ]
         [    0    ]         [    ]
         [         ]         [ 0  ]
         [    0    ]         [    ]
         [         ]         [ 0  ]
 Col 5 = [    0    ] Col 6 = [    ]
         [         ]         [ 0  ]
         [    k    ]         [    ]
         [   3     ]         [ 0  ]
         [         ]         [    ]
         [  k    k ]         [  k ]
         [ 3  - 2  ]         [ 2  ]

Для использования функцию следует загрузить командой load("diag").


Next: , Previous: Пакет diag, Up: Top   [Contents][Index]

45 Пакет distrib


Next: , Previous: Пакет distrib, Up: Пакет distrib   [Contents][Index]

45.1 Введение в пакет distrib

Пакет distrib включает набор функций для вероятностных вычислений с дискретными и непрерывными распределениями одной переменной.

Далее следует краткий обзор основных понятий по вероятностным распределениям.

Пусть f(x) есть функция плотности вероятности непрерывной случайной величины X. Тогда функция распределения определяется как

                       x
                      /
                      [
               F(x) = I     f(u) du
                      ]
                      /
                       minf

что равно вероятности Pr(X <= x)

Среднее значение характеризует локализацию и определено как

                     inf
                    /
                    [
           E[X]  =  I   x f(x) dx
                    ]
                    /
                     minf

Дисперсия характеризует изменчивость распределения

                 inf
                /
                [                    2
         V[X] = I     f(x) (x - E[X])  dx
                ]
                /
                 minf

что есть положительное вещественное число. Квадратный корень дисперсии называется стандартным отклонением, D[X]=sqrt(V[X]), и является иной мерой изменчивости.

Коэффициент асимметрии является мерой асимметрии распределения

                 inf
                /
            1   [                    3
  SK[X] = ----- I     f(x) (x - E[X])  dx
              3 ]
          D[X]  /
                 minf

Коэффициент куртозиса является мерой остроты распределения

                 inf
                /
            1   [                    4
  KU[X] = ----- I     f(x) (x - E[X])  dx - 3
              4 ]
          D[X]  /
                 minf

Если случайная величина X гауссова, то KU[X]=0. Фактически, коэффициенты асимметрии и куртозиса являются параметрами формы и измеряют степень не-гауссовости распределения.

Если случайная переменная X является дискретной, то плотность, или вероятность, f(x) принимает положительные значения на некотором счетном множестве чисел x_i, и равна нулю в противном случае. В этом случае функция распределения есть

                       ====
                       \
                F(x) =  >    f(x )
                       /        i
                       ====
                      x <= x
                       i

А среднее, дисперсия, стандартное отклонение, коэффициенты асимметрии и куртозиса имеют вид

                       ====
                       \
                E[X] =  >  x  f(x ) ,
                       /    i    i
                       ====
                        x 
                         i
                ====
                \                     2
        V[X] =   >    f(x ) (x - E[X])  ,
                /        i    i
                ====
                 x
                  i
               D[X] = sqrt(V[X]),
                     ====
              1      \                     3
  SK[X] =  -------    >    f(x ) (x - E[X])  
           D[X]^3    /        i    i
                     ====
                      x
                       i

и

                     ====
              1      \                     4
  KU[X] =  -------    >    f(x ) (x - E[X])   - 3 ,
           D[X]^4    /        i    i
                     ====
                      x
                       i

соответственно.

Пакет distrib включает функции для моделирования случайных переменных. Некоторые из этих функций используют управляющие переменные, указывающие используемый алгоритм. В большинстве случаев реализован общий метод обращения, который основан на факте, что если u случайная величина с равномерным распределением в интервале (0,1), то F^(-1)(u) есть случайная величина с распределением F. Этот метод недостаточно эффективен с точки зрения времени вычисления, но полезен для сравнения с другими алгоритмами. В этом примере сравнивается производительность алгоритмов ahrens_cheng и inverse при вычислении гистограмм для Хи-квадрат случайной переменной:

(%i1) load("distrib")$
(%i2) load("descriptive")$
(%i3) showtime: true$
Evaluation took 0.00 seconds (0.00 elapsed) using 32 bytes.
(%i4) random_chi2_algorithm: 'ahrens_cheng$
                                       histogram(random_chi2(10,500))$
Evaluation took 0.00 seconds (0.00 elapsed) using 40 bytes.
Evaluation took 0.69 seconds (0.71 elapsed) using 5.694 MB.
(%i6) random_chi2_algorithm: 'inverse$ histogram(random_chi2(10,500))$
Evaluation took 0.00 seconds (0.00 elapsed) using 32 bytes.
Evaluation took 10.15 seconds (10.17 elapsed) using 322.098 MB.

Для визуального сравнения алгоритмов для дискретных переменных можно использовать функцию barsplot пакета descriptive.

Заметим, что еще требуется проделать некоторую работу, поскольку данные модельные распределения еще не проверены более строгими оценками качества совпадения.

За более детальной информацией по поводу данных математических объектов, пожалуйста, обратитесь к любому вводному руководству по вероятности и статистике.

Имена функций пакета distrib следуют определенному соглашению. Каждое имя состоит из двух частей – первая определяет функцию или параметр, которое необходимо вычислить.

Функции:
   Плотность вероятности           (pdf_*)
   Распределение                   (cdf_*)
   Квантиль                        (quantile_*)
   Среднее значение                (mean_*)
   Дисперсия                       (var_*)
   Стандартное отклонение          (std_*)
   Коэффициент асимметрии          (skewness_*)
   Коэффициент куртозиса           (kurtosis_*)
   Случайная переменная (variate)  (random_*)

Вторая часть определяет тип распределения.

Непрерывные распределения:
   Нормальное                  (*normal)
   Стьюдента                   (*student_t)
   Хи-квадрат                  (*chi2)
   F                           (*f)
   Экспоненциальное            (*exp)
   Логнормальное               (*lognormal)
   Гамма                       (*gamma)
   Бета                        (*beta)
   Равномерное неприрывное     (*continuous_uniform)
   Логистическое               (*logistic)
   Парето                      (*pareto)
   Вейбулла                    (*weibull)
   Релея                       (*rayleigh)
   Лапласа                     (*laplace)
   Коши                        (*cauchy)
   Гумбеля                     (*gumbel)

Дискретные распределения:
   Биномиальное                (*binomial)
   Пуассона                    (*poisson)
   Бернулли                    (*bernoulli)
   Геометрическое              (*geometric)
   Равномерное дискретное      (*discrete_uniform)
   Гипергеометрическое         (*hypergeometric)
   Отрицательное биномиальное  (*negative_binomial)

Например, pdf_student_t(x,n) – плотность распределения Стьюдента с n степенями свободы, std_pareto(a,b) – стандартное отклонение распределения Парето с параметрами a и b, и kurtosis_poisson(m) – коэффициент куртозиса распределения Пуассона со средним m.

Для использования пакет distrib необходимо загрузить командой

(%i1) load("distrib")$

Для комментариев, сообщений об ошибках и предложений обращайтесь к автору пакета по адресу ’mario AT edu DOT xunta DOT es’.


Next: , Previous: Введение в пакет distrib, Up: Пакет distrib   [Contents][Index]

45.2 Функции и переменные для непрерывных распределений

Функция: pdf_normal (x,m,s)

Возвращает значение функции плотности вероятности нормального распределения Normal(m,s) с s>0 в точке x.

Чтобы использовать эту функцию, ее следует сначала загрузить командой load("distrib").

Функция: cdf_normal (x,m,s)

Возвращает значение функции распределения нормального распределения Normal(m,s) с s>0 в точке x.

Эта функция определена в терминах встроенной Maxima функции erf.

(%i1) load ("distrib")$
(%i2) assume(s>0)$ cdf_normal(x,m,s);
                             x - m
                       erf(---------)
                           sqrt(2) s    1
(%o3)                  -------------- + -
                             2          2

См. также erf.

Функция: quantile_normal (q,m,s)

Возвращает q-квантиль нормального распределения Normal(m,s) с s>0, т.е. значение функции обратной cdf_normal. Значение аргумента q должно быть в интервале [0,1].

Чтобы использовать эту функцию, ее следует сначала загрузить командой load("distrib").

Функция: mean_normal (m,s)

Возвращает среднее значение нормального распределения Normal(m,s) с s>0, т.е. m.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: var_normal (m,s)

Возвращает дисперсию нормального распределения Normal(m,s) с s>0, т.е. s^2.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: std_normal (m,s)

Возвращает стандартное отклонение нормального распределения Normal(m,s) с s>0, т.е. s.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: skewness_normal (m,s)

Возвращает коэффициент асимметрии нормального распределения Normal(m,s) с s>0, котрый всегда равен 0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: kurtosis_normal (m,s)

Возвращает коэффициент куртозиса нормального распределения Normal(m,s) с s>0, котрый всегда равен 0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Управляющая переменная: random_normal_algorithm

Значение по умолчанию: box_mueller

Определяет алгоритм, выбранный для симулирования нормальной случайной переменной. Реализованы алгоритмы box_mueller и inverse:

См. также random_normal.

Функция: random_normal (m,s)
Функция: random_normal (m,s,n)

Возвращает значение симулированной случайной переменной нормального распределения Normal(m,s) с s>0. Вызов random_normal с третьим аргументом n дает случайную выборку размера n.

Для этой функции реализовано два алгоритма. Используемый алгоритм определяется значением глобальной переменной random_normal_algorithm, которая по умолчанию равна box_mueller.

См. также random_normal_algorithm.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: pdf_student_t (x,n)

Возвращает значение функции плотности вероятности распределения Стюдента t(n) с n>0 в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: cdf_student_t (x,n)

Возвращает значение функции распределения Стюдента t(n) с n>0 в точке x.

Эта функция не имеет замкнутой формы и вычисляется численно, если значение глобальной переменной numer рано true, иначе возвращается номинальное выражение.

(%i1) load ("distrib")$
(%i2) cdf_student_t(1/2, 7/3);
                                     1  7
(%o2)                  cdf_student_t(-, -)
                                     2  3
(%i3) %,numer;
(%o3)                   .6698450596140417
Функция: quantile_student_t (q,n)

Возвращает q-квантиль распределения Стюдента t(n) с n>0, т.е. значение функции обратной cdf_student_t. Значение аргумента q должно быть в интервале [0,1].

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: mean_student_t (n)

Возвращает среднее значение распределения Стюдента t(n) с n>0, которое всегда равное 0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: var_student_t (n)

Возвращает дисперсию распределения Стюдента t(n) с n>2.

(%i1) load ("distrib")$
(%i2) assume(n>2)$  var_student_t(n);
                                n
(%o3)                         -----
                              n - 2
Функция: std_student_t (n)

Возвращает стандартное отклонение распределения Стюдента t(n) с n>2.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: skewness_student_t (n)

Возвращает коэффициент ассиметрии распределения Стюдента t(n) с n>3, который всегда равен 0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: kurtosis_student_t (n)

Возвращает коэффициент куртозиса распределения Стюдента t(n) с n>4.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Управляющая переменная: random_student_t_algorithm

Значение по умолчанию: ratio

Определяет алгоритм, выбранный для симулирования случайной переменной распределения Стьюдента. Реализованы алгоритмы inverse и ratio:

См. также random_student_t.

Функция: random_student_t (n)
Функция: random_student_t (n,m)

Возвращает значение симулированной случайной переменной распределение Стьюдента t(n) с n>0. Вызов random_student_t со вторым аргументом m дает случайную выборку размера m.

Для этой функции реализовано два алгоритма. Используемый алгоритм определяется значением глобальной переменной random_student_t_algorithm, которая по умолчанию равна ratio.

См. также random_student_t_algorithm.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: pdf_chi2 (x,n)

Возвращает значение функции плотности вероятности распределения Хи-квадрат Chi^2(n) с n>0 в точке x.

Случайная переменная Chi^2(n) эквивалентна случайной переменной Gamma(n/2,2). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах функции плотности гамма распределения.

(%i1) load ("distrib")$
(%i2) pdf_chi2(x,n);
                                    n
(%o2)                  pdf_gamma(x, -, 2)
                                    2
(%i3) assume(x>0, n>0)$  pdf_chi2(x,n);
                         n/2 - 1   - x/2
                        x        %e
(%o4)                   ----------------
                          n/2       n
                         2    gamma(-)
                                    2
Функция: cdf_chi2 (x,n)

Возвращает значение функции распределения Хи-квадрат Chi^2(n) с n>0 в точке x.

Эта функция не имеет замкнутой формы и вычисляется численно, если значение глобальной переменной numer рано true, иначе возвращается номинальное выражение основанное на гамма квантили, поскольку распределение Chi^2(n) эквивалентно Gamma(n/2,2).

(%i1) load ("distrib")$
(%i2) cdf_chi2(3,4);
(%o2)                  cdf_gamma(3, 2, 2)
(%i3) cdf_chi2(3,4),numer;
(%o3)                   .4421745996289249
Функция: quantile_chi2 (q,n)

Возвращает q-квантиль распределения Хи-квадрат Chi^2(n) с n>0, т.е. значение функции обратной cdf_chi2. Значение аргумента q должно быть в интервале [0,1].

Эта функция не имеет замкнутой формы и вычисляется численно, если значение глобальной переменной numer рано true, иначе возвращается номинальное выражение основанное на гамма квантили, поскольку распределение Chi^2(n) эквивалентно Gamma(n/2,2).

(%i1) load ("distrib")$
(%i2) quantile_chi2(0.99,9);
(%o2)                   21.66599433346194
(%i3) quantile_chi2(0.99,n);
                                        n
(%o3)              quantile_gamma(0.99, -, 2)
                                        2
Функция: mean_chi2 (n)

Возвращает среднее значение распределения Хи-квадрат Chi^2(n) с n>0.

Случайная переменная Chi^2(n) эквивалентна случайной переменной Gamma(n/2,2). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах среднего значения гамма распределения.

(%i1) load ("distrib")$
(%i2) mean_chi2(n);
                                   n
(%o2)                   mean_gamma(-, 2)
                                   2
(%i3) assume(n>0)$ mean_chi2(n);
(%o4)                           n
Функция: var_chi2 (n)

Возвращает дисперсию распределения Хи-квадрат Chi^2(n) с n>0.

Случайная переменная Chi^2(n) эквивалентна случайной переменной Gamma(n/2,2). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах дисперсии гамма распределения.

(%i1) load ("distrib")$
(%i2) var_chi2(n);
                                   n
(%o2)                    var_gamma(-, 2)
                                   2
(%i3) assume(n>0)$ var_chi2(n);
(%o4)                          2 n
Функция: std_chi2 (n)

Возвращает стандартное отклонение распределения Хи-квадрат Chi^2(n) с n>0.

Случайная переменная Chi^2(n) эквивалентна случайной переменной Gamma(n/2,2). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах стандартного отклонения гамма распределения.

(%i1) load ("distrib")$
(%i2) std_chi2(n);
                                   n
(%o2)                    std_gamma(-, 2)
                                   2
(%i3) assume(n>0)$ std_chi2(n);
(%o4)                    sqrt(2) sqrt(n)
Функция: skewness_chi2 (n)

Возвращает коэффициент асимметрии распределения Хи-квадрат Chi^2(n) с n>0.

Случайная переменная Chi^2(n) эквивалентна случайной переменной Gamma(n/2,2). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах коэффициента асимметрии гамма распределения.

(%i1) load ("distrib")$
(%i2) skewness_chi2(n);
                                     n
(%o2)                 skewness_gamma(-, 2)
                                     2
(%i3) assume(n>0)$ skewness_chi2(n);
                            2 sqrt(2)
(%o4)                       ---------
                             sqrt(n)
Функция: kurtosis_chi2 (n)

Возвращает коэффициент куртозиса распределения Хи-квадрат Chi^2(n) с n>0.

Случайная переменная Chi^2(n) эквивалентна случайной переменной Gamma(n/2,2). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах коэффициента куртозиса гамма распределения.

(%i1) load ("distrib")$
(%i2) kurtosis_chi2(n);
                                     n
(%o2)                 kurtosis_gamma(-, 2)
                                     2
(%i3) assume(n>0)$ kurtosis_chi2(n);
                               12
(%o4)                          --
                               n
Управляющая переменная: random_chi2_algorithm

Значение по умолчанию: ahrens_cheng

Определяет алгоритм, выбранный для симулирования случайной переменной распределения Хи-квадрат. Реализованы алгоритмы ahrens_cheng и inverse:

См. также random_chi2.

Функция: random_chi2 (n)
Функция: random_chi2 (n,m)

Возвращает значение симулированной случайной переменной распределения Хи-квадрат Chi^2(n) с n>0. Вызов random_chi2 со вторым аргументом m дает случайную выборку размера m.

Для этой функции реализовано два алгоритма. Используемый алгоритм определяется значением глобальной переменной random_chi2_algorithm, которая по умолчанию равна ahrens_cheng.

См. также random_chi2_algorithm.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: pdf_f (x,m,n)

Возвращает значение функции плотности вероятности распределения F(m,n) с m,n>0 в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: cdf_f (x,m,n)

Возвращает значение функции распределения F(m,n) с m,n>0 в точке x.

Эта функция не имеет замкнутой формы и вычисляется численно, если значение глобальной переменной numer рано true, иначе возвращается номинальное выражение.

(%i1) load ("distrib")$
(%i2) cdf_f(2,3,9/4);
                                     9
(%o2)                    cdf_f(2, 3, -)
                                     4
(%i3) %,numer;
(%o3)                   0.66756728179008
Функция: quantile_f (q,m,n)

Возвращает q-квантиль распределения F(m,n) с m,n>0, т.е. значение функции обратной cdf_f. Значение аргумента q должно быть в интервале [0,1].

Эта функция не имеет замкнутой формы и вычисляется численно, если значение глобальной переменной numer рано true, иначе возвращается номинальное выражение.

(%i1) load ("distrib")$
(%i2) quantile_f(2/5,sqrt(3),5);
                               2
(%o2)               quantile_f(-, sqrt(3), 5)
                               5
(%i3) %,numer;
(%o3)                   0.518947838573693
Функция: mean_f (m,n)

Возвращает среднее значение распределения F(m,n) с m>0, n>2.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: var_f (m,n)

Возвращает дисперсию распределения F(m,n) с m>0, n>4.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: std_f (m,n)

Возвращает стандартное отклонение распределения F(m,n) с m>0, n>4.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: skewness_f (m,n)

Возвращает коэффициент асимметрии распределения F(m,n) с m>0, n>6.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: kurtosis_f (m,n)

Возвращает коэффициент куртозиса распределения F(m,n) с m>0, n>8.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Управляющая переменная: random_f_algorithm

Значение по умолчанию: inverse

Определяет алгоритм, выбранный для симулирования случайной переменной распределения F. Реализованы алгоритмы ratio и inverse:

См. также random_f.

Функция: random_f (m,n)
Функция: random_f (m,n,k)

Возвращает значение симулированной случайной переменной распределения F(m,n) с m,n>0. Вызов random_f с третьим аргументом k дает случайную выборку размера k.

Для этой функции реализовано два алгоритма. Используемый алгоритм определяется значением глобальной переменной random_f_algorithm, которая по умолчанию равна inverse.

См. также random_f_algorithm.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: pdf_exp (x,m)

Возвращает значение функции плотности вероятности экспоненциального распределения Exponential(m) с m>0 в точке x.

Случайная переменная Exponential(m) эквивалентна случайной переменной Weibull(1,1/m). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах плотности вероятности распределения Вейбулла.

(%i1) load ("distrib")$
(%i2) pdf_exp(x,m);
                                        1
(%o2)                 pdf_weibull(x, 1, -)
                                        m
(%i3) assume(x>0,m>0)$  pdf_exp(x,m);
                                - m x
(%o4)                       m %e
Функция: cdf_exp (x,m)

Возвращает значение функции распределения экспоненциального распределения Exponetial(m) с m>0 в точке x.

Случайная переменная Exponential(m) эквивалентна случайной переменной Weibull(1,1/m). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах функции распределения распределения Вейбулла.

(%i1) load ("distrib")$
(%i2) cdf_exp(x,m);
                                        1
(%o2)                 cdf_weibull(x, 1, -)
                                        m
(%i3) assume(x>0,m>0)$  cdf_exp(x,m);
                                 - m x
(%o4)                      1 - %e
Функция: quantile_exp (q,m)

Возвращает q-квантиль экспоненциального распределения Exponetial(m) с m>0, т.е. значение функции обратной cdf_exp. Значение аргумента q должно быть в интервале [0,1].

Случайная переменная Exponential(m) эквивалентна случайной переменной Weibull(1,1/m). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах квантили распределения Вейбулла.

(%i1) load ("distrib")$
(%i2) quantile_exp(0.56,5);
(%o2)                   .1641961104139661
(%i3) quantile_exp(0.56,m);
                                            1
(%o3)             quantile_weibull(0.56, 1, -)
                                            m
Функция: mean_exp (m)

Возвращает среднее значение экспоненциального распределения Exponetial(m) с m>0.

Случайная переменная Exponential(m) эквивалентна случайной переменной Weibull(1,1/m). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах среднего значения распределения Вейбулла.

(%i1) load ("distrib")$
(%i2) mean_exp(m);
                                       1
(%o2)                  mean_weibull(1, -)
                                       m
(%i3) assume(m>0)$  mean_exp(m);
                                1
(%o4)                           -
                                m
Функция: var_exp (m)

Возвращает дисперсию экспоненциального распределения Exponetial(m) с m>0.

Случайная переменная Exponential(m) эквивалентна случайной переменной Weibull(1,1/m). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах дисперсии распределения Вейбулла.

(%i1) load ("distrib")$
(%i2) var_exp(m);
                                       1
(%o2)                   var_weibull(1, -)
                                       m
(%i3) assume(m>0)$  var_exp(m);
                               1
(%o4)                          --
                                2
                               m
Функция: std_exp (m)

Возвращает стандартное отклонение экспоненциального распределения Exponetial(m) с m>0.

Случайная переменная Exponential(m) эквивалентна случайной переменной Weibull(1,1/m). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах стандартного отклонения распределения Вейбулла.

(%i1) load ("distrib")$
(%i2) std_exp(m);
                                       1
(%o2)                   std_weibull(1, -)
                                       m
(%i3) assume(m>0)$  std_exp(m);
                                1
(%o4)                           -
                                m
Функция: skewness_exp (m)

Возвращает коэффициент асимметрии экспоненциального распределения Exponetial(m) с m>0.

Случайная переменная Exponential(m) эквивалентна случайной переменной Weibull(1,1/m). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах коэффициента асимметрии распределения Вейбулла.

(%i1) load ("distrib")$
(%i2) skewness_exp(m);
                                         1
(%o2)                skewness_weibull(1, -)
                                         m
(%i3) assume(m>0)$  skewness_exp(m);
(%o4)                           2
Функция: kurtosis_exp (m)

Возвращает коэффициент куртозиса экспоненциального распределения Exponetial(m) с m>0.

Случайная переменная Exponential(m) эквивалентна случайной переменной Weibull(1,1/m). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах коэффициента куртозиса распределения Вейбулла.

(%i1) load ("distrib")$
(%i2) kurtosis_exp(m);
                                         1
(%o2)                kurtosis_weibull(1, -)
                                         m
(%i3) assume(m>0)$  kurtosis_exp(m);
(%o4)                           6
Управляющая переменная: random_exp_algorithm

Значение по умолчанию: inverse

Определяет алгоритм, выбранный для симулирования случайной переменной экспоненциального распределения. Реализованы алгоритмы inverse, ahrens_cheng и ahrens_dieter

См. также random_exp.

Функция: random_exp (m)
Функция: random_exp (m,k)

Возвращает значение симулированной случайной переменной экспоненциального распределения Exponential(m) с m>0. Вызов random_exp со вторым аргументом k дает случайную выборку размера k.

Для этой функции реализовано три алгоритма. Используемый алгоритм определяется значением глобальной переменной random_exp_algorithm, которая по умолчанию равна inverse.

См. также random_exp_algorithm.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: pdf_lognormal (x,m,s)

Возвращает значение функции плотности вероятности логнормального распределения Lognormal(m,s) с s>0 в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: cdf_lognormal (x,m,s)

Возвращает значение функции распределения логнормального распределения Lognormal(m,s) с s>0 в точке x.

Эта функция определена в терминах встроенной Maxima функции erf.

(%i1) load ("distrib")$
(%i2) assume(x>0, s>0)$  cdf_lognormal(x,m,s);
                           log(x) - m
                       erf(----------)
                           sqrt(2) s     1
(%o3)                  --------------- + -
                              2          2

См. также erf.

Функция: quantile_lognormal (q,m,s)

Возвращает q-квантиль логнормального распределения Lognormal(m,s) с s>0, т.е. значение функции обратной cdf_lognormal. Значение аргумента q должно быть в интервале [0,1].

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: mean_lognormal (m,s)

Возвращает среднее значение логнормального распределения Lognormal(m,s) с s>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: var_lognormal (m,s)

Возвращает дисперсию логнормального распределения Lognormal(m,s) с s>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: std_lognormal (m,s)

Возвращает стандартное отклонение логнормального распределения Lognormal(m,s) с s>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: skewness_lognormal (m,s)

Возвращает коэффициент асимметрии логнормального распределения Lognormal(m,s) с s>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: kurtosis_lognormal (m,s)

Возвращает коэффициент куртозиса логнормального распределения Lognormal(m,s) с s>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: random_lognormal (m,s)
Функция: random_lognormal (m,s,n)

Возвращает значение симулированной случайной переменной логнормального распределения Lognormal(m,s) с s>0. Вызов random_lognormal с третьим аргументом n дает случайную выборку размера n.

Логнормальное распределение симулируется при помощи нормального распределения. Для этой функции реализовано два алгоритма. Используемый алгоритм определяется значением глобальной переменной random_normal_algorithm, которая по умолчанию равна box_mueller.

См. также random_normal_algorithm.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: pdf_gamma (x,a,b)

Возвращает значение функции плотности вероятности гамма распределения Gamma(a,b) с a,b>0 в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: cdf_gamma (x,a,b)

Возвращает значение функции распределения гамма распределения Gamma(a,b) с a,b>0 в точке x.

Эта функция не имеет замкнутой формы и вычисляется численно, если значение глобальной переменной numer рано true, иначе возвращается номинальное выражение.

(%i1) load ("distrib")$
(%i2) cdf_gamma(3,5,21);
(%o2)                  cdf_gamma(3, 5, 21)
(%i3) %,numer;
(%o3)                 4.402663157135039E-7
Функция: quantile_gamma (q,a,b)

Возвращает q-квантиль гамма распределения Gamma(a,b) с a,b>0, т.е. значение функции обратной cdf_gamma. Значение аргумента q должно быть в интервале [0,1].

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: mean_gamma (a,b)

Возвращает среднее значение гамма распределения Gamma(a,b) с a,b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: var_gamma (a,b)

Возвращает дисперсию гамма распределения Gamma(a,b) с a,b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: std_gamma (a,b)

Возвращает стандартное отклонение гамма распределения Gamma(a,b) с a,b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: skewness_gamma (a,b)

Возвращает коэффициент асимметрии гамма распределения Gamma(a,b) с a,b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: kurtosis_gamma (a,b)

Возвращает коэффициент куртозиса гамма распределения Gamma(a,b) с a,b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Управляющая переменная: random_gamma_algorithm

Значение по умолчанию: ahrens_cheng

Определяет алгоритм, выбранный для симулирования случайной переменной гамма распределения. Реализованы алгоритмы ahrens_cheng и inverse

См. также random_gamma.

Функция: random_gamma (a,b)
Функция: random_gamma (a,b,n)

Возвращает значение симулированной случайной переменной гамма распределения Gamma(a,b) с a,b>0. Вызов random_gamma с третьим аргументом n дает случайную выборку размера n.

Для этой функции реализовано два алгоритма. Используемый алгоритм определяется значением глобальной переменной random_gamma_algorithm, которая по умолчанию равна ahrens_cheng.

См. также random_gamma_algorithm.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: pdf_beta (x,a,b)

Возвращает значение функции плотности вероятности бета распределения Beta(a,b) с a,b>0 в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: cdf_beta (x,a,b)

Возвращает значение функции распределения бета распределения Beta(a,b) с a,b>0 в точке x.

Эта функция не имеет замкнутой формы и вычисляется численно, если значение глобальной переменной numer рано true, иначе возвращается номинальное выражение.

(%i1) load ("distrib")$
(%i2) cdf_beta(1/3,15,2);
                                 1
(%o2)                   cdf_beta(-, 15, 2)
                                 3
(%i3) %,numer;
(%o3)                 7.666089131388224E-7
Функция: quantile_beta (q,a,b)

Возвращает q-квантиль бета распределения Beta(a,b) с a,b>0, т.е. значение функции обратной cdf_beta. Значение аргумента q должно быть в интервале [0,1].

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: mean_beta (a,b)

Возвращает среднее значение бета распределения Beta(a,b) с a,b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: var_beta (a,b)

Возвращает дисперсию бета распределения Beta(a,b) с a,b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: std_beta (a,b)

Возвращает стандартное отклонение бета распределения Beta(a,b) с a,b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: skewness_beta (a,b)

Возвращает коэффициент асимметрии бета распределения Beta(a,b) с a,b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: kurtosis_beta (a,b)

Возвращает коэффициент куртозиса бета распределения Beta(a,b) с a,b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Управляющая переменная: random_beta_algorithm

Значение по умолчанию: cheng

Определяет алгоритм, выбранный для симулирования случайной переменной бета распределения. Реализованы алгоритмы cheng, inverse и ratio

См. также random_beta.

Функция: random_beta (a,b)
Функция: random_beta (a,b,n)

Возвращает значение симулированной случайной переменной бета распределения Beta(a,b) с a,b>0. Вызов random_beta с третьим аргументом n дает случайную выборку размера n.

Для этой функции реализовано три алгоритма. Используемый алгоритм определяется значением глобальной переменной random_beta_algorithm, которая по умолчанию равна cheng.

См. также random_beta_algorithm.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: pdf_continuous_uniform (x,a,b)

Возвращает значение функции плотности вероятности равномерного непрерывного распределения Continuous Uniform(a,b) с a<b в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: cdf_continuous_uniform (x,a,b)

Возвращает значение функции распределения равномерного непрерывного распределения Continuous Uniform(a,b) с a<b в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: quantile_continuous_uniform (q,a,b)

Возвращает q-квантиль равномерного непрерывного распределения Continuous Uniform(a,b) с a<b, т.е. значение функции обратной cdf_continuous_uniform. Значение аргумента q должно быть в интервале [0,1].

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: mean_continuous_uniform (a,b)

Возвращает среднее значение равномерного непрерывного распределения Continuous Uniform(a,b) с a<b.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: var_continuous_uniform (a,b)

Возвращает дисперсию равномерного непрерывного распределения Continuous Uniform(a,b) с a<b.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: std_continuous_uniform (a,b)

Возвращает стандартное отклонение равномерного непрерывного распределения Continuous Uniform(a,b) с a<b.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: skewness_continuous_uniform (a,b)

Возвращает коэффициент ассиметрии равномерного непрерывного распределения Continuous Uniform(a,b) с a<b.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: kurtosis_continuous_uniform (a,b)

Возвращает коэффициент куртозиса равномерного непрерывного распределения Continuous Uniform(a,b) с a<b.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: random_continuous_uniform (a,b)
Функция: random_continuous_uniform (a,b,n)

Возвращает значение симулированной случайной переменной равномерного непрерывного распределения Continuous Uniform(a,b) с a<b. Вызов random_continuous_uniform с третьим аргументом n дает случайную выборку размера n.

Для вычисления используется встроенная Maxima функция random.

См. также random.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: pdf_logistic (x,a,b)

Возвращает значение функции плотности вероятности логистического распределения Logistic(a,b) с b>0 в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: cdf_logistic (x,a,b)

Возвращает значение функции распределения логистического распределения Logistic(a,b) с b>0 в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: quantile_logistic (q,a,b)

Возвращает q-квантиль логистического распределения Logistic(a,b) с b>0, т.е. значение функции обратной cdf_logistic. Значение аргумента q должно быть в интервале [0,1].

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: mean_logistic (a,b)

Возвращает среднее значение логистического распределения Logistic(a,b) с b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: var_logistic (a,b)

Возвращает дисперсию логистического распределения Logistic(a,b) с b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: std_logistic (a,b)

Возвращает стандартное отклонение логистического распределения Logistic(a,b) с b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: skewness_logistic (a,b)

Возвращает коэффициент асимметрии логистического распределения Logistic(a,b) с b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: kurtosis_logistic (a,b)

Возвращает коэффициент куртозиса логистического распределения Logistic(a,b) с b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: random_logistic (a,b)
Функция: random_logistic (a,b,n)

Возвращает значение симулированной случайной переменной логистического распределения Logistic(a,b) с b>0. Вызов random_logistic с третьим аргументом n дает случайную выборку размера n.

Реализован только метод обращения.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: pdf_pareto (x,a,b)

Возвращает значение функции плотности вероятности распределения Парето Pareto(a,b) с a,b>0 в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: cdf_pareto (x,a,b)

Возвращает значение функции распределения Парето Pareto(a,b) с a,b>0 в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: quantile_pareto (q,a,b)

Возвращает q-квантиль распределения Парето Pareto(a,b) с a,b>0, т.е. значение функции обратной cdf_pareto. Значение аргумента q должно быть в интервале [0,1].

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: mean_pareto (a,b)

Возвращает среднее значение распределения Парето Pareto(a,b) с a>1,b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: var_pareto (a,b)

Возвращает дисперсию распределения Парето Pareto(a,b) с a>2,b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: std_pareto (a,b)

Возвращает стандартное отклонение распределения Парето Pareto(a,b) с a>2,b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: skewness_pareto (a,b)

Возвращает коэффициент асимметрии распределения Парето Pareto(a,b) с a>3,b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: kurtosis_pareto (a,b)

Возвращает коэффициент куртозиса распределения Парето Pareto(a,b) с a>4,b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: random_pareto (a,b)
Функция: random_pareto (a,b,n)

Возвращает значение симулированной случайной переменной распределения Парето Pareto(a,b) с a>0,b>0. Вызов random_pareto с третьим аргументом n дает случайную выборку размера n.

Реализован только метод обращения.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: pdf_weibull (x,a,b)

Возвращает значение функции плотности вероятности распределения Вейбулла Weibull(a,b) с a,b>0 в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: cdf_weibull (x,a,b)

Возвращает значение функции распределения Вейбулла Weibull(a,b) с a,b>0 в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: quantile_weibull (q,a,b)

Возвращает q-квантиль распределения Вейбулла Weibull(a,b) с a,b>0, т.е. значение функции обратной cdf_weibull. Значение аргумента q должно быть в интервале [0,1].

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: mean_weibull (a,b)

Возвращает среднее значение распределения Вейбулла Weibull(a,b) с a,b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: var_weibull (a,b)

Возвращает дисперсию распределения Вейбулла Weibull(a,b) с a,b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: std_weibull (a,b)

Возвращает стандартное отклонение распределения Вейбулла Weibull(a,b) с a,b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: skewness_weibull (a,b)

Возвращает коэффициент асимметрии распределения Вейбулла Weibull(a,b) с a,b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: kurtosis_weibull (a,b)

Возвращает коэффициент куртозиса распределения Вейбулла Weibull(a,b) с a,b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: random_weibull (a,b)
Функция: random_weibull (a,b,n)

Возвращает значение симулированной случайной переменной распределения Вейбулла Weibull(a,b) с a,b>0. Вызов random_continuous_weibull с третьим аргументом n дает случайную выборку размера n.

Реализован только метод обращения.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: pdf_rayleigh (x,b)

Возвращает значение функции плотности вероятности распределения Релея Rayleigh(b) с b>0 в точке x.

Случайная переменная Rayleigh(b) эквивалентна случайной переменной Weibull(2,1/b). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах плотности вероятности распределения Вейбулла.

(%i1) load ("distrib")$
(%i2) pdf_rayleigh(x,b);
                                        1
(%o2)                 pdf_weibull(x, 2, -)
                                        b
(%i3) assume(x>0,b>0)$ pdf_rayleigh(x,b);
                                    2  2
                           2     - b  x
(%o4)                   2 b  x %e
Функция: cdf_rayleigh (x,b)

Возвращает значение функции распределения Релея Rayleigh(b) с b>0 в точке x.

Случайная переменная Rayleigh(b) эквивалентна случайной переменной Weibull(2,1/b). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах функции распределения распределения Вейбулла.

(%i1) load ("distrib")$
(%i2) cdf_rayleigh(x,b);
                                        1
(%o2)                 cdf_weibull(x, 2, -)
                                        b
(%i3) assume(x>0,b>0)$ cdf_rayleigh(x,b);
                                   2  2
                                - b  x
(%o4)                     1 - %e
Функция: quantile_rayleigh (q,b)

Возвращает q-квантиль распределения Релея Rayleigh(b) с b>0, т.е. значение функции обратной cdf_rayleigh. Значение аргумента q должно быть в интервале [0,1].

Случайная переменная Rayleigh(b) эквивалентна случайной переменной Weibull(2,1/b). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах квантили распределения Вейбулла.

(%i1) load ("distrib")$
(%i2) quantile_rayleigh(0.99,b);
                                            1
(%o2)             quantile_weibull(0.99, 2, -)
                                            b
(%i3) assume(x>0,b>0)$ quantile_rayleigh(0.99,b);
                        2.145966026289347
(%o4)                   -----------------
                                b
Функция: mean_rayleigh (b)

Возвращает среднее значение распределения Релея Rayleigh(b) с b>0.

Случайная переменная Rayleigh(b) эквивалентна случайной переменной Weibull(2,1/b). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах среднего значения распределения Вейбулла.

(%i1) load ("distrib")$
(%i2) mean_rayleigh(b);
                                       1
(%o2)                  mean_weibull(2, -)
                                       b
(%i3) assume(b>0)$ mean_rayleigh(b);
                            sqrt(%pi)
(%o4)                       ---------
                               2 b
Функция: var_rayleigh (b)

Возвращает дисперсию распределения Релея Rayleigh(b) с b>0.

Случайная переменная Rayleigh(b) эквивалентна случайной переменной Weibull(2,1/b). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах дисперсии распределения Вейбулла.

(%i1) load ("distrib")$
(%i2) var_rayleigh(b);
                                       1
(%o2)                   var_weibull(2, -)
                                       b
(%i3) assume(b>0)$ var_rayleigh(b);
                                 %pi
                             1 - ---
                                  4
(%o4)                        -------
                                2
                               b
Функция: std_rayleigh (b)

Возвращает стандартное отклонение распределения Релея Rayleigh(b) с b>0.

Случайная переменная Rayleigh(b) эквивалентна случайной переменной Weibull(2,1/b). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах стандартного отклонения распределения Вейбулла.

(%i1) load ("distrib")$
(%i2) std_rayleigh(b);
                                       1
(%o2)                   std_weibull(2, -)
                                       b
(%i3) assume(b>0)$ std_rayleigh(b);
                                   %pi
                          sqrt(1 - ---)
                                    4
(%o4)                     -------------
                                b
Функция: skewness_rayleigh (b)

Возвращает коэффициент асимметрии распределения Релея Rayleigh(b) с b>0.

Случайная переменная Rayleigh(b) эквивалентна случайной переменной Weibull(2,1/b). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах коэффициента асимметрии распределения Вейбулла.

(%i1) load ("distrib")$
(%i2) skewness_rayleigh(b);
                                         1
(%o2)                skewness_weibull(2, -)
                                         b
(%i3) assume(b>0)$ skewness_rayleigh(b);
                         3/2
                      %pi      3 sqrt(%pi)
                      ------ - -----------
                        4           4
(%o4)                 --------------------
                               %pi 3/2
                          (1 - ---)
                                4
Функция: kurtosis_rayleigh (b)

Возвращает коэффициент куртозиса распределения Релея Rayleigh(b) с b>0.

Случайная переменная Rayleigh(b) эквивалентна случайной переменной Weibull(2,1/b). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах коэффициента куртозиса распределения Вейбулла.

(%i1) load ("distrib")$
(%i2) kurtosis_rayleigh(b);
                                         1
(%o2)                kurtosis_weibull(2, -)
                                         b
(%i3) assume(b>0)$ kurtosis_rayleigh(b);
                                  2
                             3 %pi
                         2 - ------
                               16
(%o4)                    ---------- - 3
                              %pi 2
                         (1 - ---)
                               4
Функция: random_rayleigh (b)
Функция: random_rayleigh (b,n)

Возвращает значение симулированной случайной переменной распределения Релея Rayleigh(b) с b>0. Вызов random_rayleigh со вторым аргументом n дает случайную выборку размера n.

Реализован только метод обращения.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: pdf_laplace (x,a,b)

Возвращает значение функции плотности вероятности распределения Лапласа Laplace(a,b) с b>0 в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: cdf_laplace (x,a,b)

Возвращает значение функции распределения Лапласа Laplace(a,b) с b>0 в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: quantile_laplace (q,a,b)

Возвращает q-квантиль распределения Лапласа Laplace(a,b) с b>0, т.е. значение функции обратной cdf_laplace. Значение аргумента q должно быть в интервале [0,1].

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: mean_laplace (a,b)

Возвращает среднее значение распределения Лапласа Laplace(a,b) с b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: var_laplace (a,b)

Возвращает дисперсию распределения Лапласа Laplace(a,b) с b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: std_laplace (a,b)

Возвращает стандартное отклонение распределения Лапласа Laplace(a,b) с b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: skewness_laplace (a,b)

Возвращает коэффициент асимметрии распределения Лапласа Laplace(a,b) с b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: kurtosis_laplace (a,b)

Возвращает коэффициент куртозиса распределения Лапласа Laplace(a,b) с b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: random_laplace (a,b)
Функция: random_laplace (a,b,n)

Возвращает значение симулированной случайной переменной распределения Лапласа Laplace(a,b) с b>0. Вызов random_laplace с третьим аргументом n дает случайную выборку размера n.

Реализован только метод обращения.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: pdf_cauchy (x,a,b)

Возвращает значение функции плотности вероятности распределения Коши Cauchy(a,b) с b>0 в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: cdf_cauchy (x,a,b)

Возвращает значение функции распределения Коши Cauchy(a,b) с b>0 в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: quantile_cauchy (q,a,b)

Возвращает q-квантиль распределения Коши Cauchy(a,b) с b>0, т.е. значение функции обратной cdf_cauchy. Значение аргумента q должно быть в интервале [0,1].

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: random_cauchy (a,b)
Функция: random_cauchy (a,b,n)

Возвращает значение симулированной случайной переменной распределения Коши Cauchy(a,b) с b>0. Вызов random_cauchy с третьим аргументом n дает случайную выборку размера n.

Реализован только метод обращения.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: pdf_gumbel (x,a,b)

Возвращает значение функции плотности вероятности распределения Гумбеля Gumbel(a,b) с b>0 в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: cdf_gumbel (x,a,b)

Возвращает значение функции распределения Гумбеля Gumbel(a,b) с b>0 в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: quantile_gumbel (q,a,b)

Возвращает q-квантиль распределения Гумбеля Gumbel(a,b) с b>0, т.е. значение функции обратной cdf_gumbel. Значение аргумента q должно быть в интервале [0,1].

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: mean_gumbel (a,b)

Возвращает среднее значение распределения Гумбеля Gumbel(a,b) с b>0.

(%i1) load ("distrib")$
(%i2) assume(b>0)$  mean_gumbel(a,b);
(%o3)                     %gamma b + a

где %gamma – константа Эйлера-Маскерони. См. также %gamma.

Функция: var_gumbel (a,b)

Возвращает дисперсию распределения Гумбеля Gumbel(a,b) с b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: std_gumbel (a,b)

Возвращает стандартное отклонение распределения Гумбеля Gumbel(a,b) с b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: skewness_gumbel (a,b)

Возвращает коэффициент асимметрии распределения Гумбеля Gumbel(a,b) с b>0.

(%i1) load ("distrib")$
(%i2) assume(b>0)$ skewness_gumbel(a,b);
                       12 sqrt(6) zeta(3)
(%o3)                  ------------------
                                 3
                              %pi
(%i4) numer:true$ skewness_gumbel(a,b);
(%o5)                   1.139547099404649

где zeta – дзэта-функция Римана.

Функция: kurtosis_gumbel (a,b)

Возвращает коэффициент куртозиса распределения Гумбеля Gumbel(a,b) с b>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: random_gumbel (a,b)
Функция: random_gumbel (a,b,n)

Возвращает значение симулированной случайной переменной распределения Гумбеля Gumbel(a,b) с b>0. Вызов random_gumbel с третьим аргументом n дает случайную выборку размера n.

Реализован только метод обращения.

Для использования этой функции, ее необходимо загрузить командой load("distrib").


Previous: Функции и переменные для непрерывных распределений, Up: Пакет distrib   [Contents][Index]

45.3 Функции и переменные для дискретных распределений

Функция: pdf_binomial (x,n,p)

Возвращает значение функции плотности вероятности биномиального распределения Binomial(n,p) с 0<p<1 и положительным целым n в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: cdf_binomial (x,n,p)

Возвращает значение функции распределения биномиального распределения Binomial(n,p) с 0<p<1 и положительным целым n в точке x.

Эта функция вычисляется численно, если значение глобальной переменной numer рано true, иначе возвращается номинальное выражение.

(%i1) load ("distrib")$
(%i2) cdf_binomial(5,7,1/6);
                                         1
(%o2)                 cdf_binomial(5, 7, -)
                                         6
(%i3) cdf_binomial(5,7,1/6), numer;
(%o3)                   .9998713991769548
Функция: quantile_binomial (q,n,p)

Возвращает q-квантиль биномиального распределения Binomial(n,p) с 0<p<1 и положительным целым n, т.е. значение функции обратной cdf_binomial. Значение аргумента q должно быть в интервале [0,1].

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: mean_binomial (n,p)

Возвращает среднее значение биномиального распределения Binomial(n,p) с 0<p<1 и положительным целым n.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: var_binomial (n,p)

Возвращает дисперсию биномиального распределения Binomial(n,p) с 0<p<1 и положительным целым n.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: std_binomial (n,p)

Возвращает стандартное отклонение биномиального распределения Binomial(n,p) с 0<p<1 и положительным целым n.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: skewness_binomial (n,p)

Возвращает коэффициент асимметрии биномиального распределения Binomial(n,p) с 0<p<1 и положительным целым n.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: kurtosis_binomial (n,p)

Возвращает коэффициент куртозиса биномиального распределения Binomial(n,p) с 0<p<1 и положительным целым n.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Управляющая переменная: random_binomial_algorithm

Значение по умолчанию: kachit

Определяет алгоритм, выбранный для симулирования случайной переменной биномиального распределения. Реализованы алгоритмы kachit, bernoulli и inverse:

См. также random_binomial.

Функция: random_binomial (n,p)
Функция: random_binomial (n,p,m)

Возвращает значение симулированной случайной переменной биномиального распределения Binomial(n,p) с 0<p<1 и положительным целым n. Вызов random_binomial с третьим аргументом m дает случайную выборку размера m.

Для этой функции реализовано три алгоритма. Используемый алгоритм определяется значением глобальной переменной random_binomial_algorithm, которая по умолчанию равна kachit.

См. также random_binomial_algorithm.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: pdf_poisson (x,m)

Возвращает значение функции плотности вероятности распределения Пуассона Poisson(m) с m>0 в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: cdf_poisson (x,m)

Возвращает значение функции распределения Пуассона Poisson(m) с m>0 в точке x.

Эта функция вычисляется численно, если значение глобальной переменной numer рано true, иначе возвращается номинальное выражение.

(%i1) load ("distrib")$
(%i2) cdf_poisson(3,5);
(%o2)                   cdf_poisson(3, 5)
(%i3) cdf_poisson(3,5), numer;
(%o3)                   .2650259152973617
Функция: quantile_poisson (q,m)

Возвращает q-квантиль распределения Пуассона Poisson(m) с m>0, т.е. значение функции обратной cdf_poisson. Значение аргумента q должно быть в интервале [0,1].

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: mean_poisson (m)

Возвращает среднее значение распределения Пуассона Poisson(m) с m>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: var_poisson (m)

Возвращает дисперсию распределения Пуассона Poisson(m) с m>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: std_poisson (m)

Возвращает стандартное отклонение распределения Пуассона Poisson(m) с m>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: skewness_poisson (m)

Возвращает коэффициент асимметрии распределения Пуассона Poisson(m) с m>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: kurtosis_poisson (m)

Возвращает коэффициент куртозиса распределения Пуассона Poisson(m) с m>0.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Управляющая переменная: random_poisson_algorithm

Значение по умолчанию: ahrens_dieter

Определяет алгоритм, выбранный для симулирования случайной переменной распределения Пуассона. Реализованы алгоритмы ahrens_dieter и inverse:

См. также random_poisson.

Функция: random_poisson (m)
Функция: random_poisson (m,n)

Возвращает значение симулированной случайной переменной распределения Пуассона Poisson(m) с m>0. Вызов random_poisson со вторым аргументом n дает случайную выборку размера n.

Для этой функции реализовано два алгоритма. Используемый алгоритм определяется значением глобальной переменной random_poisson_algorithm, которая по умолчанию равна ahrens_dieter.

См. также random_poisson_algorithm.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: pdf_bernoulli (x,p)

Возвращает значение функции плотности вероятности распределения Бернулли Bernoulli(p) с 0<p<1 в точке x.

Случайная переменная Bernoulli(p) эквивалентна случайной переменной Binomial(1,p). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах плотности вероятности биномиального распределения.

(%i1) load ("distrib")$
(%i2) pdf_bernoulli(1,p);
(%o2)                 pdf_binomial(1, 1, p)
(%i3) assume(0<p,p<1)$ pdf_bernoulli(1,p);
(%o4)                           p
Функция: cdf_bernoulli (x,p)

Возвращает значение функции распределения Бернулли Bernoulli(p) с 0<p<1 в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: quantile_bernoulli (q,p)

Возвращает q-квантиль распределения Бернулли Bernoulli(p) с 0<p<1, т.е. значение функции обратной cdf_bernoulli. Значение аргумента q должно быть в интервале [0,1].

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: mean_bernoulli (p)

Возвращает среднее значение распределения Бернулли Bernoulli(p) с 0<p<1.

Случайная переменная Bernoulli(p) эквивалентна случайной переменной Binomial(1,p). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах среднего значения биномиального распределения.

(%i1) load ("distrib")$
(%i2) mean_bernoulli(p);
(%o2)                  mean_binomial(1, p)
(%i3) assume(0<p,p<1)$ mean_bernoulli(p);
(%o4)                           p
Функция: var_bernoulli (p)

Возвращает дисперсию распределения Бернулли Bernoulli(p) с 0<p<1.

Случайная переменная Bernoulli(p) эквивалентна случайной переменной Binomial(1,p). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах дисперсии биномиального распределения.

(%i1) load ("distrib")$
(%i2) var_bernoulli(p);
(%o2)                  var_binomial(1, p)
(%i3) assume(0<p,p<1)$ var_bernoulli(p);
(%o4)                       (1 - p) p
Функция: std_bernoulli (p)

Возвращает стандартное отклонение распределения Бернулли Bernoulli(p) с 0<p<1.

Случайная переменная Bernoulli(p) эквивалентна случайной переменной Binomial(1,p). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах стандартного отклонения биномиального распределения.

(%i1) load ("distrib")$
(%i2) std_bernoulli(p);
(%o2)                  std_binomial(1, p)
(%i3) assume(0<p,p<1)$ std_bernoulli(p);
(%o4)                  sqrt(1 - p) sqrt(p)
Функция: skewness_bernoulli (p)

Возвращает коэффициент асимметрии распределения Бернулли Bernoulli(p) с 0<p<1.

Случайная переменная Bernoulli(p) эквивалентна случайной переменной Binomial(1,p). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах коэффициента асимметрии биномиального распределения.

(%i1) load ("distrib")$
(%i2) skewness_bernoulli(p);
(%o2)                skewness_binomial(1, p)
(%i3) assume(0<p,p<1)$ skewness_bernoulli(p);
                             1 - 2 p
(%o4)                  -------------------
                       sqrt(1 - p) sqrt(p)
Функция: kurtosis_bernoulli (p)

Возвращает коэффициент куртозиса распределения Бернулли Bernoulli(p) с 0<p<1.

Случайная переменная Bernoulli(p) эквивалентна случайной переменной Binomial(1,p). Таким образом, если недостаточно информации для вычисления результата, возвращается невычисляемая форма в терминах коэффициента куртозиса биномиального распределения.

(%i1) load ("distrib")$
(%i2) kurtosis_bernoulli(p);
(%o2)                kurtosis_binomial(1, p)
(%i3) assume(0<p,p<1)$ kurtosis_bernoulli(p);
                         1 - 6 (1 - p) p
(%o4)                    ---------------
                            (1 - p) p
Функция: random_bernoulli (p)
Функция: random_bernoulli (p,n)

Возвращает значение симулированной случайной переменной распределения Бернулли Bernoulli(p) с 0<p<1. Вызов random_bernoulli со вторым аргументом n дает случайную выборку размера n.

Для вычисления используется встроенная Maxima функция random.

См. также random.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: pdf_geometric (x,p)

Возвращает значение функции плотности вероятности геометрического распределения Geometric(p) с 0<p<1 в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: cdf_geometric (x,p)

Возвращает значение функции распределения геометрического распределения Geometric(p) с 0<p<1 в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: quantile_geometric (q,p)

Возвращает q-квантиль геометрического распределения Geometric(p) с 0<p<1, т.е. значение функции обратной cdf_geometric. Значение аргумента q должно быть в интервале [0,1].

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: mean_geometric (p)

Возвращает среднее значение геометрического распределения Geometric(p) с 0<p<1.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: var_geometric (p)

Возвращает дисперсию геометрического распределения Geometric(p) с 0<p<1.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: std_geometric (p)

Возвращает стандартное отклонение геометрического распределения Geometric(p) с 0<p<1.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: skewness_geometric (p)

Возвращает коэффициент асимметрии геометрического распределения Geometric(p) с 0<p<1.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: kurtosis_geometric (p)

Возвращает коэффициент куртозиса геометрического распределения Geometric(p) с 0<p<1.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Управляющая переменная: random_geometric_algorithm

Значение по умолчанию: bernoulli

Определяет алгоритм, выбранный для симулирования случайной переменной геометрического распределения. Реализованы алгоритмы bernoulli, devroye и inverse:

См. также random_geometric.

Функция: random_geometric (p)
Функция: random_geometric (p,n)

Возвращает значение симулированной случайной переменной геометрического распределения Geometric(p) с 0<p<1. Вызов random_geometric со вторым аргументом n дает случайную выборку размера n.

Для этой функции реализовано три алгоритма. Используемый алгоритм определяется значением глобальной переменной random_geometric_algorithm, которая по умолчанию равна bernoulli.

См. также random_geometric_algorithm.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: pdf_discrete_uniform (x,n)

Возвращает значение функции плотности вероятности равномерного дискретного распределения Discrete Uniform(n) со строго положительным целым n в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: cdf_discrete_uniform (x,n)

Возвращает значение функции распределения равномерного дискретного распределения Discrete Uniform(n) со строго положительным целым n в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: quantile_discrete_uniform (q,n)

Возвращает q-квантиль равномерного дискретного распределения Discrete Uniform(n) со строго положительным целым n, т.е. значение функции обратной cdf_discrete_uniform. Значение аргумента q должно быть в интервале [0,1].

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: mean_discrete_uniform (n)

Возвращает среднее значение равномерного дискретного распределения Discrete Uniform(n) со строго положительным целым n.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: var_discrete_uniform (n)

Возвращает дисперсию равномерного дискретного распределения Discrete Uniform(n) со строго положительным целым n.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: std_discrete_uniform (n)

Возвращает стандартное отклонение равномерного дискретного распределения Discrete Uniform(n) со строго положительным целым n.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: skewness_discrete_uniform (n)

Возвращает коэффициент асимметрии равномерного дискретного распределения Discrete Uniform(n) со строго положительным целым n.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: kurtosis_discrete_uniform (n)

Возвращает коэффициент куртозиса равномерного дискретного распределения Discrete Uniform(n) со строго положительным целым n.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: random_discrete_uniform (n)
Функция: random_discrete_uniform (n,m)

Возвращает значение симулированной случайной переменной равномерного дискретного распределения Discrete Uniform(n) со строго положительным целым n. Вызов random_discrete_uniform со вторым аргументом m дает случайную выборку размера m.

Для вычисления используется встроенная Maxima функция random.

См. также random.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: pdf_hypergeometric (x,n1,n2,n)

Возвращает значение функции плотности вероятности гипергеометрического распределения Hypergeometric(n1,n2,n) с неотрицательными целыми n1, n2, n при условии n<=n1+n2 в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: cdf_hypergeometric (x,n1,n2,n)

Возвращает значение функции распределения гипергеометрического распределения Hypergeometric(n1,n2,n) с неотрицательными целыми n1, n2, n при условии n<=n1+n2 в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: quantile_hypergeometric (q,n1,n2,n)

Возвращает q-квантиль гипергеометрического распределения Hypergeometric(n1,n2,n) с неотрицательными целыми n1, n2, n при условии n<=n1+n2, т.е. значение функции обратной cdf_hypergeometric. Значение аргумента q должно быть в интервале [0,1].

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: mean_hypergeometric (n1,n2,n)

Возвращает среднее значение гипергеометрического распределения Hypergeometric(n1,n2,n), с неотрицательными целыми n1, n2, n при условии n<=n1+n2.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: var_hypergeometric (n1,n2,n)

Возвращает дисперсию гипергеометрического распределения Hypergeometric(n1,n2,n), с неотрицательными целыми n1, n2, n при условии n<=n1+n2.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: std_hypergeometric (n1,n2,n)

Возвращает стандартное отклонение гипергеометрического распределения Hypergeometric(n1,n2,n), с неотрицательными целыми n1, n2, n при условии n<=n1+n2.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: skewness_hypergeometric (n1,n2,n)

Возвращает коэффициент асимметрии гипергеометрического распределения Hypergeometric(n1,n2,n), с неотрицательными целыми n1, n2, n при условии n<=n1+n2.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: kurtosis_hypergeometric (n1,n2,n)

Возвращает коэффициент куртозиса гипергеометрического распределения Hypergeometric(n1,n2,n), с неотрицательными целыми n1, n2, n при условии n<=n1+n2.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Управляющая переменная: random_hypergeometric_algorithm

Значение по умолчанию: kachit

Определяет алгоритм, выбранный для симулирования случайной переменной гипергеометрического распределения. Реализованы алгоритмы kachit и inverse:

См. также random_hypergeometric.

Функция: random_hypergeometric (n1,n2,n)
Функция: random_hypergeometric (n1,n2,n,m)

Возвращает значение симулированной случайной переменной гипергеометрического распределения Hypergeometric(n1,n2,n) с неотрицательными целыми n1, n2,n при условии n<=n1+n2. Вызов random_hypergeometric с четвертым аргументом m дает случайную выборку размера m.

Для этой функции реализовано два алгоритма. Используемый алгоритм определяется значением глобальной переменной random_hypergeometric_algorithm, которая по умолчанию равна kachit.

См. также random_hypergeometric_algorithm.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: pdf_negative_binomial (x,n,p)

Возвращает значение функции плотности вероятности отрицательного биномиального распределения Negative Binomial(n,p) с 0<p<1 и положительным целым n в точке x.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: cdf_negative_binomial (x,n,p)

Возвращает значение функции распределения отрицательного биномиального распределения Negative Binomial(n,p) с 0<p<1 и положительным целым n в точке x.

Эта функция вычисляется численно, если значение глобальной переменной numer рано true, иначе возвращается номинальное выражение.

(%i1) load ("distrib")$
(%i2) cdf_negative_binomial(3,4,1/8);
                                             1
(%o2)            cdf_negative_binomial(3, 4, -)
                                             8
(%i3) cdf_negative_binomial(3,4,1/8), numer;
(%o3)                  .006238937377929698
Функция: quantile_negative_binomial (q,n,p)

Возвращает q-квантиль отрицательного биномиального распределения Negative Binomial(n,p) с 0<p<1 и положительным целым n, т.е. значение функции обратной cdf_negative_binomial. Значение аргумента q должно быть в интервале [0,1].

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: mean_negative_binomial (n,p)

Возвращает среднее значение отрицательного биномиального распределения Negative Binomial(n,p) с 0<p<1 и положительным целым n.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: var_negative_binomial (n,p)

Возвращает дисперсию отрицательного биномиального распределения Negative Binomial(n,p) с 0<p<1 и положительным целым n.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: std_negative_binomial (n,p)

Возвращает стандартное отклонение отрицательного биномиального распределения Negative Binomial(n,p) с 0<p<1 и положительным целым n.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: skewness_negative_binomial (n,p)

Возвращает коэффициент асимметрии отрицательного биномиального распределения Negative Binomial(n,p) с 0<p<1 и положительным целым n.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Функция: kurtosis_negative_binomial (n,p)

Возвращает коэффициент куртозиса отрицательного биномиального распределения Negative Binomial(n,p) с 0<p<1 и положительным целым n.

Для использования этой функции, ее необходимо загрузить командой load("distrib").

Управляющая переменная: random_negative_binomial_algorithm

Значение по умолчанию: bernoulli

Определяет алгоритм, выбранный для симулирования случайной переменной отрицательного биномиального распределения. Реализованы алгоритмы devroye, bernoulli и inverse:

См. также random_negative_binomial.

Функция: random_negative_binomial (n,p)
Функция: random_negative_binomial (n,p,m)

Возвращает значение симулированной случайной переменной отрицательного биномиального распределения Negative Binomial(n,p) с 0<p<1 и положительным целым n. Вызов random_negative_binomial с третьим аргументом m дает случайную выборку размера m.

Для этой функции реализовано три алгоритма. Используемый алгоритм определяется значением глобальной переменной random_negative_binomial_algorithm, которая по умолчанию равна bernoulli.

См. также random_negative_binomial_algorithm.

Для использования этой функции, ее необходимо загрузить командой load("distrib").


Next: , Previous: Пакет distrib, Up: Top   [Contents][Index]

46 Пакет draw


Next: , Previous: Пакет draw, Up: Пакет draw   [Contents][Index]

46.1 Введение в пакет draw

draw является интерфейсом Maxima к программе Gnuplot.

На уровне Maxima есть три основные функции: draw2d, draw3d и draw.

Более сложные примеры использования пакета можно найти по ссылке:

http://www.telefonica.net/web2/biomates/maxima/gpdraw

Для работы программы требуется Gnuplot 4.2.


Next: , Previous: Введение в пакет draw, Up: Пакет draw   [Contents][Index]

46.2 Функции и переменные пакета draw

Графическая опция: xrange

Значение по умолчанию: auto

Если xrange равно auto, то диапазон координаты x вычисляется автоматически.

Если требуется определенный интервал x, он должен быть задан в форме списка, например xrange=[-2, 3].

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw2d(xrange = [-3,5],
             explicit(x^2,x,-1,1))$

См. yrange и zrange.

Графическая опция: yrange

Значение по умолчанию: auto

Если yrange равно auto, то диапазон координаты y вычисляется автоматически.

Если требуется определенный интервал y, он должен быть задан в форме списка, например yrange=[-2, 3].

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw2d(yrange = [-2,3],
             explicit(x^2,x,-1,1),
             xrange = [-3,3])$

См. xrange и zrange.

Графическая опция: zrange

Значение по умолчанию: auto

Если zrange равно auto, то диапазон координаты z вычисляется автоматически.

Если требуется определенный интервал z, он должен быть задан в форме списка, например zrange=[-2, 3].

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw3d(yrange = [-3,3],
             zrange = [-2,5],
             explicit(x^2+y^2,x,-1,1,y,-1,1),
             xrange = [-3,3])$

См. xrange и yrange.

Графическая опция: logx

Значение по умолчанию: false

Если logx равно true, то ось x будет изображаться в логарифмической шкале.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw2d(explicit(log(x),x,0.01,5),
             logx = true)$

См. logy и logz.

Графическая опция: logy

Значение по умолчанию: false

Если logy равно true, то ось y будет изображаться в логарифмической шкале.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw2d(logy = true,
             explicit(exp(x),x,0,5))$

См. logx и logz.

Графическая опция: logz

Значение по умолчанию: false

Если logz равно true, то ось z будет изображаться в логарифмической шкале.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw3d(logz = true,
             explicit(exp(u^2+v^2),u,-2,2,v,-2,2))$

См. logx и logy.

Графическая опция: terminal

Значение по умолчанию: screen

Выбирает терминал, используемый программой Gnuplot. Возможные значения: screen (умолчание), png, jpg, eps, eps_color, gif, animated_gif и wxt.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения. Она также может использоваться как аргумент функции draw.

Примеры:

(%i1) load("draw")$
(%i2) /* screen terminal (default) */
      draw2d(explicit(x^2,x,-1,1))$
(%i3) /* png file */
      draw2d(terminal  = 'png,
             pic_width = 300,
             explicit(x^2,x,-1,1))$
(%i4) /* jpg file */
      draw2d(terminal   = 'jpg,
             pic_width  = 300,
             pic_height = 300,
             explicit(x^2,x,-1,1))$
(%i5) /* eps file */
      draw2d(file_name = "myfile",
             explicit(x^2,x,-1,1),
             terminal  = 'eps)$
(%i6) /* wxwidgets window */
      draw2d(explicit(x^2,x,-1,1),
             terminal  = 'wxt)$

Файл анимированного gif:

(%i1) load("draw")$
(%i2) draw(
        delay     = 100,
        file_name = "zzz",
        terminal  = 'animated_gif,
        gr2d(explicit(x^2,x,-1,1)),
        gr2d(explicit(x^3,x,-1,1)),
        gr2d(explicit(x^4,x,-1,1)));
End of animation sequence
(%o2)          [gr2d(explicit), gr2d(explicit), gr2d(explicit)]

Опция delay возможна тоько для анимированного gif. В других случаях она игнорируется.

См. file_name, pic_width, pic_height и delay.

Графическая опция: grid

Значение по умолчанию: false

Если grid равно true, то на плоскости xy будет изображена сетка.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw2d(grid = true,
             explicit(exp(u),u,-2,2))$
Графическая опция: title

Значение по умолчанию: "" (пустая строка)

Опция title – строка, содержащая основной заголовок сцены. По умолчанию заголовок отсутствует.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw2d(explicit(exp(u),u,-2,2),
             title = "Exponential function")$
Графическая опция: xlabel

Значение по умолчанию: "" (пустая строка)

Опция xlabel – строка, содержащая метку для оси x. По умолчанию метка отсутствует.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw2d(xlabel = "Time",
             explicit(exp(u),u,-2,2),
             ylabel = "Population")$

См. ylabel и zlabel.

Графическая опция: ylabel

Значение по умолчанию: "" (пустая строка)

Опция ylabel – строка, содержащая метку для оси y. По умолчанию метка отсутствует.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw2d(xlabel = "Time",
             ylabel = "Population",
             explicit(exp(u),u,-2,2) )$

См. xlabel и zlabel.

Графическая опция: zlabel

Значение по умолчанию: "" (пустая строка)

Опция zlabel – строка, содержащая метку для оси z. По умолчанию метка отсутствует.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw3d(zlabel = "Z variable",
             ylabel = "Y variable",
             explicit(sin(x^2+y^2),x,-2,2,y,-2,2),
             xlabel = "X variable" )$

См. xlabel и ylabel.

Графическая опция: xtics

Значение по умолчанию: auto

Управляет методом изображения делений на оси x.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Примеры:

Деления отключены.

(%i1) load("draw")$
(%i2) draw2d(xtics = 'none,
             explicit(x^3,x,-1,1)  )$

Деления на каждой 1/4.

(%i1) load("draw")$
(%i2) draw2d(xtics = 1/4,
             explicit(x^3,x,-1,1)  )$

Деления на значениях от -3/4 до 3/4 с шагом 1/8.

(%i1) load("draw")$
(%i2) draw2d(xtics = [-3/4,1/8,3/4],
             explicit(x^3,x,-1,1)  )$

Деления в точках -1/2, -1/4 и 3/4.

(%i1) load("draw")$
(%i2) draw2d(xtics = {-1/2,-1/4,3/4},
             explicit(x^3,x,-1,1)  )$

Деления с метками.

(%i1) load("draw")$
(%i2) draw2d(xtics = {["High",0.75],["Medium",0],["Low",-0.75]},
             explicit(x^3,x,-1,1)  )$

См. ytics и ztics.

Графическая опция: ytics

Значение по умолчанию: auto

Управляет методом изображения делений на оси y.

См. xtics для полного описания.

Графическая опция: ztics

Значение по умолчанию: auto

Управляет методом изображения делений на оси z.

См. xtics для полного описания.

Графическая опция: xtics_rotate

Значение по умолчанию: false

Если xtics_rotate равно true, то деления на оси x поворачиваются на 90 градусов.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Графическая опция: ytics_rotate

Значение по умолчанию: false

Если ytics_rotate равно true, то деления на оси y поворачиваются на 90 градусов.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Графическая опция: ztics_rotate

Значение по умолчанию: false

Если ztics_rotate равно true, то деления на оси z поворачиваются на 90 градусов.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Графическая опция: xtics_axis

Значение по умолчанию: false

Если xtics_axis равно true, то деления и их метки изображаются вдоль оси x, если false, то деления изображаются на границе.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Графическая опция: ytics_axis

Значение по умолчанию: false

Если ytics_axis равно true, то деления и их метки изображаются вдоль оси y, если false, то деления изображаются на границе.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Графическая опция: ztics_axis

Значение по умолчанию: false

Если ztics_axis равно true, то деления и их метки изображаются вдоль оси z, если false, то деления изображаются на границе.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Графическая опция: xaxis

Значение по умолчанию: false

Если xaxis равно true, то ось x изображается.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw2d(explicit(x^3,x,-1,1),
             xaxis       = true,
             xaxis_color = blue)$

См. xaxis_width, xaxis_type и xaxis_color.

Графическая опция: xaxis_width

Значение по умолчанию: 1

xaxis_width – толщина оси x. Значение должно быть положительным числом.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw2d(explicit(x^3,x,-1,1),
             xaxis       = true,
             xaxis_width = 3)$

См. xaxis, xaxis_type и xaxis_color.

Графическая опция: xaxis_type

Значение по умолчанию: dots

xaxis_type – задает стиль изображения оси x. Возможные значения: solid и dots.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw2d(explicit(x^3,x,-1,1),
             xaxis       = true,
             xaxis_type  = solid)$

См. xaxis, xaxis_width и xaxis_color.

Графическая опция: xaxis_color

Значение по умолчанию: "black"

xaxis_color – определяет цвет оси x axis. См. color для способа задания цвета.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw2d(explicit(x^3,x,-1,1),
             xaxis       = true,
             xaxis_color = red)$

См. xaxis, xaxis_width и xaxis_type.

Графическая опция: yaxis

Значение по умолчанию: false

Если yaxis равно true, то ось y изображается.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw2d(explicit(x^3,x,-1,1),
             yaxis       = true,
             yaxis_color = blue)$

См. yaxis_width, yaxis_type и yaxis_color.

Графическая опция: yaxis_width

Значение по умолчанию: 1

yaxis_width – толщина оси y. Значение должно быть положительным числом.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw2d(explicit(x^3,x,-1,1),
             yaxis       = true,
             yaxis_width = 3)$

См. yaxis, yaxis_type и yaxis_color.

Графическая опция: yaxis_type

Значение по умолчанию: dots

yaxis_type – задает стиль изображения y. Возможные значения: solid и dots.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw2d(explicit(x^3,x,-1,1),
             yaxis       = true,
             yaxis_type  = solid)$

См. yaxis, yaxis_width и yaxis_color.

Графическая опция: yaxis_color

Значение по умолчанию: "black"

yaxis_color – определяет цвет оси y axis. См. color для способа задания цвета.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw2d(explicit(x^3,x,-1,1),
             yaxis       = true,
             yaxis_color = red)$

См. yaxis, yaxis_width и yaxis_type.

Графическая опция: zaxis

Значение по умолчанию: false

Если zaxis равно true, то ось x изображается на трехмерных графиках. Эта опция не влияет на двумерные графики.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw3d(explicit(x^2+y^2,x,-1,1,y,-1,1),
             zaxis       = true,
             zaxis_type  = solid,
             zaxis_color = blue)$

См. zaxis_width, zaxis_type и zaxis_color.

Графическая опция: zaxis_width

Значение по умолчанию: 1

zaxis_width – толщина оси z. Значение должно быть положительным числом. Эта опция не влияет на двумерные графики.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw3d(explicit(x^2+y^2,x,-1,1,y,-1,1),
             zaxis       = true,
             zaxis_type  = solid,
             zaxis_width = 3)$

См. zaxis, zaxis_type и zaxis_color.

Графическая опция: zaxis_type

Значение по умолчанию: dots

zaxis_type – задает стиль изображения оси z. Возможные значения: solid и dots. Эта опция не влияет на двумерные графики.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw3d(explicit(x^2+y^2,x,-1,1,y,-1,1),
             zaxis       = true,
             zaxis_type  = solid)$

См. zaxis, zaxis_width и zaxis_color.

Графическая опция: zaxis_color

Значение по умолчанию: "black"

zaxis_color – определяет цвет оси z axis. См. color для способа задания цвета. Эта опция не влияет на двумерные графики.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw3d(explicit(x^2+y^2,x,-1,1,y,-1,1),
             zaxis       = true,
             zaxis_type  = solid,
             zaxis_color = red)$

См. zaxis, zaxis_width и zaxis_type.

Графическая опция: rot_vertical

Значение по умолчанию: 60

rot_vertical – угол поворота (в градусах) вокруг оси x точки наблюдения в трехмерных сценах.

Угол может быть в интервале [0, 180].

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw3d(rot_vertical = 170,
             explicit(sin(x^2+y^2),x,-2,2,y,-2,2) )$

См. rot_horizontal.

Графическая опция: rot_horizontal

Значение по умолчанию: 30

rot_horizontal – угол поворота (в градусах) вокруг оси z точки наблюдения в трехмерных сценах.

Угол может быть в интервале [0, 360].

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw3d(rot_vertical = 170,
             rot_horizontal = 360,
             explicit(sin(x^2+y^2),x,-2,2,y,-2,2) )$

См. rot_vertical.

Графическая опция: xy_file

Значение по умолчанию: "" (пустая строка)

xy_file – имя файла, в котором будут сохранены координаты после щелчка мышкой и нажатия клавиши ’x’. По умолчанию координаты не сохраняются.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Графическая опция: user_preamble

Значение по умолчанию: "" (пустая строка)

Опытные пользователи Gnuplot могут использовать эту опцию для тонкой настройке поведения Gnuplot путем задания установок до комманд plot или splot.

Значение этой опции должно быть строкой или списком строк (по одной на строку).

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

Терминал dumb не поддерживается пакетом draw, но можно задать его при помощи опции user_preamble,

(%i1) load("draw")$
(%i2) draw2d(explicit(exp(x)-1,x,-1,1),
             parametric(cos(u),sin(u),u,0,2*%pi),
             user_preamble="set terminal dumb")$
Графическая опция: file_name

Значение по умолчанию: "maxima_out"

Это имя файла, в котром терминалы png, jpg, eps и eps_color сохраняют графику.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения. Она также может использоваться как аргумент функции draw.

Пример:

(%i1) load("draw")$
(%i2) draw2d(file_name = "myfile",
             explicit(x^2,x,-1,1),
             terminal  = 'png)$

См. terminal, pic_width и pic_height.

Графическая опция: delay

Значение по умолчанию: 5

Это задержка в 1/100 секунды между кадрами анимированного gif.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения. Она также может использоваться как аргумент функции draw.

Пример:

(%i1) load("draw")$
(%i2) draw(
        delay     = 100,
        file_name = "zzz",
        terminal  = 'animated_gif,
        gr2d(explicit(x^2,x,-1,1)),
        gr2d(explicit(x^3,x,-1,1)),
        gr2d(explicit(x^4,x,-1,1)));
End of animation sequence
(%o2)          [gr2d(explicit), gr2d(explicit), gr2d(explicit)]

Опция delay применима только для анимированного gif. Для других случаев она игнорируется.

См. terminal, pic_width и pic_height.

Графическая опция: pic_width

Значение по умолчанию: 640

Это ширина изображения, создаваемого терминалами png и jpg.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения. Она также может использоваться как аргумент функции draw.

Пример:

(%i1) load("draw")$
(%i2) draw2d(terminal   = 'png,
             pic_width  = 300,
             pic_height = 300,
             explicit(x^2,x,-1,1))$

См. terminal, file_name и pic_height.

Графическая опция: pic_height

Значение по умолчанию: 640

Это высота изображения, создаваемого терминалами png и jpg.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения. Она также может использоваться как аргумент функции draw.

Пример:

(%i1) load("draw")$
(%i2) draw2d(terminal   = 'png,
             pic_width  = 300,
             pic_height = 300,
             explicit(x^2,x,-1,1))$

См. terminal, file_name и pic_width.

Графическая опция: eps_width

Значение по умолчанию: 12

Это ширина изображения Postscript (в сантиметрах), создаваемого терминалами eps и eps_color.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения. Она также может использоваться как аргумент функции draw.

Пример:

(%i1) load("draw")$
(%i2) draw2d(terminal   = 'eps,
             eps_width  = 3,
             eps_height = 3,
             explicit(x^2,x,-1,1))$

См. terminal, file_name и eps_height.

Графическая опция: eps_height

Значение по умолчанию: 8

Это высота изображения Postscript (в сантиметрах), создаваемого терминалами eps и eps_color.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения. Она также может использоваться как аргумент функции draw.

Пример:

(%i1) load("draw")$
(%i2) draw2d(terminal   = 'eps,
             eps_width  = 3,
             eps_height = 3,
             explicit(x^2,x,-1,1))$

См. terminal, file_name и eps_width.

Графическая опция: axis_bottom

Значение по умолчанию: true

Если axis_bottom равно true, то на двумерных сценах изображается нижняя ось.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw2d(axis_bottom = false,
             explicit(x^3,x,-1,1))$

См. axis_left, axis_top, axis_right и axis_3d.

Графическая опция: axis_left

Значение по умолчанию: true

Если axis_left равно true, то на двумерных сценах изображается левая ось.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw2d(axis_left = false,
             explicit(x^3,x,-1,1))$

См. axis_bottom, axis_top, axis_right и axis_3d.

Графическая опция: axis_top

Значение по умолчанию: true

Если axis_top равно true, то на двумерных сценах отображается верхняя ось.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw2d(axis_top = false,
             explicit(x^3,x,-1,1))$

См. axis_bottom, axis_left, axis_right и axis_3d.

Графическая опция: axis_right

Значение по умолчанию: true

Если axis_right равно true, то на двумерных сценах отображается правая ось.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw2d(axis_right = false,
             explicit(x^3,x,-1,1))$

См. axis_bottom, axis_left, axis_top и axis_3d.

Графическая опция: axis_3d

Значение по умолчанию: true

Если axis_3d равно true, то оси x, y и z изображаются на трехмерных сценах.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw3d(axis_3d = false,
             explicit(sin(x^2+y^2),x,-2,2,y,-2,2) )$

См. axis_bottom, axis_left, axis_top и axis_right для двух измерений.

Графическая опция: palette

Значение по умолчанию: color

palette определяет, как отобразить реальные значения матрицы, передаваемые в объект image, в компоненты цвета.

palette – вектор тремя компонентами со значеним в пределах от -36 до +36. Каждое значение является индексом для формулы, отображающей уровни в красный, зеленый и синий цвета соответственно:

 0: 0               1: 0.5           2: 1
 3: x               4: x^2           5: x^3
 6: x^4             7: sqrt(x)       8: sqrt(sqrt(x))
 9: sin(90x)       10: cos(90x)     11: |x-0.5|
12: (2x-1)^2       13: sin(180x)    14: |cos(180x)|
15: sin(360x)      16: cos(360x)    17: |sin(360x)|
18: |cos(360x)|    19: |sin(720x)|  20: |cos(720x)|
21: 3x             22: 3x-1         23: 3x-2
24: |3x-1|         25: |3x-2|       26: (3x-1)/2
27: (3x-2)/2       28: |(3x-1)/2|   29: |(3x-2)/2|
30: x/0.32-0.78125 31: 2*x-0.84     32: 4x;1;-2x+1.84;x/0.08-11.5
33: |2*x - 0.5|    34: 2*x          35: 2*x - 0.5
36: 2*x - 1

Отрицательные числа означают отрицательные цветовые компоненты.

palette = gray и palette = color являются сокращениями для palette = [3,3,3] и palette = [7,5,15] соответственно.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Примеры:

(%i1) load("draw")$
(%i2) im: apply(
           'matrix,
            makelist(makelist(random(200),i,1,30),i,1,30))$
(%i3) /* palette = color, default */
      draw2d(image(im,0,0,30,30))$
(%i4) draw2d(palette = gray, image(im,0,0,30,30))$
(%i5) draw2d(palette = [15,20,-4],
             colorbox=false,
             image(im,0,0,30,30))$

См. colorbox.

Графическая опция: colorbox

Значение по умолчанию: true

Если colorbox равно true, то палитра цветов изображается вместе с объектами изображения image.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) im: apply('matrix,
                 makelist(makelist(random(200),i,1,30),i,1,30))$
(%i3) draw2d(image(im,0,0,30,30))$
(%i4) draw2d(colorbox=false, image(im,0,0,30,30))$

См. palette.

Графическая опция: enhanced3d

Значение по умолчанию: false

Если enhanced3d равно true, то поверхности в трехмерных графиках окрашиваются, другими словами, включается Gnuplot мода pm3d.

См. palette для того, чтобы узнать как задается палитра.

Пример:

(%i1) load("draw")$
(%i2) draw3d(surface_hide = true,
             enhanced3d   = true,
             palette      = gray,
             explicit(20*exp(-x^2-y^2)-10,x,-3,3,y,-3,3))$
Графическая опция: point_size

Значение по умолчанию: 1

point_size – устанавливает размер изображаемых точек. Значение должно быть неотрицательным числом.

Эта опция влияет на следующие графические объекты:

Пример:

(%i1) load("draw")$
(%i2) draw2d(points(makelist([random(20),random(50)],k,1,10)),
        point_size = 5,
        points(makelist(k,k,1,20),makelist(random(30),k,1,20)))$
Графическая опция: point_type

Значение по умолчанию: 1

point_type определяет то, как изображаются изолированные точки. Значение этой опции может быть целое число больше или равное -1, или имя стиля точки: $none (-1), dot (0), plus (1), multiply (2), asterisk (3), square (4), filled_square (5), circle (6), filled_circle (7), up_triangle (8), filled_up_triangle (9), down_triangle (10), filled_down_triangle (11), diamant (12) и filled_diamant (13).

Эта опция влияет на следующие графические объекты:

Пример:

(%i1) load("draw")$
(%i2) draw2d(xrange = [0,10],
             yrange = [0,10],
             point_size = 3,
             point_type = diamant,
             points([[1,1],[5,1],[9,1]]),
             point_type = filled_down_triangle,
             points([[1,2],[5,2],[9,2]]),
             point_type = asterisk,
             points([[1,3],[5,3],[9,3]]),
             point_type = filled_diamant,
             points([[1,4],[5,4],[9,4]]),
             point_type = 5,
             points([[1,5],[5,5],[9,5]]),
             point_type = 6,
             points([[1,6],[5,6],[9,6]]),
             point_type = filled_circle,
             points([[1,7],[5,7],[9,7]]),
             point_type = 8,
             points([[1,8],[5,8],[9,8]]),
             point_type = filled_diamant,
             points([[1,9],[5,9],[9,9]]) )$
Графическая опция: points_joined

Значение по умолчанию: false

Если points_joined равно true, то точки соединяются линиями.

Эта опция влияет на следующие графические объекты:

Пример:

(%i1) load("draw")$
(%i2) draw2d(xrange        = [0,10],
             yrange        = [0,4],
             point_size    = 3,
             point_type    = up_triangle,
             color         = blue,
             points([[1,1],[5,1],[9,1]]),
             points_joined = true,
             point_type    = square,
             line_type     = dots,
             points([[1,2],[5,2],[9,2]]),
             point_type    = circle,
             color         = red,
             line_width    = 7,
             points([[1,3],[5,3],[9,3]]) )$
Графическая опция: filled_func

Значение по умолчанию: false

Опция filled_func управляет то, как заполняются области, ограниченные функциями. Если filled_func равно true, то область, ограниченная функцией, определенной объектом explicit и низом графического окна, заполняется цветом fill_color. Если filled_func содержит функциональное выражение, то будет заполнена область, ограниченная этой функцией и функцией, определенной объектом explicit. По умолчанию явные функции не заполняются.

Эта опция влияет только на двумерные графические объекты explicit.

Пример:

Область, ограниченная объектом explicit и низом графического окна.

(%i1) load("draw")$
(%i2) draw2d(fill_color  = red,
             filled_func = true,
             explicit(sin(x),x,0,10) )$

Область, ограниченная объектом explicit и функцией, определенной в filled_func. Отметим, что переменная в filled_func должна быть той же, что и в explicit.

(%i1) load("draw")$
(%i2) draw2d(fill_color  = grey,
             filled_func = sin(x),
             explicit(-sin(x),x,0,%pi));

См. fill_color и explicit.

Графическая опция: transparent

Значение по умолчанию: false

Если transparent равно true, то внутренняя область многоугольников заполняется в соответствии с fill_color.

Эта опция влияет на следующие графические объекты:

Пример:

(%i1) load("draw")$
(%i2) draw2d(polygon([[3,2],[7,2],[5,5]]),
             transparent = true,
             color       = blue,
             polygon([[5,2],[9,2],[7,5]]) )$
Графическая опция: border

Значение по умолчанию: true

Если border равно true, то границы многоугольников изображаются в соответствии с опциями line_type и line_width.

Эта опция влияет на следующие графические объекты:

Пример:

(%i1) load("draw")$
(%i2) draw2d(color       = brown,
             line_width  = 8,
             polygon([[3,2],[7,2],[5,5]]),
             border      = false,
             fill_color  = blue,
             polygon([[5,2],[9,2],[7,5]]) )$
Графическая опция: head_both

Значение по умолчанию: false

Если head_both равно true, то векторы изображаются со окончаниями в форме двух стрелок. Если false, то изображается только одна стрелка.

Эта опция влияет только на объекты типа vector.

Пример:

(%i1) load("draw")$
(%i2) draw2d(xrange      = [0,8],
             yrange      = [0,8],
             head_length = 0.7,
             vector([1,1],[6,0]),
             head_both   = true,
             vector([1,7],[6,0]) )$

См. head_length, head_angle и head_type.

Графическая опция: head_length

Значение по умолчанию: 2

head_length задает длину наконечника стрелок в единицах оси x.

Эта опция влияет только на объекты типа vector.

Пример:

(%i1) load("draw")$
(%i2) draw2d(xrange      = [0,12],
             yrange      = [0,8],
             vector([0,1],[5,5]),
             head_length = 1,
             vector([2,1],[5,5]),
             head_length = 0.5,
             vector([4,1],[5,5]),
             head_length = 0.25,
             vector([6,1],[5,5]))$

См. head_both, head_angle и head_type.

Графическая опция: head_angle

Значение по умолчанию: 45

head_angle задает угол в градусах между стронами наконечника стрелки и ее осью.

Эта опция влияет только на объекты типа vector.

Пример:

(%i1) load("draw")$
(%i2) draw2d(xrange      = [0,10],
             yrange      = [0,9],
             head_length = 0.7,
             head_angle  = 10,
             vector([1,1],[0,6]),
             head_angle  = 20,
             vector([2,1],[0,6]),
             head_angle  = 30,
             vector([3,1],[0,6]),
             head_angle  = 40,
             vector([4,1],[0,6]),
             head_angle  = 60,
             vector([5,1],[0,6]),
             head_angle  = 90,
             vector([6,1],[0,6]),
             head_angle  = 120,
             vector([7,1],[0,6]),
             head_angle  = 160,
             vector([8,1],[0,6]),
             head_angle  = 180,
             vector([9,1],[0,6]) )$

См. head_both, head_length и head_type.

Графическая опция: head_type

Значение по умолчанию: filled

head_type задает способ изображения наконечника стрелок. Возможны значения: filled (замкнутые и заполненные наконечники), empty (замкнутые и пустые наконечники) и nofilled (открытые наконечники).

Эта опция влияет только на объекты типа vector.

Пример:

(%i1) load("draw")$
(%i2) draw2d(xrange      = [0,12],
             yrange      = [0,10],
             head_length = 1,
             vector([0,1],[5,5]), /* default type */
             head_type = 'empty,
             vector([3,1],[5,5]),
             head_type = 'nofilled,
             vector([6,1],[5,5]))$

См. head_both, head_angle и head_length.

Графическая опция: unit_vectors

Значение по умолчанию: false

Если unit_vectors равно true, все вектора изображаются с единичной длиной. Это полезно при изображении векторных полей. Если unit_vectors равно false, то вектора изображаются с их настоящей длиной.

Эта опция влияет только на объекты типа vector.

Пример:

(%i1) load("draw")$
(%i2) draw2d(xrange      = [-1,6],
             yrange      = [-1,6],
             head_length = 0.1,
             vector([0,0],[5,2]),
             unit_vectors = true,
             color        = red,
             vector([0,3],[5,2]))$
Графическая опция: label_alignment

Значение по умолчанию: center

label_alignment определяет положение меток, по отношению к заданным координатам. Возможны значения: center, left и right.

Эта опция влияет только на объекты типа label.

Пример:

(%i1) load("draw")$
(%i2) draw2d(xrange          = [0,10],
             yrange          = [0,10],
             points_joined   = true,
             points([[5,0],[5,10]]),
             color           = blue,
             label(["Centered alignment (default)",5,2]),
             label_alignment = 'left,
             label(["Left alignment",5,5]),
             label_alignment = 'right,
             label(["Right alignment",5,8]))$

См. label_orientation и color.

Графическая опция: label_orientation

Значение по умолчанию: horizontal

label_orientation определяет ориентацию меток. Возможны значения: horizontal и vertical.

Эта опция влияет только на объекты типа label.

Пример:

В этом примере к изображению добавлена фиктивная точка. Пакет draw требует непустые данные, чтобы изобразить сцену.

(%i1) load("draw")$
(%i2) draw2d(xrange     = [0,10],
             yrange     = [0,10],
             point_size = 0,
             points([[5,5]]),
             color      = navy,
             label(["Horizontal orientation (default)",5,2]),
             label_orientation = 'vertical,
             color             = "#654321",
             label(["Vertical orientation",1,5]))$

См. label_alignment и color.

Графическая опция: color

Значение по умолчанию: "black"

color задает цвет линий, точек, границ многоугольников и меток.

Цвет может быть задан как наименование или как шестнадцатиричный rgb код.

Доступны следующие наименования цветов: "white", "black", "gray0", "grey0", "gray10", "grey10", "gray20", "grey20", "gray30", "grey30", "gray40", "grey40", "gray50", "grey50", "gray60", "grey60", "gray70", "grey70", "gray80", "grey80", "gray90", "grey90", "gray100", "grey100", "gray", "grey", "light-gray", "light-grey", "dark-gray", "dark-grey", "red", "light-red", "dark-red", "yellow", "light-yellow", "dark-yellow", "green", "light-green", "dark-green", "spring-green", "forest-green", "sea-green", "blue", "light-blue", "dark-blue", "midnight-blue", "navy", "medium-blue", "royalblue", "skyblue", "cyan", "light-cyan", "dark-cyan", "magenta", "light-magenta", "dark-magenta", "turquoise", "light-turquoise", "dark-turquoise", "pink", "light-pink", "dark-pink", "coral", "light-coral", "orange-red", "salmon", "light-salmon", "dark-salmon", "aquamarine", "khaki", "dark-khaki", "goldenrod", "light-goldenrod", "dark-goldenrod", "gold", "beige", "brown", "orange", "dark-orange", "violet", "dark-violet", "plum" и "purple".

Цветовые компоненты в шестнадцатиричном коде представляются в форме "#rrggbb".

Пример:

(%i1) load("draw")$
(%i2) draw2d(explicit(x^2,x,-1,1), /* default is black */
             color = "red",
             explicit(0.5 + x^2,x,-1,1),
             color = blue,
             explicit(1 + x^2,x,-1,1),
             color = "light-blue", /* double quotes if - is used */
             explicit(1.5 + x^2,x,-1,1),
             color = "#23ab0f",
             label(["This is a label",0,1.2])  )$

См. fill_color.

Графическая опция: fill_color

Значение по умолчанию: "red"

fill_color определяет цвет для заполнения многоугольников и двумерных explicit функций.

См. color для способа задания цвета.

Графическая опция: fill_density

Значение по умолчанию: 0

fill_density – число от 0 до 1, которое задает интенсивность цвета fill_color в объектах bars.

См. bars для примеров.

Графическая опция: line_width

Значение по умолчанию: 1

line_width – ширина изображаемых линий. Значение должно быть положительным числом.

Эта опция влияет на следующие графические объекты:

Пример:

(%i1) load("draw")$
(%i2) draw2d(explicit(x^2,x,-1,1), /* default width */
             line_width = 5.5,
             explicit(1 + x^2,x,-1,1),
             line_width = 10,
             explicit(2 + x^2,x,-1,1))$

См. line_type.

Графическая опция: line_type

Значение по умолчанию: solid

line_type – задает стиль изображения линий. Возможные значения: solid и dots.

Эта опция влияет на следующие графические объекты:

Пример:

(%i1) load("draw")$
(%i2) draw2d(line_type = dots,
             explicit(1 + x^2,x,-1,1),
             line_type = solid, /* default */
             explicit(2 + x^2,x,-1,1))$

См. line_width.

Графическая опция: nticks

Значение по умолчанию: 30

nticks – число пробных точек, используемых в графических процедурах.

Эта опция влияет на следующие графические объекты:

Пример:

(%i1) load("draw")$
(%i2) draw2d(transparent = true,
             ellipse(0,0,4,2,0,180),
             nticks = 5,
             ellipse(0,0,4,2,180,180) )$
Графическая опция: adapt_depth

Значение по умолчанию: 10

adapt_depth – максимальное число разбиений, используемое в адаптивных графиках.

Эта опция влияет только на двумерные explicit функции.

Графическая опция: key

Значение по умолчанию: "" (пустая строка)

key – наименование функции в легенде. Если key – пустая строка, то ничего не изображается.

Эта опция влияет на следующие графические объекты:

Пример:

(%i1) load("draw")$
(%i2) draw2d(key   = "Sinus",
             explicit(sin(x),x,0,10),
             key   = "Cosinus",
             color = red,
             explicit(cos(x),x,0,10) )$
Графическая опция: xu_grid

Значение по умолчанию: 30

xu_grid – число координат первой переменной (x в явной и u в параметрической трехмерной поверхности) для построения сетки пробных точек.

Эта опция влияет на следующие графические объекты:

Пример:

(%i1) load("draw")$
(%i2) draw3d(xu_grid = 10,
             yv_grid = 50,
             explicit(x^2+y^2,x,-3,3,y,-3,3) )$

См. yv_grid.

Графическая опция: yv_grid

Значение по умолчанию: 30

yv_grid – число координат второй переменной (y в явной и v в параметрической трехмерной поверхности) для построения сетки пробных точек.

Эта опция влияет на следующие графические объекты:

Пример:

(%i1) load("draw")$
(%i2) draw3d(xu_grid = 10,
             yv_grid = 50,
             explicit(x^2+y^2,x,-3,3,y,-3,3) )$

См. xu_grid.

Графическая опция: surface_hide

Значение по умолчанию: false

Если surface_hide равно true, то скрытые части на трехмерных поверхностях не изображаются.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw(columns=2,
           gr3d(explicit(exp(sin(x)+cos(x^2)),x,-3,3,y,-3,3)),
           gr3d(surface_hide = true,
                explicit(exp(sin(x)+cos(x^2)),x,-3,3,y,-3,3)) )$
Графическая опция: contour

Значение по умолчанию: none

Опция contour позволяет пользователю выбрать, где изображать контурные линии. Доступны следующие значения:

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Пример:

(%i1) load("draw")$
(%i2) draw3d(explicit(20*exp(-x^2-y^2)-10,x,0,2,y,-3,3),
             contour_levels = 15,
             contour        = both,
             surface_hide   = true) $
Графическая опция: contour_levels

Значение по умолчанию: 5

Эта опция управляет способом изображения контуров. contour_levels может иметь значение в виде положительного целого числа, списка трех чисел или произвольного набора чисел:

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения.

Примеры:

Контурные линии, расположенные на равном расстоянии. Число уровней можно настраивать.

(%i1) load("draw")$
(%i2) draw3d(color = green,
             explicit(20*exp(-x^2-y^2)-10,x,0,2,y,-3,3),
             contour_levels = 10,
             contour        = both,
             surface_hide   = true) $

Контурные линии от -8 до 8 с шагом 4.

(%i1) load("draw")$
(%i2) draw3d(color = green,
             explicit(20*exp(-x^2-y^2)-10,x,0,2,y,-3,3),
             contour_levels = [-8,4,8],
             contour        = both,
             surface_hide   = true) $

Контурные линии на уровне -7, -6, 0.8 и 5.

(%i1) load("draw")$
(%i2) draw3d(color = green,
             explicit(20*exp(-x^2-y^2)-10,x,0,2,y,-3,3),
             contour_levels = {-7, -6, 0.8, 5},
             contour        = both,
             surface_hide   = true) $

См. contour.

Графическая опция: columns

Значение по умолчанию: 1

columns число колонок в множественных графиках.

Поскольку это глобальная графическая опция, ее расположение в описании сцены не имеет значения. Она также может использоваться как аргумент функции draw.

Пример:

(%i1) load("draw")$
(%i2) scene1: gr2d(title="Ellipse",
                   nticks=30,
                   parametric(2*cos(t),5*sin(t),t,0,2*%pi))$
(%i3) scene2: gr2d(title="Triangle",
                   polygon([4,5,7],[6,4,2]))$
(%i4) draw(scene1, scene2, columns = 2)$
Графическая опция: ip_grid

Значение по умолчанию: [50, 50]

ip_grid задает решетку для первой пробной выборки для неявных графиков.

Эта опция влияет только на объекты типа implicit.

Графическая опция: ip_grid_in

Значение по умолчанию: [5, 5]

ip_grid_in задает решетку для второй пробной выборки для неявных графиков.

Эта опция влияет только на объекты типа implicit.

Графическая опция: x_voxel

Значение по умолчанию: 10

x_voxel есть число вокселей в направлении x, используемых в алгоритме марширующих кубов, реализованном лоя трехмерных implicit объектов.

Графическая опция: y_voxel

Значение по умолчанию: 10

y_voxel есть число вокселей в направлении y, используемых в алгоритме марширующих кубов, реализованном лоя трехмерных implicit объектов.

Графическая опция: z_voxel

Значение по умолчанию: 10

z_voxel есть число вокселей в направлении z, используемых в алгоритме марширующих кубов, реализованном лоя трехмерных implicit объектов.

Конструктор сцены: gr2d (графическая опция, ..., графический объект, ...)

Функция gr2d строит объект, который описывает двумерную сцену. Аргументы есть графические опции и графические объекты. Эта сцена интерпретируется последовательно: графические опции влияет на графические объекты, расположенные справа от них. Некоторые графические опции глобально влияют на вид сцены.

Это список графических объектов, доступных для сцены в двух измерениях: points, polygon, rectangle, bars, ellipse, label, vector, explicit, implicit, polar, parametric, image и geomap.

См. следующие глобальные графические опции: xrange, yrange, logx, logy, terminal, grid, title, xlabel, ylabel, xtics, ytics, xtics_rotate, ytics_rotate, xtics_axis, ytics_axis, xaxis, yaxis, xaxis_width, yaxis_width, xaxis_type, yaxis_type, xaxis_color, yaxis_color, xy_file, file_name, pic_width, pic_height, eps_width, eps_height, user_preamble, axis_bottom, axis_left, axis_top и axis_right.

Для того, чтобы использовать эту функцию, ее следует загрузить командой load("draw").

Конструктор сцены: gr3d (графическая опция, ..., графический объект, ...)

Функция gr3d строит объект, который описывает трехмерную сцену. Аргументы есть графические опции и графические объекты. Эта сцена интерпретируется последовательно: графические опции влияет на графические объекты, неположенные справа от них. Некоторые графические опции глобально влияют на вид сцены.

Это список графических объектов, доступных для сцены в трех измерениях: points, label, vector, explicit, implicit, parametric, parametric_surface и geomap.

См. следующие графические опции: xrange, yrange, zrange, logx, logy, logz, terminal, grid, title, xlabel, ylabel, zlabel, xtics, ytics, ztics, xtics_rotate, ytics_rotate, ztics_rotate, xtics_axis, ytics_axis, ztics_axis, xaxis, yaxis, zaxis, xaxis_width, yaxis_width, zaxis_width, xaxis_type, yaxis_type, zaxis_type, xaxis_color, yaxis_color, zaxis_color, xy_file, user_preamble, axis_bottom, axis_left, axis_top, file_name, pic_width, pic_height, eps_width, eps_height, axis_right, rot_vertical, rot_horizontal, axis_3d, xu_grid, yv_grid, surface_hide, contour, contour_levels, palette, colorbox и enhanced3d.

Для того, чтобы использовать эту функцию, ее следует загрузить командой load("draw").

Графический объект: points ([[x1,y1], [x2,y2],...])
Графический объект: points ([x1,x2,...], [y1,y2,...])
Графический объект: points ([y1,y2,...])
Графический объект: points ([[x1,y1,z1], [x2,y2,z2],...])
Графический объект: points ([x1,x2,...], [y1,y2,...], [z1,z2,...])
Графический объект: points (matrix)

Строит точки в двух и трех измерениях.

Следующие графические опции влияют на этот объект: point_size, point_type, points_joined, line_width, key, line_type и color.

Два измерения

points ([[x1,y1], [x2,y2],...]) или points ([x1,x2,...], [y1,y2,...]) строит точки с координатами [x1,y1], [x2,y2], и т.д. Если абсциссы не заданы, то они принимаются равными последовательным положительным числам, так что points ([y1,y2,...]) строит точки [1,y1], [2,y2], и т.д. Если matrix – матрица из двух строк или столбцов, то points (matrix) строит соответствующие точки. Если matrix – матрица из одной строки или одного столбца, то абсциссы выбираются автоматически.

Пример:

(%i1) load("draw")$
(%i2) draw2d(
        key = "Small points",
        points(makelist([random(20),random(50)],k,1,10)),
        point_type    = circle,
        point_size    = 3,
        points_joined = true,
        key           = "Great points",
        points(makelist(k,k,1,20),makelist(random(30),k,1,20)),
        point_type    = filled_down_triangle,
        key           = "Automatic abscissas",
        color         = red,
        points([2,12,8]))$

Три измерения

points ([[x1,y1,z1], [x2,y2,z2],...]) или points ([x1,x2,...], [y1,y2,...], [z1,z2,...]) строит точки с координатами [x1,y1,z1], [x2,y2,z2], и т.д. Если matrix – матрица из трех строк или трех столбцов, то points (matrix) строит соответствующие точки.

Примеры:

Одна трехмерная выборка:

(%i1) load("draw")$
(%i2) load ("numericalio")$
(%i3) s2 : read_matrix (file_search ("wind.data"))$
(%i4) draw3d(title = "Daily average wind speeds",
             point_size = 2,
             points(args(submatrix (s2, 4, 5))) )$

Две трехмерные выборки:

(%i1) load("draw")$
(%i2) load ("numericalio")$
(%i3) s2 : read_matrix (file_search ("wind.data"))$
(%i4) draw3d(
         title = "Daily average wind speeds. Two data sets",
         point_size = 2,
         key        = "Sample from stations 1, 2 and 3",
         points(args(submatrix (s2, 4, 5))),
         point_type = 4,
         key        = "Sample from stations 1, 4 and 5",
         points(args(submatrix (s2, 2, 3))) )$
Графический объект: polygon ([[x1,y1], [x2,y2],...])
Графический объект: polygon ([x1,x2,...], [y1,y2,...])

Строит многоугольник в двух измерениях.

Два измерения

polygon ([[x1,y1], [x2,y2],...]) или polygon ([x1,x2,...], [y1,y2,...]): строит на плоскости многоугольник с вершинами [x1,y1], [x2,y2], и т.д.

Следующие графические опции влияют на этот объект: transparent, fill_color, border, line_width, key, line_type и color.

Пример:

(%i1) load("draw")$
(%i2) draw2d(color      = "#e245f0",
             line_width = 8,
             polygon([[3,2],[7,2],[5,5]]),
             border      = false,
             fill_color  = yellow,
             polygon([[5,2],[9,2],[7,5]]) )$
Графический объект: rectangle ([x1,y1], [x2,y2])

Строит прямоугольники в двух измерениях.

Два измерения

rectangle ([x1,y1], [x2,y2]) строит прямоугольник с противоположными вершинами [x1,y1] и [x2,y2].

Следующие графические опции влияют на этот объект: transparent, fill_color, border, line_width, key, line_type и color.

Пример:

(%i1) load("draw")$
(%i2) draw2d(fill_color  = red,
             line_width  = 6,
             line_type   = dots,
             transparent = false,
             fill_color  = blue,
             rectangle([-2,-2],[8,-1]), /* opposite vertices */
             transparent = true,
             line_type   = solid,
             line_width  = 1,
             rectangle([9,4],[2,-1.5]),
             xrange      = [-3,10],
             yrange      = [-3,4.5] )$
Графический объект: bars ([x1,h1,w1], [x2,h2,w2, ...])

Строит вертикальные полоски в двух измерениях.

Два измерения

bars ([x1,h1,w1], [x2,h2,w2, ...]) Строит полоски с центрами на x1, x2, ... с высотами h1, h2, ... и ширинами w1, w2, ...

Следующие графические опции влияют на этот объект: key, fill_color, fill_density и line_width.

Пример:

(%i1) load("draw")$
(%i2) draw2d(
       key          = "Group A",
       fill_color   = blue,
       fill_density = 0.2,
       bars([0.8,5,0.4],[1.8,7,0.4],[2.8,-4,0.4]),
       key          = "Group B",
       fill_color   = red,
       fill_density = 0.6,
       line_width   = 4,
       bars([1.2,4,0.4],[2.2,-2,0.4],[3.2,5,0.4]),
       xaxis = true);
Графический объект: ellipse (xc, yc, a, b, ang1, ang2)

Строит эллипсы и круги в двух измерениях.

Два измерения

ellipse (xc, yc, a, b, ang1, ang2) строит эллипс с центром в [xc, yc] с горизонтальной и вертикальной полу-осями a и b соответственно от угла ang1 до угла ang2.

Следующие графические опции влияют на этот объект: nticks, transparent, fill_color, border, line_width, line_type, key и color.

Пример:

(%i1) load("draw")$
(%i2) draw2d(transparent = false,
             fill_color  = red,
             color       = gray30,
             transparent = false,
             line_width  = 5,
             ellipse(0,6,3,2,270,-270),
             /* center (x,y), a, b, start & end in degrees */
             transparent = true,
             color       = blue,
             line_width  = 3,
             ellipse(2.5,6,2,3,30,-90),
             xrange      = [-3,6],
             yrange      = [2,9] )$
Графический объект: label ([string,x,y],...)
Графический объект: label ([string,x,y,z],...)

Изображает текстовую метку в двух или трех измерениях.

Следующие графические опции влияют на этот объект: label_alignment, label_orientation и color.

Два измерения

label([string,x,y]) изображает текст string в точке [x,y].

Пример:

(%i1) load("draw")$
(%i2) draw2d(yrange = [0.1,1.4],
             color = "red",
             label(["Label in red",0,0.3]),
             color = "#0000ff",
             label(["Label in blue",0,0.6]),
             color = "light-blue",
             label(["Label in light-blue",0,0.9],
                   ["Another ligght-blue",0,1.2])  )$

Три измерения

label([string,x,y,z]) изображает текст string в точке [x,y,z].

Пример:

(%i1) load("draw")$
(%i2) draw3d(explicit(exp(sin(x)+cos(x^2)),x,-3,3,y,-3,3),
             color = red,
             label(["UP 1",-2,0,3], ["UP 2",1.5,0,4]),
             color = blue,
             label(["DOWN 1",2,0,-3]) )$
Графический объект: vector ([x,y], [dx,dy])
Графический объект: vector ([x,y,z], [dx,dy,dz])

Строит вектор в двух или трех измерениях.

Следующие графические опции влияют на этот объект: head_both, head_length, head_angle, head_type, line_width, line_type, key и color.

Два измерения

vector([x,y], [dx,dy]) строит вектор [dx,dy] с началом в точке [x,y].

Пример:

(%i1) load("draw")$
(%i2) draw2d(xrange      = [0,12],
             yrange      = [0,10],
             head_length = 1,
             vector([0,1],[5,5]), /* default type */
             head_type = 'empty,
             vector([3,1],[5,5]),
             head_both = true,
             head_type = 'nofilled,
             line_type = dots,
             vector([6,1],[5,5]))$

Три измерения

vector([x,y,z], [dx,dy,dz]) строит вектор [dx,dy,dz] с началом в точке [x,y,z].

Пример:

(%i1) load("draw")$
(%i2) draw3d(color = cyan,
             vector([0,0,0],[1,1,1]/sqrt(3)),
             vector([0,0,0],[1,-1,0]/sqrt(2)),
             vector([0,0,0],[1,1,-2]/sqrt(6)) )$
Графический объект: explicit (fcn,var,minval,maxval)
Графический объект: explicit (fcn,var1,minval1,maxval1,var2,minval2,maxval2)

Строит явную функцию в двух или трех измерениях.

Два измерения

explicit(fcn,var,minval,maxval) строит явную функцию fcn переменной var, принимающей значения от minval до maxval.

Следующие графические опции влияют на этот объект: nticks, adapt_depth, line_width, line_type, key, filled_func, fill_color и color.

Пример:

(%i1) load("draw")$
(%i2) draw2d(line_width = 3,
             color      = blue,
             explicit(x^2,x,-3,3) )$
(%i3) draw2d(fill_color  = brown,
             filled_func = true,
             explicit(x^2,x,-3,3) )$

Три измерения

explicit(fcn,var1,minval1,maxval1,var2,minval2,maxval2) строит явную функцию fcn переменной var1 в пределах от minval1 до maxval1, и переменной var2 в пределах от minval2 до maxval2.

Следующие графические опции влияют на этот объект: xu_grid, yv_grid, line_type, key и color.

Пример:

(%i1) load("draw")$
(%i2) draw3d(key   = "Gauss",
             color = "#a02c00",
             explicit(20*exp(-x^2-y^2)-10,x,-3,3,y,-3,3),
             yv_grid     = 10,
             color = blue,
             key   = "Plane",
             explicit(x+y,x,-5,5,y,-5,5),
             surface_hide = true)$

См. filled_func по поводу функций с заполнением.

Графический объект: implicit (fcn,x,xmin,xmax,y,ymin,ymax)
Графический объект: implicit (fcn,x,xmin,xmax,y,ymin,ymax,z,zmin,zmax)

Строит неявную функцию в двух и трех измерениях.

Два измерения

implicit(fcn,x,xmin,xmax,y,ymin,ymax) строит неявную функцию, определенную fcn с переменной x, принимающей значения от xmin до xmax, и переменной y, принимающей значения от ymin до ymax.

Следующие графические опции влияют на этот объект: ip_grid, ip_grid_in, line_width, line_type, key и color.

Пример:

(%i1) load("draw")$
(%i2) draw2d(terminal  = eps,
             grid      = true,
             line_type = solid,
             key       = "y^2=x^3-2*x+1",
             implicit(y^2=x^3-2*x+1, x, -4,4, y, -4,4),
             line_type = dots,
             key       = "x^3+y^3 = 3*x*y^2-x-1",
             implicit(x^3+y^3 = 3*x*y^2-x-1, x,-4,4, y,-4,4),
             title     = "Two implicit functions" )$

Три измерения

implicit (fcn,x,xmin,xmax, y,ymin,ymax, z,zmin,zmax) строит неявную поверхность, определенную fcn, с переменной x, принимающей значения от xmin до xmax, переменной y, принимающей значения от ymin до ymax и переменной z, принимающей значения от zmin до zmax. Для построения используется алгоритм марширующих кубов.

Следующие графические опции влияют на этот объект: x_voxel, y_voxel, z_voxel, line_width, line_type, key и color.

Пример:

(%i1) load("draw")$
(%i2) draw3d(
        color=blue,
        implicit((x^2+y^2+z^2-1)*(x^2+(y-1.5)^2+z^2-0.5)=0.015,
                 x,-1,1,y,-1.2,2.3,z,-1,1),
        surface_hide=true);
Графический объект: polar (radius,ang,minang,maxang)

Строит двумерную функцию в полярных координатах.

Два измерения

polar (radius,ang,minang,maxang) изображает функцию radius(ang) в полярных координатах переменной ang в пределах от minang до maxang.

Следующие графические опции влияют на этот объект: nticks, line_width, line_type, key и color.

Пример:

(%i1) load("draw")$
(%i2) draw2d(user_preamble = "set grid polar",
             nticks        = 200,
             xrange        = [-5,5],
             yrange        = [-5,5],
             color         = blue,
             line_width    = 3,
             title         = "Hyperbolic Spiral",
             polar(10/theta,theta,1,10*%pi) )$
Графический объект: spherical (radius,azi,minazi,maxazi,zen,minzen,maxzen)

Строит трехмерную функцию в сферических координатах.

Три измерения

spherical (radius,azi,minazi,maxazi,zen,minzen,maxzen) строит функцию radius(azi,zen) в сферических координатах с азимутом azi в пределах от minazi до maxazi и возвышением zen в пределах от minzen до maxzen.

Следующие графические опции влияют на этот объект: xu_grid, yv_grid, line_type, key и color.

Пример:

(%i1) load("draw")$
(%i2) draw3d(spherical(1,a,0,2*%pi,z,0,%pi))$
Графический объект: cylindrical (radius,z,minz,maxz,azi,minazi,maxazi)

Строит трехмерную функцию в цилиндрических координатах.

Три измерения

cylindrical (radius,z,minz,maxz,azi,minazi,maxazi) строит функцию radius(z,azi) в цилиндрических координатах с z в пределах от minz до maxz и азимутом azi в пределах от minazi до maxazi.

Следующие графические опции влияют на этот объект: xu_grid, yv_grid, line_type, key и color.

Пример:

(%i1) load("draw")$
(%i2) draw3d(cylindrical(1,z,-2,2,az,0,2*%pi))$
Графический объект: parametric (xfun,yfun,par,parmin,parmax)
Графический объект: parametric (xfun,yfun,zfun,par,parmin,parmax)

Строит параметрическую функцию в двух и трех переменных.

Следующие графические опции влияют на этот объект: nticks, line_width, line_type, key и color.

Два измерения

parametric (xfun,yfun,par,parmin,parmax) строит параметрическую функцию [xfun,yfun] с параметром par, принимающим значения от parmin до parmax.

Пример:

(%i1) load("draw")$
(%i2) draw2d(explicit(exp(x),x,-1,3),
             color = red,
             key   = "This is the parametric one!!",
             parametric(2*cos(rrr),rrr^2,rrr,0,2*%pi))$

Три измерения

parametric (xfun,yfun,zfun,par,parmin,parmax) строит параметрическую кривую [xfun,yfun,zfun] с параметром par, принимающем значения от parmin до parmax.

Пример:

(%i1) load("draw")$
(%i2) draw3d(explicit(exp(sin(x)+cos(x^2)),x,-3,3,y,-3,3),
             color = royalblue,
             parametric(cos(5*u)^2,sin(7*u),u-2,u,0,2),
             color      = turquoise,
             line_width = 2,
             parametric(t^2,sin(t),2+t,t,0,2),
             surface_hide = true,
             title = "Surface & curves" )$
Графический объект: image (im,x0,y0,width,height)

Строит в двух измерениях.

Два измерения

image (im,x0,y0,width,height) строит изображение im в прямоугольной области от угла (x0,y0) до (x0+width,y0+height) на вещественной плоскости. Параметр im должен быть матрицей вещественных чисел, или матрицей векторов длины 3, или объект типа картина.

Если im – матрица вещественных чисел или объект картина уровней, то значения пикселов интерпретируются в соответствии с графической опцией palette, которая является вектором длины 3 с компонентами, принимающими значение от -36 до +36. Каждое значение является индексом формулы, преобразующей значение уровня в красный, зеленый и синий цвета соответственно:

 0: 0               1: 0.5           2: 1
 3: x               4: x^2           5: x^3
 6: x^4             7: sqrt(x)       8: sqrt(sqrt(x))
 9: sin(90x)       10: cos(90x)     11: |x-0.5|
12: (2x-1)^2       13: sin(180x)    14: |cos(180x)|
15: sin(360x)      16: cos(360x)    17: |sin(360x)|
18: |cos(360x)|    19: |sin(720x)|  20: |cos(720x)|
21: 3x             22: 3x-1         23: 3x-2
24: |3x-1|         25: |3x-2|       26: (3x-1)/2
27: (3x-2)/2       28: |(3x-1)/2|   29: |(3x-2)/2|
30: x/0.32-0.78125                  31: 2*x-0.84
32: 4x;1;-2x+1.84;x/0.08-11.5
33: |2*x - 0.5|    34: 2*x          35: 2*x - 0.5
36: 2*x - 1

Отрицательные числа означают отрицательные цветовые компоненты.

palette = gray и palette = color являются сокращениями для palette = [3,3,3] и palette = [7,5,15] соответственно.

Если im – матрица векторов длины 3 или объект rgb-картина, то они интерпретируются как красный, зеленый и синий цвета.

Примеры:

Если im – матрица вещественных чисел или объект картина уровней, то значения пикселов интерпретируются в соответствии с графической опцией palette.

(%i1) load("draw")$
(%i2) im: apply(
           'matrix,
            makelist(makelist(random(200),i,1,30),i,1,30))$
(%i3) /* palette = color, default */
      draw2d(image(im,0,0,30,30))$
(%i4) draw2d(palette = gray, image(im,0,0,30,30))$
(%i5) draw2d(palette = [15,20,-4],
             colorbox=false,
             image(im,0,0,30,30))$

См. colorbox.

Если im – матрица векторов длины 3 или объект rgb-картина, то они интерпретируются как красный, зеленый и синий цвета.

(%i1) load("draw")$
(%i2) im: apply(
            'matrix,
             makelist(
               makelist([random(300),
                         random(300),
                         random(300)],i,1,30),i,1,30))$
(%i3) draw2d(image(im,0,0,30,30))$

Пакет draw автоматически загружает пакет picture. В данном примере, объект типа картина уровней строится вручную и потом изображается.

(%i1) load("draw")$
(%i2) im: make_level_picture([45,87,2,134,204,16],3,2);
(%o2)       picture(level, 3, 2, {Array:  #(45 87 2 134 204 16)})
(%i3) /* default color palette */
      draw2d(image(im,0,0,30,30))$
(%i4) /* gray palette */
      draw2d(palette = gray,
             image(im,0,0,30,30))$

Файл xpm читается и изображается.

(%i1) load("draw")$
(%i2) im: read_xpm("myfile.xpm")$
(%i3) draw2d(image(im,0,0,10,7))$

См. make_level_picture, make_rgb_picture и read_xpm.

По ссылке URL http://www.telefonica.net/web2/biomates/maxima/gpdraw/image находятся более развернутые примеры.

Глобальная переменная: boundaries_array

Значение по умолчанию: false

boundaries_array – это массив, в котором графический объект geomap ищет координаты границ.

Каждая компонента boundaries_array есть массив чисел с плавающей точкой – координат многоугольного сегмента или границы карты.

См. geomap.

Графический объект: geomap (numlist)
Графический объект: geomap (numlist,3Dprojection)

Строит карты в двух и трех измерениях.

Два измерения

Эта функция работает вместе с глобальной переменной boundaries_array.

Аргумент numlist – список, содержащий числа или списки чисел. Все числа должны быть неотрицательными целыми, которые представляют компоненты глобального массива boundaries_array.

Каждая компонента boundaries_array есть массив чисел с плавающей точкой – координат многоугольного сегмента или границы карты.

Функция geomap (numlist) проецирует свои аргументы на плоскость и строит соответствующую границу из boundaries_array.

Следующие графические опции влияют на этот объект: line_width, line_type и color.

Примеры:

Простая карта, определенная вручную:

(%i1) load("draw")$
(%i2) /* Vertices of boundary #0: {(1,1),(2,5),(4,3)} */
   ( bnd0: make_array(flonum,6),
     bnd0[0]:1.0, bnd0[1]:1.0, bnd0[2]:2.0,
     bnd0[3]:5.0, bnd0[4]:4.0, bnd0[5]:3.0 )$
(%i3) /* Vertices of boundary #1: {(4,3),(5,4),(6,4),(5,1)} */
   ( bnd1: make_array(flonum,8),
     bnd1[0]:4.0, bnd1[1]:3.0, bnd1[2]:5.0, bnd1[3]:4.0,
     bnd1[4]:6.0, bnd1[5]:4.0, bnd1[6]:5.0, bnd1[7]:1.0)$
(%i4) /* Vertices of boundary #2: {(5,1), (3,0), (1,1)} */
   ( bnd2: make_array(flonum,6),
     bnd2[0]:5.0, bnd2[1]:1.0, bnd2[2]:3.0,
     bnd2[3]:0.0, bnd2[4]:1.0, bnd2[5]:1.0 )$
(%i5) /* Vertices of boundary #3: {(1,1), (4,3)} */
   ( bnd3: make_array(flonum,4),
     bnd3[0]:1.0, bnd3[1]:1.0, bnd3[2]:4.0, bnd3[3]:3.0)$
(%i6) /* Vertices of boundary #4: {(4,3), (5,1)} */
   ( bnd4: make_array(flonum,4),
     bnd4[0]:4.0, bnd4[1]:3.0, bnd4[2]:5.0, bnd4[3]:1.0)$
(%i7) /* Pack all together in boundaries_array */
   ( boundaries_array: make_array(any,5),
     boundaries_array[0]: bnd0, boundaries_array[1]: bnd1,
     boundaries_array[2]: bnd2, boundaries_array[3]: bnd3,
     boundaries_array[4]: bnd4 )$
(%i8) draw2d(geomap([0,1,2,3,4]))$

Вспомогательный пакет worldmap заносит в boundaries_array реальные границы (долгота, широта). Эти данные публично доступны и получены из http://www-cger.nies.go.jp/grid-e/gridtxt/grid19.html. Пакет worldmap также определяет границы стран, континентов и береговых линий в форме списков с необходимыми компонентами boundaries_array (см. файл share/draw/worldmap.mac для дальнейшей информации). Пакет draw не загружает автоматически пакет worldmap.

(%i1) load("draw")$
(%i2) load("worldmap")$
(%i3) c1: gr2d(geomap(Canada,United_States,
                      Mexico,Cuba))$
(%i4) c2: gr2d(geomap(Africa))$
(%i5) c3: gr2d(geomap(Oceania,China,Japan))$
(%i6) c4: gr2d(geomap(France,Portugal,Spain,
                      Morocco,Western_Sahara))$
(%i7) draw(columns  = 2,
           c1,c2,c3,c4)$

Пакет worldmap также полезен для изображения стран в виде многоугольников. В этом случае графический объект geomap не нужен и вместо его используется объект polygon. Т.к. в этом случае используются списки а не массивы, то изображение карт будет мудреннее. См. make_poly_country и make_poly_continent, чтобы понять следующий код.

(%i1) load("draw")$
(%i2) load("worldmap")$
(%i3) mymap: append(
   [color      = white],  /* borders are white */
   [fill_color = red],             make_poly_country(Bolivia),
   [fill_color = cyan],            make_poly_country(Paraguay),
   [fill_color = green],           make_poly_country(Colombia),
   [fill_color = blue],            make_poly_country(Chile),
   [fill_color = "#23ab0f"],       make_poly_country(Brazil),
   [fill_color = goldenrod],       make_poly_country(Argentina),
   [fill_color = "midnight-blue"], make_poly_country(Uruguay))$
(%i4) apply(draw2d, mymap)$

Три измерения

geomap (numlist) проецирует границы карты на сферу единичного радиуса с центром (0,0,0). Сферу и тип проекции можно изменить при помощи geomap (numlist,3Dprojection).

Доступны следующие трехмерные проекции:

См. http://www.telefonica.net/web2/biomates/maxima/gpdraw/geomap для более сложных примеров.

Графический объект: parametric_surface (xfun,yfun,zfun,par1,par1min,par1max,par2,par2min,par2max)

Строит параметрическую поверхность в трех измерениях.

Три измерения

parametric_surface (xfun,yfun,zfun,par1,par1min,par1max,par2,par2min,par2max) строит параметрическую поверхность [xfun,yfun,zfun], с параметром par1, принимающем значения от par1min до par1max и параметром par2, принимающем значения от par2min до par2max.

Следующие графические опции влияют на этот объект: xu_grid, yv_grid, line_type, key и color.

Пример:

(%i1) load("draw")$
(%i2) draw3d(title          = "Sea shell",
             xu_grid        = 100,
             yv_grid        = 25,
             rot_vertical   = 100,
             rot_horizontal = 20,
             surface_hide   = true,
             parametric_surface(0.5*u*cos(u)*(cos(v)+1),
                           0.5*u*sin(u)*(cos(v)+1),
                           u*sin(v) - ((u+3)/8*%pi)^2 - 20,
                           u, 0, 13*%pi, v, -%pi, %pi) )$
Функция: draw (gr2d, ..., gr3d, ..., options, ...)

Изображает серию графических сцен. Ее аргументы есть gr2d и/или gr3d графические объекты вместе с некоторыми опциями. По умолчанию сцены собираются вместе в одну колонку.

Функция draw принимает следующие глобальные опции: terminal, columns, pic_width, pic_height, eps_width, eps_height, file_name и delay.

Функции draw2d и draw3d – сокращения, которые используются, когда требуется изобразить только одну сцену в двух или трех измерениях соответственно.

Для того, чтобы использовать эту функцию, ее следует загрузить командой load("draw").

Пример:

(%i1) load("draw")$
(%i2) scene1: gr2d(title="Ellipse",
                   nticks=30,
                   parametric(2*cos(t),5*sin(t),t,0,2*%pi))$
(%i3) scene2: gr2d(title="Triangle",
                   polygon([4,5,7],[6,4,2]))$
(%i4) draw(scene1, scene2, columns = 2)$

Эти две команды эквивалентны:

(%i1) load("draw")$
(%i2) draw(gr3d(explicit(x^2+y^2,x,-1,1,y,-1,1)));
(%o2)                          [gr3d(explicit)]
(%i3) draw3d(explicit(x^2+y^2,x,-1,1,y,-1,1));
(%o3)                          [gr3d(explicit)]

Анимированный файл gif:

(%i1) load("draw")$
(%i2) draw(
        delay     = 100,
        file_name = "zzz",
        terminal  = 'animated_gif,
        gr2d(explicit(x^2,x,-1,1)),
        gr2d(explicit(x^3,x,-1,1)),
        gr2d(explicit(x^4,x,-1,1)));
End of animation sequence
(%o2)          [gr2d(explicit), gr2d(explicit), gr2d(explicit)]

См. gr2d, gr3d, draw2d и draw3d.

Функция: draw2d (option, graphic_object, ...)

Эта функция является сокращением для draw(gr2d(options, ..., graphic_object, ...)).

Она может использоваться для изображения одиночной двумерной сцены.

Для того, чтобы использовать эту функцию, ее следует загрузить командой load("draw").

См. также draw и gr2d.

Функция: draw3d (option, graphic_object, ...)

Эта функция является сокращением для draw(gr3d(options, ..., graphic_object, ...)).

Она может использоваться для изображения одиночной трехмерной сцены.

Для того, чтобы использовать эту функцию, ее следует загрузить командой load("draw").

См. также draw и gr3d.


Next: , Previous: Функции и переменные пакета draw, Up: Пакет draw   [Contents][Index]

46.3 Функции и переменные для картин

Функция: make_level_picture (data)
Функция: make_level_picture (data,width,height)

Возвращает объект типа картина уровней. make_level_picture (data) строит объект картина из матрицы data. make_level_picture (data,width,height) строит объект из списка чисел; в этом случае должны быть заданы оба параметра width и height.

Возвращает объект типа картина, содержащий следующие четыре части:

  1. символ level
  2. ширина картины
  3. высота картины
  4. массив целых чисел в пределах от 0 до 255, описывающих пикселы. Аргумент data должен содержать только числа в пределах от 0 до 255; отрицательные числа заменяются 0, а те, что превышают 255, заменяются на 255.

Пример:

Картина уровней из матрицы.

(%i1) load("draw")$
(%i2) make_level_picture(matrix([3,2,5],[7,-9,3000]));
(%o2)         picture(level, 3, 2, {Array:  #(3 2 5 7 0 255)})

Картина уровней из числового списка.

(%i1) load("draw")$
(%i2) make_level_picture([-2,0,54,%pi],2,2);
(%o2)            picture(level, 2, 2, {Array:  #(0 0 54 3)})
Функция: picturep (x)

Возвращает true, если аргумент является правильно сформированной картиной, и false в противном случае.

Функция: picture_equalp (x,y)

Возвращает true, если картины совпадают, и false в противном случае.

Функция: make_rgb_picture (redlevel,greenlevel,bluelevel)

Возвращает rgb-цветную картину. Все три аргумента должны быть картинами уровней, с уровнями, задающими красный, зеленый и синий цвета соответственно.

Возвращаемый объект картина содержит следующие четыре части:

  1. символ rgb
  2. ширина картины
  3. высота картины
  4. целый массив длины 3*width*height с данными о пикселах со значениями от 0 до 255. Каждый пиксел представляется тремя последовательными числами (красный, зелены, синий).

Пример:

(%i1) load("draw")$
(%i2) red: make_level_picture(matrix([3,2],[7,260]));
(%o2)           picture(level, 2, 2, {Array:  #(3 2 7 255)})
(%i3) green: make_level_picture(matrix([54,23],[73,-9]));
(%o3)           picture(level, 2, 2, {Array:  #(54 23 73 0)})
(%i4) blue: make_level_picture(matrix([123,82],[45,32.5698]));
(%o4)          picture(level, 2, 2, {Array:  #(123 82 45 33)})
(%i5) make_rgb_picture(red,green,blue);
(%o5) picture(rgb, 2, 2, 
              {Array:  #(3 54 123 2 23 82 7 73 45 255 0 33)})
Функция: take_channel (im,color)

Если параметр color равен red, green или blue, то функция take_channel возвращает соответствующий цветовой канал картины im. Пример:

(%i1) load("draw")$
(%i2) red: make_level_picture(matrix([3,2],[7,260]));
(%o2)           picture(level, 2, 2, {Array:  #(3 2 7 255)})
(%i3) green: make_level_picture(matrix([54,23],[73,-9]));
(%o3)           picture(level, 2, 2, {Array:  #(54 23 73 0)})
(%i4) blue: make_level_picture(matrix([123,82],[45,32.5698]));
(%o4)          picture(level, 2, 2, {Array:  #(123 82 45 33)})
(%i5) make_rgb_picture(red,green,blue);
(%o5) picture(rgb, 2, 2, 
              {Array:  #(3 54 123 2 23 82 7 73 45 255 0 33)})
(%i6) take_channel(%,'green);  /* simple quote!!! */
(%o6)           picture(level, 2, 2, {Array:  #(54 23 73 0)})
Функция: negative_picture (pic)

Возвращает негатив картины (уровней или rgb).

Функция: rgb2level (pic)

Преобразует rgb картину в картину уровней усреднением красного, зеленого и синего каналов.

Функция: get_pixel (pic,x,y)

Возвращает пиксел из картины. Координаты x и y должны быть от 0 до width-1 и height-1 соответственно.

Функция: read_xpm (xpm_file)

Читает файл в формате xpm и возвращает объект типа картина.


Previous: Функции и переменные для картин, Up: Пакет draw   [Contents][Index]

46.4 Функции и переменные для карты мира

Функция: region_boundaries (x1,y1,x2,y2)

Определяет многоугольные сегменты из глобальной переменной boundaries_array, содержащиеся внутри прямоугольника с вершинами (x1,y1) (верхний левый) и (x2,y2) (нижний правый).

Пример:

Возвращает номера сегментов для северной Италии.

(%i1) load("draw")$
(%i2) load("worldmap")$
(%i3) region_boundaries(10.4,41.5,20.7,35.4);
(%o3)                [1846, 1863, 1864, 1881, 1888, 1894]
(%i4) draw2d(geomap(%))$
Функция: numbered_boundaries (nlist)

Строит многоугольные сегменты (границы), обозначаемые числами (координаты в boundaries_array). Эта функция очень полезна при создании географических объектов.

Пример:

Карта Европы, с границами, обозначенными номерами компонент в boundaries_array.

(%i1) load("draw")$
(%i2) load("worldmap")$
(%i3) european_borders: 
           region_boundaries(-31.81,74.92,49.84,32.06)$
(%i4) numbered_boundaries(european_borders)$
Функция: make_polygon (nlist)

Возвращает объект polygon, построенный из индексов границ. Аргумент nlist – список компонент в массиве boundaries_array.

Пример:

Бутан определяется номерами компонент 171, 173 и 1143, так что make_polygon([171,173,1143]) добавляет массив координат boundaries_array[171], boundaries_array[173] и boundaries_array[1143] и возвращает объект polygon, пригодный для изображения функцией draw. Для того чтобы избежать сообщений о ошибках, массивы должны быть совместимы в том смысле, что два последовательных массива имеют общие предельные координаты. В этом примере, две первые компоненты boundaries_array[171] равны двум последним компонентам boundaries_array[173], и две первые компоненты boundaries_array[173] равны двум первым компонентам boundaries_array[1143]. В целом, числа 171, 173 и 1143 (именно в этом порядке) совместимы и цветной многоугольник может быть построен.

(%i1) load("draw")$
(%i2) load("worldmap")$
(%i3) Bhutan;
(%o3)                        [[171, 173, 1143]]
(%i4) boundaries_array[171];
(%o4) {Array:  
       #(88.750549 27.14727 88.806351 27.25305 88.901367 27.282221
         88.917877 27.321039)}
(%i5) boundaries_array[173];
(%o5) {Array:
       #(91.659554 27.76511 91.6008 27.66666 91.598022 27.62499
         91.631348 27.536381 91.765533 27.45694 91.775253 27.4161 
         92.007751 27.471939 92.11441 27.28583 92.015259 27.168051
         92.015533 27.08083 92.083313 27.02277 92.112183 26.920271
         92.069977 26.86194 91.997192 26.85194 91.915253 26.893881
         91.916924 26.85416 91.8358 26.863331 91.712479 26.799999 
         91.542191 26.80444 91.492188 26.87472 91.418854 26.873329
         91.371353 26.800831 91.307457 26.778049 90.682457 26.77417
         90.392197 26.903601 90.344131 26.894159 90.143044 26.75333
         89.98996 26.73583 89.841919 26.70138 89.618301 26.72694 
         89.636093 26.771111 89.360786 26.859989 89.22081 26.81472
         89.110237 26.829161 88.921631 26.98777 88.873016 26.95499
         88.867737 27.080549 88.843307 27.108601 88.750549 
         27.14727)}
(%i6) boundaries_array[1143];
(%o6) {Array:  
       #(91.659554 27.76511 91.666924 27.88888 91.65831 27.94805 
         91.338028 28.05249 91.314972 28.096661 91.108856 27.971109
         91.015808 27.97777 90.896927 28.05055 90.382462 28.07972
         90.396088 28.23555 90.366074 28.257771 89.996353 28.32333
         89.83165 28.24888 89.58609 28.139999 89.35997 27.87166 
         89.225517 27.795 89.125793 27.56749 88.971077 27.47361
         88.917877 27.321039)}
(%i7) Bhutan_polygon: make_polygon([171,173,1143])$
(%i8) draw2d(Bhutan_polygon)$
Функция: make_poly_country (country_name)

Строит многоугольники, необходимые для изображения страны в цвете. Если есть острова, то страна определяется более чем одним многоугольником.

Пример:

(%i1) load("draw")$
(%i2) load("worldmap")$
(%i3) make_poly_country(India)$
(%i4) apply(draw2d, %)$
Функция: make_poly_continent (continent_name)
Функция: make_poly_continent (country_list)

Строит многоугольники, необходимые для изображение континента или списка стран в цвете.

Пример:

(%i1) load("draw")$
(%i2) load("worldmap")$
(%i3) /* A continent */
      make_poly_continent(Africa)$
(%i4) apply(draw2d, %)$
(%i5) /* A list of countries */
      make_poly_continent([Germany,Denmark,Poland])$
(%i6) apply(draw2d, %)$

Next: , Previous: Пакет draw, Up: Top   [Contents][Index]

47 Пакет dynamics


Next: , Previous: Пакет dynamics, Up: Пакет dynamics   [Contents][Index]

47.1 Введение в пакет dynamics

Пакет dynamics включает несколько функций, предназначенных для создания различных графических представлений дискретных динамических систем и фракталов, и реализацию метода Рунге-Кутта 4-го порядка для численного решения систем дифференциальных уравнений.

Для того, чтобы использовать функции данного пакета, его нужно сначала загрузить командой load("dynamics").

Изменения введенные в Maxima 5.12

Начиная с версии Maxima 5.12 пакет dynamics использует для построения графиков функцию plot2d. Команды, строящие графики (исключая julia и mandelbrot), принимают любые опции команды plot2d, включая опции выбора различных графических интерфейсов, выбора стилей и цвета, и представления одной или обеих осей в логарифмической шкале. Старые опции domain, pointsize, xcenter, xradius, ycenter, yradius, xaxislabel и yaxislabel, начиная с этой версии не действуют.

Все программы теперь принимают произвольные имена переменных, а не только x и y, как в старых версиях. Обязательные параметры изменились в двух программах: evolution2d теперь требует список, называющий явным образом две независимые переменные, а горизонтальный предел для orbits больше не требует указание размера шага. Теперь предел задает имя переменной, минимальное и максимальное значения. Размер шага теперь может быть изменен с помощью опции nticks. nticks.


Previous: Введение в пакет dynamics, Up: Пакет dynamics   [Contents][Index]

47.2 Функции и переменные пакета dynamics

Функция: chaosgame ([[x1, y1]...[xm, ym]], [x0, y0], b, n, ..., options, ...);

Реализует так называемую игру хаоса: сначала изображается начальная точка (x0, y0), далее одна из m точек [x1, y1]...[xm, ym] выбирается произвольным образом. Следующая точка изображается на отрезке, соединяющем предыдущую точку со случайно выбранной, на расстоянии от случайной точки равном длине этого отрезка, умноженной на b Процедура повторяется n раз.

Функция: evolution (F, y0, n, ..., options, ...);

Изображает n+1 точек на 2-мерном графе, где горизонтальные координаты точек есть 0, 1, 2, ..., n, а вертикальные координаты есть соответствующие значения последовательности y(n), определенной рекуррентным соотношением

        y(n+1) = F(y(n))

С начальным значением y(0) равным y0. F должно быть выражением, которое зависит только от одной переменной (в примере, оно зависит от y, но может быть использована только одна переменная), y0 должно быть вещественным числом, а n должно быть положительным целым.

Функция: evolution2d ([F, G], [u, v], [u0, y0], n, ..., options, ...);

Изображает на двумерном графике первые n+1 точек последовательности, определяемой двумерной дискретной динамической системой с рекуррентными соотношениями

        u(n+1) = F(u(n), v(n))    v(n+1) = G(u(n), v(n))

С начальными значениями u0 и v0. Выражения F и G должны зависеть только от двух переменных u и v, которые должны быть явно объявлены в списке.

Функция: ifs ([r1, ..., rm], [A1, ..., Am], [[x1, y1], ..., [xm, ym]], [x0, y0], n, ..., options, ...);

Реализует метод системы повторяющихся функций (Iterated Function System). Этот метод аналогичен игре хаоса, описанной в функции chaosgame, но вместо сжатия отрезка от текущей точки до случайно выбранной, две компоненты данного отрезка умножаются на 2х2 матрицу Ai, которая соответствует случайно выбранной точке.

Случайный выбор m точек притяжения может быть осуществлен с вероятностью, определенной весами r1,...,rm. Веса могут быть заданы в кумулятивной форме, например, если есть 3 точки с вероятностями 0.2, 0.5 и 0.3, то веса r1, r2 и r3 могут быть 2, 7 и 10.

Функция: julia (x, y, ...options...)

Создает графический файл с изображением фрактала Джулия для комплексного числа (x + i y). Параметры x и y должны быть вещественными. Файл в графическом формате XPM создается в текущей директории пользователя. Работа программы занимает несколько секунд, а по окончании вычислений она печатает имя созданного файла.

Точкам, которые не принадлежат фракталу Джулия, присваиваются разные цвета в соответствии с числом итераций, необходимых последовательности, начинающейся в точке, чтобы выити из круга сходимости радиуса 2. Максимальное число итераций определяется опцией levels. Если после этого числа итераций, последовательность все еще находится в круге сходимости, то точка будет изображена цветом, определяемым опцией color.

Все цвета, используемые для изображения точек, не принадлежащих фракталу Джулия, имеют одинаковые saturation и value, но различные углю оттенков, равномерно распределенные в интервале от hue до (hue + huerange).

options – набор необязательных опций. Список допустимых опций приведен в разделе ниже.

Функция: mandelbrot (options)

Создает графический файл с изображением фрактала Мандельброта. Файл в графическом формате XPM создается в текущей директории пользователя. Работа программы занимает несколько секунд, а по окончании вычислений она печатает имя созданного файла.

Точкам, которые не принадлежат фракталу Джулия, присваиваются разные цвета в соответствии с числом итераций, необходимых последовательности, начинающейся в точке, чтобы выити из круга сходимости радиуса 2. Максимальное число итераций определяется опцией levels. Если после этого числа итераций, последовательность все еще находится в круге сходимости, то точка будет изображена цветом, определяемым опцией color.

Все цвета, используемые для изображения точек, не принадлежащих фракталу Джулия, имеют одинаковые saturation и value, но различные углы оттенков, равномерно распределенные в интервале от hue до (hue + huerange).

options – набор необязательных опций. Список допустимых опций приведен в разделе ниже.

Функция: orbits (F, y0, n1, n2, [x, x0, xf, xstep], ...options...);

Изображает диаграмму траекторий семейства одномерных дискретных динамических систем с одним параметром x. Такой тип диаграмм используется при изучении бифуркации одномерных дискретных систем.

Функция F(y) определяет последовательность с начальным значением y0, также как в случае функции evolution, но в данном случае функция еще зависит от параметра x, принимающего значения в интервале от x0 до xf с шагом xstep. Каждое значение параметра x изображается на горизонтальной оси. На вертикальной оси изображаются n2 значений последовательности y(n1+1),..., y(n1+n2+1), полученных поле n1 начальных итераций.

Функция: rk (ODE, var, initial, domain)
Функция: rk ([ODE1,...,ODEm], [v1,...,vm], [init1,...,initm], domain)

Первая форма численно решает одно обычное дифференциальное уравнение первого порядка, а вторая форма решает систему m подобных уравнений, с использованием метода Рунге-Кутта 4-го порядка. var – зависимая переменная. ODE – должно быть выражением, которое зависит только от независимой и зависимой переменных и определяет производную зависимой переменной по независимой.

Независимая переменная задается параметром domain, который должен быть списком четырех элементов. Например:

[t, 0, 10, 0.1]

первый элемент списка есть независимая переменная, второй и третий элементы есть начальное и конечное значения этой переменной, и последний элемент задает шаг для данного интервала.

Если предстоит решить m уравнений, то должно быть m зависимых переменных v1, v2, ..., vm. Начальные значения для этих переменных будут init1, init2, ..., initm. При этом все равно остается только одна зависимая переменная, задаваемая domain, как в предыдущем случае. ODE1, ..., ODEm – выражения, определяющие производную каждой из зависимых переменных по независимой. Эти выражения могут зависеть только от зависимых переменных и независимой переменной. Важно задать производные ODE1, ..., ODEm в списке точно в том порядке, что и зависимые переменные. Т.е. третий элемент списка будет интерпретирован как производная третьей зависимой переменной.

Программа пытается проинтегрировать уравнения от начального значения независимой переменной до конечного значения с использованием постоянного приращения. Если на каком-либо шаге значение одной из зависимых переменных становится слишком большим по абсолютной величине, то интегрирование прекращается. Результат является списком с числом элементов равным числу итераций. Каждый элемент сам является списком с m+1 элементами: значение зависимой переменной с последующими значениями зависимых переменных в соответствующей точке.

Функция: staircase (F, y0, n, ...options...);

Строит лестничную диаграмму для последовательности, заданной рекуррентным соотношением

        y(n+1) = F(y(n))

Интерпретация и допустимые значения параметров аналогичны таковым для команды evolution. Лестничная диаграмма состоит из графика функции F(y) вместе с прямой G(y) = y. Из точки (y0, y0) на этой прямой строится вертикальный отрезок до переcечения с функцией F. Из этой точки строится горизонтальный отрезок до точки пересечения с прямой в точке (y1, y1). Процедура повторяется n раз до достижения точки (yn, yn).

Опции

Каждая опция есть список из двух или более элементов. Первый элемент – имя опции, остальные – аргументы опции.

Допустимые опции функций evolution, evolution2d, staircase, orbits, ifs и chaosgame те же самые, что у функции plot2d. Функция orbits допускает дополнительную опцию pixels, которая задает максимальное число точек по вертикали.

Следующие опции допускаются функциями julia и mandelbrot:

Примеры

Графическое представление лестничной диаграммы для последовательности: 2, cos(2), cos(cos(2)),...

(%i1) load("dynamics")$

(%i2) evolution(cos(y), 2, 11);

(%i3) staircase(cos(y), 1, 11, [y, 0, 1.2]);
./figures/dynamics1 ./figures/dynamics2

Если ваша система медленна, следует уменьшить число итераций в следующих примерах. Если точки кажутся слишком маленькими на мониторе, то можно попробовать другой стиль, например [style, [points, 0.8 ]].

Диаграмма траекторий для квадратичного отображения с параметром a.

        x(n+1) = a + x(n)^2
(%i4) orbits(x^2+a, 0, 50, 200, [a, -2, 0.25], [style, dots]);
./figures/dynamics3

Для того, чтобы увеличить область вблизи нижней бифуркации около x = -1.25 используем:

(%i5) orbits(x+y^2, 0, 100, 400, [a,-1,-1.53], [x,-1.6,-0.8],
             [nticks, 400], [style,dots]);
./figures/dynamics4

Эволюция двумерной системы, приводящая к фракталу:

(%i6) f: 0.6*x*(1+2*x)+0.8*y*(x-1)-y^2-0.9$

(%i7) g: 0.1*x*(1-6*x+4*y)+0.1*y*(1+9*y)-0.4$

(%i8) evolution2d([f,g], [x,y], [-0.5,0], 50000, [style,dots]);
./figures/dynamics5

Увеличение небольшой области фрактала:

(%i9) evolution2d([f,g], [x,y], [-0.5,0], 300000, [x,-0.8,-0.6],
                  [y,-0.4,-0.2], [style, dots]);
./figures/dynamics6

График треугольника Серпинского, полученный как игра хаоса:

(%i9) chaosgame([[0, 0], [1, 0], [0.5, sqrt(3)/2]], [0.1, 0.1], 1/2,
                 30000, [style, dots]);
./figures/dynamics7

Фрактал папоротник (Barnsley’s fern) полученный при помощи системы повторяющихся функций (Iterated Function System):

(%i10) a1: matrix([0.85,0.04],[-0.04,0.85])$

(%i11) a2: matrix([0.2,-0.26],[0.23,0.22])$

(%i12) a3: matrix([-0.15,0.28],[0.26,0.24])$

(%i13) a4: matrix([0,0],[0,0.16])$

(%i14) p1: [0,1.6]$

(%i15) p2: [0,1.6]$

(%i16) p3: [0,0.44]$

(%i17) p4: [0,0]$

(%i18) w: [85,92,99,100]$

(%i19) ifs(w, [a1,a2,a3,a4], [p1,p2,p3,p4], [5,0], 50000, [style,dots]);
./figures/dynamics8

Чтобы создать файл dynamics9.xpm с графическим изображением фрактала Мандельброта с 12 цветами, выполним:

mandelbrot([filename,"dynamics9"])$

Для фрактала Джулия с числом (-0.55 + i 0.6):

julia(-0.55, 0.6, [levels, 36], [center, 0, 0.6], [radius, 0.3],
      [hue, 240], [huerange, -180], [filename, "dynamics10"])$

Граф будет сохранен ф файле dynamics10.xpm и будет изображать область от -0.3 до 0.3 по оси x, и от 0.3 до 0.9 по оси y. Используется 36 цветов, начиная с синего и заканчивая желтым.

Чтобы решить дифференциальное уравнение

          dx/dt = t - x^2

с начальным значением x(t=0) = 1, в интервале t от 0 до 8 с шагом 0.1, используем команду:

(%i20) results: rk(t-x^2,x,1,[t,0,8,0.1])$

Результат сохраняется в списке results.

Чтобы численно решить систему:

        dx/dt = 4-x^2-4*y^2     dy/dt = y^2-x^2+1

для t от 0 до 4, и с значениями -1.25 и 0.75 для x и y в t=0:

(%i21) sol: rk([4-x^2-4*y^2,y^2-x^2+1],[x,y],[-1.25,0.75],[t,0,4,0.02])$

Next: , Previous: Пакет dynamics, Up: Top   [Contents][Index]

48 Пакет f90


Previous: Пакет f90, Up: Пакет f90   [Contents][Index]

48.1 Функции и переменные пакета f90

Функция: f90 (expr)

Команда f90 является исправлением оригинальной Maxima команды fortran. Основная разница заключается в том, как осуществляется перенос длинных строк.

В следующем примере, обратите внимание как команда fortran переносит строки внутри символов. Команда f90 никогда не делает перенос внутри символа.

(%i1) load("f90")$

(%i2) expr:expand((xxx+yyy+7)^4);
         4            3         3        2    2
(%o2) yyy  + 4 xxx yyy  + 28 yyy  + 6 xxx  yyy
             2          2        3             2
 + 84 xxx yyy  + 294 yyy  + 4 xxx  yyy + 84 xxx  yyy
                               4         3          2
 + 588 xxx yyy + 1372 yyy + xxx  + 28 xxx  + 294 xxx
 + 1372 xxx + 2401
(%i3) fortran(expr);
      yyy**4+4*xxx*yyy**3+28*yyy**3+6*xxx**2*yyy**2+84*xxx*yyy**2+294*yy
     1   y**2+4*xxx**3*yyy+84*xxx**2*yyy+588*xxx*yyy+1372*yyy+xxx**4+28*
     2   xxx**3+294*xxx**2+1372*xxx+2401
(%o3)                       done
(%i4) f90(expr);
yyy**4+4*xxx*yyy**3+28*yyy**3+6*xxx**2*yyy**2+84*xxx*yyy**2+294* &
     yyy**2+4*xxx**3*yyy+84*xxx**2*yyy+588*xxx*yyy+1372*yyy+xxx** &
     4+28*xxx**3+294*xxx**2+1372*xxx+2401
(%o4)                       done

Команда f90 реализована как быстрый хак. Она не является хорошим примером того, как следует реализовывать трансляцию в другие языки.

Для того, чтобы использовать эту функцию, сначала введите команду load("f90").


Next: , Previous: Пакет f90, Up: Top   [Contents][Index]

49 ggf


Previous: ggf-pkg, Up: ggf-pkg   [Contents][Index]

49.1 Functions and Variables for ggf

Option variable: GGFINFINITY

Default value: 3

This is an option variable for function ggf.

When computing the continued fraction of the generating function, a partial quotient having a degree (strictly) greater than GGFINFINITY will be discarded and the current convergent will be considered as the exact value of the generating function; most often the degree of all partial quotients will be 0 or 1; if you use a greater value, then you should give enough terms in order to make the computation accurate enough.

See also ggf.

Option variable: GGFCFMAX

Default value: 3

This is an option variable for function ggf.

When computing the continued fraction of the generating function, if no good result has been found (see the GGFINFINITY flag) after having computed GGFCFMAX partial quotients, the generating function will be considered as not being a fraction of two polynomials and the function will exit. Put freely a greater value for more complicated generating functions.

See also ggf.

Function: ggf (l)

Compute the generating function (if it is a fraction of two polynomials) of a sequence, its first terms being given. l is a list of numbers.

The solution is returned as a fraction of two polynomials. If no solution has been found, it returns with done.

This function is controlled by global variables GGFINFINITY and GGFCFMAX. See also GGFINFINITY and GGFCFMAX.

To use this function write first load("ggf").

(%i1) load("ggf")$
(%i2) makelist(fib(n),n,0,10);
(%o2)                [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
(%i3) ggf(%);
                                       x
(%o3)                            - ----------
                                    2
                                   x  + x - 1
(%i4) taylor(%,x,0,10);
              2      3      4      5      6       7       8       9       10
(%o4)/T/ x + x  + 2 x  + 3 x  + 5 x  + 8 x  + 13 x  + 21 x  + 34 x  + 55 x
                                                                        + . . .
(%i5) makelist(2*fib(n+1)-fib(n),n,0,10);
(%o5)              [2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123]
(%i6) ggf(%);
                                    x - 2
(%o6)                             ----------
                                   2
                                  x  + x - 1
(%i7) taylor(%,x,0,10);
                    2      3      4       5       6       7       8       9
(%o7)/T/ 2 + x + 3 x  + 4 x  + 7 x  + 11 x  + 18 x  + 29 x  + 47 x  + 76 x
                                                                     10
                                                              + 123 x   + . . .

As these examples show, the generating function does create a function whose Taylor series has coefficients that are the elements of the original list.


Next: , Previous: ggf-pkg, Up: Top   [Contents][Index]

50 Пакет graphs


Next: , Previous: Пакет graphs, Up: Пакет graphs   [Contents][Index]

50.1 Введение в пакет graphs

Пакет graphs предоставляет структуры для представления графов и ориентированных графов в Maxima. Графы и ориентированные графы являются простыми, т.е. не имеют кратных ребер и петель, но ориентированные графы могут иметь ориентированное ребро из u в v и ориентированное ребро из v в u.

Внутренне графы представляются как списки смежности и реализованы в виде Lisp структур. Вершины обозначаются своими идентификаторами id (id – есть целое число). Ребра/дуги представлены списками длины 2. Вершинам графов и ориентированных графов могут быть присвоены метки а ребрам/дугам можно присвоить веса.

Функция draw_graph предназначена для рисования графов. Графы изображаются с использованием метода взаимодействия сил. Функция draw_graph может также использовать программу graphviz, доступную по ссылке http://www.graphviz.org. Функция draw_graph основана на пакете draw.

Чтобы использовать пакет graphs, его сначала следует загрузить командой load("graphs").


Previous: Введение в пакет graphs, Up: Пакет graphs   [Contents][Index]

50.2 Функции и переменные пакета graphs

50.2.1 Построение графов

Функция: create_graph (v_list, e_list)
Функция: create_graph (n, e_list)
Функция: create_graph (v_list, e_list, directed)

Создает новый граф с множеством вершин v_list и ребрами e_list.

v_list – список вершин ([v1, v2,..., vn]) или вершин вместе с метками ([[v1,l1], [v2,l2],..., [vn,ln]]).

Если n – число вершин, то они будут обозначаться целыми числами от 0 до n-1.

e_list – список ребер вида ([e1, e2,..., em]) или список ребер вместе с весами ([[e1, w1], ..., [em, wm]]).

Если directed отлично от false, то возвращается ориентированный граф.

Пример 1: цикл с тремя вершинами:

(%i1) load ("graphs")$
(%i2) g : create_graph([1,2,3], [[1,2], [2,3], [1,3]])$
(%i3) print_graph(g)$
Graph on 3 vertices with 3 edges.
Adjacencies:
  3 :  1  2
  2 :  3  1
  1 :  3  2

Пример 2: цикл с тремя вершинами и весами ребер:

(%i1) load ("graphs")$
(%i2) g : create_graph([1,2,3], [[[1,2], 1.0], [[2,3], 2.0],
                          [[1,3], 3.0]])$
(%i3) print_graph(g)$
Graph on 3 vertices with 3 edges.
Adjacencies:
  3 :  1  2
  2 :  3  1
  1 :  3  2

Пример 3: ориентированный граф:

(%i1) load ("graphs")$
(%i2) d : create_graph(
        [1,2,3,4],
        [
         [1,3], [1,4],
         [2,3], [2,4]
        ],
        'directed = true)$
(%i3) print_graph(d)$
Digraph on 4 vertices with 4 arcs.
Adjacencies:
  4 :
  3 :
  2 :  4  3
  1 :  4  3
Функция: copy_graph (g)

Возвращает копию графа g.

Функция: circulant_graph (n, d)

Возвращает циркулянтный граф граф с параметрами n и d.

Пример:

(%i1) load ("graphs")$
(%i2) g : circulant_graph(10, [1,3])$
(%i3) print_graph(g)$
Graph on 10 vertices with 20 edges.
Adjacencies:
  9 :  2  6  0  8
  8 :  1  5  9  7
  7 :  0  4  8  6
  6 :  9  3  7  5
  5 :  8  2  6  4
  4 :  7  1  5  3
  3 :  6  0  4  2
  2 :  9  5  3  1
  1 :  8  4  2  0
  0 :  7  3  9  1
Функция: clebsch_graph ()

Возвращает граф Клебша (Clebsch graph).

Функция: complement_graph (g)

Возвращает граф, дополнительный графу g.

Функция: complete_bipartite_graph (n, m)

Возвращает полный двудольный граф с n+m вершинами.

Функция: complete_graph (n)

Возвращает полный граф с n вершинами.

Функция: cycle_digraph (n)

Возвращает ориентированный циклический граф с n вершинами.

Функция: cycle_graph (n)

Возвращает циклический граф с n вершинами.

Функция: cube_graph (n)

Возвращает n-мерный куб.

Функция: dodecahedron_graph ()

Возвращает граф додекаэдра.

Функция: empty_graph (n)

Возвращает пустой граф с n вершинами.

Функция: flower_snark (n)

Возвращает цветочный граф (flower graph) с 4n вершинами.

Пример:

(%i1) load ("graphs")$
(%i2) f5 : flower_snark(5)$
(%i3) chromatic_index(f5);
(%o3)                           4
Функция: from_adjacency_matrix (A)

Возвращает граф с матрицей смежности A.

Функция: frucht_graph ()

Возвращает граф Фручта (Frucht graph).

Функция: graph_product (g1, g1)

Возвращает прямое произведение графов g1 и g2.

Пример:

(%i1) load ("graphs")$
(%i2) grid : graph_product(path_graph(3), path_graph(4))$
(%i3) draw_graph(grid)$
./figures/graphs01
Функция: graph_union (g1, g1)

Возвращает объединение (сумму) графов g1 и g2.

Функция: grid_graph (n, m)

Возвращает решетку n x m.

Функция: grotzch_graph ()

Возвращает граф Гротча (Grotzch graph).

Функция: heawood_graph ()

Возвращает граф Хейвуда (Heawood graph).

Функция: icosahedron_graph ()

Возвращает граф икосаэдра.

Функция: induced_subgraph (V, g)

Возвращает граф, состоящий из подмножества вершин V графа g.

Пример:

(%i1) load ("graphs")$
(%i2) p : petersen_graph()$
(%i3) V : [0,1,2,3,4]$
(%i4) g : induced_subgraph(V, p)$
(%i5) print_graph(g)$
Graph on 5 vertices with 5 edges.
Adjacencies:
  4 :  3  0
  3 :  2  4
  2 :  1  3
  1 :  0  2
  0 :  1  4
Функция: line_graph (g)

Возвращает граф двойственный (line graph) графу g.

Функция: make_graph (vrt, f)
Функция: make_graph (vrt, f, oriented)

Создает граф, используя функцию предикат f.

vrt – есть список/множество вкршин или целое число. Если vrt есть целое число, то вершины графа будут целыми от 1 до vrt.

f – функция предикат. Вершины a и b будут соединены, если f(a,b)=true.

Если directed не равно false, то граф будет ориентированным.

Пример 1:

(%i1) load("graphs")$
(%i2) g : make_graph(powerset({1,2,3,4,5}, 2), disjointp)$
(%i3) is_isomorphic(g, petersen_graph());
(%o3)                         true
(%i4) get_vertex_label(1, g);
(%o4)                        {1, 2}

Пример 2:

(%i1) load("graphs")$
(%i2) f(i, j) := is (mod(j, i)=0)$
(%i3) g : make_graph(20, f, directed=true)$
(%i4) out_neighbors(4, g);
(%o4)                    [8, 12, 16, 20]
(%i5) in_neighbors(18, g);
(%o5)                    [1, 2, 3, 6, 9]
Функция: mycielski_graph (g)

Возвращает граф Мицельского (mycielskian graph) графа g.

Функция: new_graph ()

Возвращает граф без вершин и ребер.

Функция: path_digraph (n)

Возвращает ориентированный путь с n вершинами.

Функция: path_graph (n)

Возвращает путь с n вершинами.

Функция: petersen_graph ()
Функция: petersen_graph (n, d)

Возвращает граф Петерсена P_{n,d}. Значения по умолчанию для n и d есть n=5 и d=2.

Функция: random_bipartite_graph (a, b, p)

Возвращает случайный двудольный граф с a+b вершинами. Каждая вершина присутствует с вероятностью p.

Функция: random_digraph (n, p)

Возвращает случайный ориентированный граф с n вершинами. Каждое ребро присутствует с вероятностью p.

Функция: random_regular_graph (n)
Функция: random_regular_graph (n, d)

Возвращает случайный d-регулярный граф с n вершинами. Значение по умолчанию для d есть d=3.

Функция: random_graph (n, p)

Возвращает случайный граф с n вершинами. Каждое ребро присутствует с вероятностью p.

Функция: random_graph1 (n, m)

Возвращает случайный граф с n вершинами и m случайными ребрами.

Функция: random_network (n, p, w)

Возвращает случайную сеть на n вершинах. Каждое ребро присутствует с вероятностью p и имеет вес в интервале [0,w]. Эта функция возвращает список [network, source, sink].

Пример:

(%i1) load ("graphs")$
(%i2) [net, s, t] : random_network(50, 0.2, 10.0);
(%o2)                   [DIGRAPH, 50, 51]
(%i3) max_flow(net, s, t)$
(%i4) first(%);
(%o4)                   27.65981397932507
Функция: random_tournament (n)

Возвращает случайный полный ориентированный граф (tournament) с n вершинами.

Функция: random_tree (n)

Возвращает случайное дерево с n вершинами.

Функция: tutte_graph ()

Возвращает граф Татта (Tutte).

Функция: underlying_graph (g)

Возвращает неориентированный граф, получаемый заменой ребер ориентированного графа g на неориентированные.

Функция: wheel_graph (n)

Возвращает колесный граф (wheel graph) с n+1 вершинами.

50.2.2 Свойства графов

Функция: adjacency_matrix (gr)

Возвращает матрицу смежности графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) c5 : cycle_graph(4)$
(%i3) adjacency_matrix(c5);
                         [ 0  1  0  1 ]
                         [            ]
                         [ 1  0  1  0 ]
(%o3)                    [            ]
                         [ 0  1  0  1 ]
                         [            ]
                         [ 1  0  1  0 ]
Функция: average_degree (gr)

Возвращает среднюю степень вершин графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) average_degree(grotzch_graph());
                               40
(%o2)                          --
                               11
Функция: biconected_components (gr)

Возвращает (наборы вершин) 2-связных компонент графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) g : create_graph(
            [1,2,3,4,5,6,7],
            [
             [1,2],[2,3],[2,4],[3,4],
             [4,5],[5,6],[4,6],[6,7]
            ])$
(%i3) biconnected_components(g);
(%o3)        [[6, 7], [4, 5, 6], [1, 2], [2, 3, 4]]
./figures/graphs13
Функция: bipartition (gr)

Возвращает двудольное разложение графа gr или пустой список, если gr не является двудольным.

Пример:

(%i1) load ("graphs")$
(%i2) h : heawood_graph()$
(%i3) [A,B]:bipartition(h);
(%o3)  [[8, 12, 6, 10, 0, 2, 4], [13, 5, 11, 7, 9, 1, 3]]
(%i4) draw_graph(h, show_vertices=A, program=circular)$
./figures/graphs02
Функция: chromatic_index (gr)

Возвращает хроматический индекс графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) p : petersen_graph()$
(%i3) chromatic_index(p);
(%o3)                           4
Функция: chromatic_number (gr)

Возвращает хроматическое число графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) chromatic_number(cycle_graph(5));
(%o2)                           3
(%i3) chromatic_number(cycle_graph(6));
(%o3)                           2
Функция: clear_edge_weight (e, gr)

Удаляет вес ребра e в графе gr.

Пример:

(%i1) load ("graphs")$
(%i2) g : create_graph(3, [[[0,1], 1.5], [[1,2], 1.3]])$
(%i3) get_edge_weight([0,1], g);
(%o3)                          1.5
(%i4) clear_edge_weight([0,1], g)$
(%i5) get_edge_weight([0,1], g);
(%o5)                           1
Функция: clear_vertex_label (v, gr)

Удаляет метку вершины v в графе gr.

Пример:

(%i1) load ("graphs")$
(%i2) g : create_graph([[0,"Zero"], [1, "One"]], [[0,1]])$
(%i3) get_vertex_label(0, g);
(%o3)                        Zero
(%i4) clear_vertex_label(0, g);
(%o4)                        done
(%i5) get_vertex_label(0, g);
(%o5)                        false
Функция: connected_components (gr)

Возвращает (наборы вершин) компоненты связности графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) g: graph_union(cycle_graph(5), path_graph(4))$
(%i3) connected_components(g);
(%o3)           [[1, 2, 3, 4, 0], [8, 7, 6, 5]]
Функция: diameter (gr)

Возвращает диаметр графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) diameter(dodecahedron_graph());
(%o2)                          5
Функция: edge_coloring (gr)

Возвращает оптимальную раскраску ребер графа gr.

Эта функция возвращает хроматический индекс и список, представляющий раскраску ребер графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) p : petersen_graph()$
(%i3) [ch_index, col] : edge_coloring(p);
(%o3) [4, [[[0, 5], 3], [[5, 7], 1], [[0, 1], 1], [[1, 6], 2], 
[[6, 8], 1], [[1, 2], 3], [[2, 7], 4], [[7, 9], 2], [[2, 3], 2], 
[[3, 8], 3], [[5, 8], 2], [[3, 4], 1], [[4, 9], 4], [[6, 9], 3], 
[[0, 4], 2]]]
(%i4) assoc([0,1], col);
(%o4)                           1
(%i5) assoc([0,5], col);
(%o5)                           3
Функция: degree_sequence (gr)

Возвращает список степеней вершин графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) degree_sequence(random_graph(10, 0.4));
(%o2)            [3, 3, 3, 4, 4, 4, 5, 5, 6, 7]
Функция: edges (gr)

Возвращает список ребер/дуг ориентированного или неориентированного графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) edges(complete_graph(4));
(%o2)   [[2, 3], [1, 3], [1, 2], [0, 3], [0, 2], [0, 1]]
Функция: get_edge_weight (e, gr)
Функция: get_edge_weight (e, gr, ifnot)

Возвращает вес ребра e графа gr.

Если вес не присвоен ребру, то возвращается 1. Если ребро в графе отсутствует, то выдается ошибка или возвращает необязательный аргумент ifnot.

Пример:

(%i1) load ("graphs")$
(%i2) c5 : cycle_graph(5)$
(%i3) get_edge_weight([1,2], c5);
(%o3)                           1
(%i4) set_edge_weight([1,2], 2.0, c5);
(%o4)                         done
(%i5) get_edge_weight([1,2], c5);
(%o5)                          2.0
Функция: get_vertex_label (v, gr)

Возвращает метку вершины v графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) g : create_graph([[0,"Zero"], [1, "One"]], [[0,1]])$
(%i3) get_vertex_label(0, g);
(%o3)                         Zero
Функция: graph_charpoly (gr, x)

Возвращает характеристический многочлен (от переменной x) графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) p : petersen_graph()$
(%i3) graph_charpoly(p, x), factor;
                                   5        4
(%o3)               (x - 3) (x - 1)  (x + 2)
Функция: graph_center (gr)

Возвращает центр графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) g : grid_graph(5,5)$
(%i3) graph_center(g);
(%o3)                         [12]
Функция: graph_eigenvalues (gr)

Возвращает собственные значения графа gr. Значение возвращаются в том же формате, что возвращает Maxima функция eigenvalue.

Пример:

(%i1) load ("graphs")$
(%i2) p : petersen_graph()$
(%i3) graph_eigenvalues(p);
(%o3)               [[3, - 2, 1], [1, 4, 5]]
Функция: graph_periphery (gr)

Возвращает периферию графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) g : grid_graph(5,5)$
(%i3) graph_periphery(g);
(%o3)                    [24, 20, 4, 0]
Функция: graph_size (gr)

Возвращает число вершин в графе gr.

Пример:

(%i1) load ("graphs")$
(%i2) p : petersen_graph()$
(%i3) graph_size(p);
(%o3)                          10
Функция: graph_order (gr)

Возвращает число ребер в графе gr.

Пример:

(%i1) load ("graphs")$
(%i2) p : petersen_graph()$
(%i3) graph_order(p);
(%o3)                          15
Функция: girth (gr)

Возвращает длину наикратчайшего цикла в графе gr.

Пример:

(%i1) load ("graphs")$
(%i2) g : heawood_graph()$
(%i3) girth(g);
(%o3)                           5
Функция: hamilton_cycle (gr)

Возвращает гамильтонов цикл графа gr или пустой список, если граф gr не является гамильтоновым.

Пример:

(%i1) load ("graphs")$
(%i2) c : cube_graph(3)$
(%i3) hc : hamilton_cycle(c);
(%o3)              [7, 3, 2, 6, 4, 0, 1, 5, 7]
(%i4) draw_graph(c, show_edges=vertices_to_cycle(hc))$
./figures/graphs03
Функция: hamilton_path (gr)

Возвращает гамильтонов путь графа gr или пустой список, если граф gr не имеет гамильтонова пути.

Пример:

(%i1) load ("graphs")$
(%i2) p : petersen_graph()$
(%i3) hp : hamilton_path(p);
(%o3)            [0, 5, 7, 2, 1, 6, 8, 3, 4, 9]
(%i4) draw_graph(p, show_edges=vertices_to_path(hp))$
./figures/graphs04
Функция: isomorphism (gr1, gr2)

Возвращает хэш-таблицу изоморфизма между (ориентированными) графами gr1 и gr2. Если gr1 и gr2 не изоморфны, то возвращается false.

Пример:

(%i1) load ("graphs")$
(%i2) clk5:complement_graph(line_graph(complete_graph(5)))$
(%i3) hash_table_data(isomorphism(clk5, petersen_graph()));
(%o3) [8 -> 9, 7 -> 8, 4 -> 7, 3 -> 6, 1 -> 5, 0 -> 4, 5 -> 3, 
                                          6 -> 2, 2 -> 1, 9 -> 0]
Функция: in_neighbors (v, gr)

Возвращает список входящих соседей (in-neighbors) вершины v ориентированного графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) p : path_digraph(3)$
(%i3) in_neighbors(2, p);
(%o3)                          [1]
(%i4) out_neighbors(2, p);
(%o4)                          []
Функция: is_biconnected (gr)

Возвращает true, если граф gr 2-связный, и false в противном случае.

Пример:

(%i1) load ("graphs")$
(%i2) is_biconnected(cycle_graph(5));
(%o2)                         true
(%i3) is_biconnected(path_graph(5));
(%o3)                         false
Функция: is_bipartite (gr)

Возвращает true, если граф gr двудольный, и false в противном случае.

Пример:

(%i1) load ("graphs")$
(%i2) is_bipartite(petersen_graph());
(%o2)                        false
(%i3) is_bipartite(heawood_graph());
(%o3)                        true
Функция: is_connected (gr)

Возвращает true, если граф gr связный, и false в противном случае.

Пример:

(%i1) load ("graphs")$
(%i2) is_connected(graph_union(cycle_graph(4), path_graph(3)));
(%o2)                        false
Функция: is_digraph (gr)

Возвращает true, если gr является ориентированным графом, и false в противном случае.

Пример:

(%i1) load ("graphs")$
(%i2) is_digraph(path_graph(5));
(%o2)                        false
(%i3) is_digraph(path_digraph(5));
(%o3)                        true
Функция: is_edge_in_graph (e, gr)

Возвращает true, если e есть ребро (ориентированного) графа g, и false в противном случае.

Пример:

(%i1) load ("graphs")$
(%i2) c4 : cycle_graph(4)$
(%i3) is_edge_in_graph([2,3], c4);
(%o3)                        true
(%i4) is_edge_in_graph([3,2], c4);
(%o4)                        true
(%i5) is_edge_in_graph([2,4], c4);
(%o5)                        false
(%i6) is_edge_in_graph([3,2], cycle_digraph(4));
(%o6)                        false
Функция: is_graph (gr)

Возвращает true, если gr является графом, и false в противном случае.

Пример:

(%i1) load ("graphs")$
(%i2) is_graph(path_graph(5));
(%o2)                        true
(%i3) is_graph(path_digraph(5));
(%o3)                        false
Функция: is_graph_or_digraph (gr)

Возвращает true, если gr является графом или ориентированным графом, и false в противном случае.

Пример:

(%i1) load ("graphs")$
(%i2) is_graph_or_digraph(path_graph(5));
(%o2)                        true
(%i3) is_graph_or_digraph(path_digraph(5));
(%o3)                        true
Функция: is_isomorphic (gr1, gr2)

Возвращает true, если (ориентированные) графы gr1 и gr2 изоморфны, и false в противном случае.

См. также isomorphism.

Пример:

(%i1) load ("graphs")$
(%i2) clk5:complement_graph(line_graph(complete_graph(5)))$
(%i3) is_isomorphic(clk5, petersen_graph());
(%o3)                       true
Функция: is_planar (gr)

Возвращает true, если gr является планарным графом, и false в противном случае.

Используется алгоритм Демукрона, который является квадратичным по времени.

Пример:

(%i1) load ("graphs")$
(%i2) is_planar(dodecahedron_graph());
(%o2)                         true
(%i3) is_planar(petersen_graph());
(%o3)                         false
(%i4) is_planar(petersen_graph(10,2));
(%o4)                         true
Функция: is_sconnected (gr)

Возвращает true, если ориентированный граф gr является сильно связным, и false в противном случае.

Пример:

(%i1) load ("graphs")$
(%i2) is_sconnected(cycle_digraph(5));
(%o2)                        true
(%i3) is_sconnected(path_digraph(5));
(%o3)                        false
Функция: is_vertex_in_graph (v, gr)

Возвращает true, если v есть вершина в графе g, и false в противном случае.

Пример:

(%i1) load ("graphs")$
(%i2) c4 : cycle_graph(4)$
(%i3) is_vertex_in_graph(0, c4);
(%o3)                        true
(%i4) is_vertex_in_graph(6, c4);
(%o4)                        false
Функция: is_tree (gr)

Возвращает true, если граф gr является деревом, и false в противном случае.

Пример:

(%i1) load ("graphs")$
(%i2) is_tree(random_tree(4));
(%o2)                        true
(%i3) is_tree(graph_union(random_tree(4), random_tree(5)));
(%o3)                        false
Функция: laplacian_matrix (gr)

Возвращает матрицу Лапласа графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) laplacian_matrix(cycle_graph(5));
                   [  2   - 1   0    0   - 1 ]
                   [                         ]
                   [ - 1   2   - 1   0    0  ]
                   [                         ]
(%o2)              [  0   - 1   2   - 1   0  ]
                   [                         ]
                   [  0    0   - 1   2   - 1 ]
                   [                         ]
                   [ - 1   0    0   - 1   2  ]
Функция: max_clique (gr)

Возвращает максимальную клику графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) g : random_graph(100, 0.5)$
(%i3) max_clique(g);
(%o3)          [2, 6, 13, 17, 21, 23, 31, 62, 65]
Функция: max_degree (gr)

Возвращает максимальную степень вершины графа gr и саму вершину с максимальной степенью.

Пример:

(%i1) load ("graphs")$
(%i2) g : random_graph(100, 0.02)$
(%i3) max_degree(g);
(%o3)                        [6, 70]
(%i4) vertex_degree(95, g);
(%o4)                           3
Функция: max_flow (net, s, t)

Возвращает максимальный поток через сеть net с истоком s и стоком t.

Функция возвращает значение максимального потока и список весов ребер оптимального потока.

Пример:

(%i1) load ("graphs")$
(%i2) net : create_graph(
  [1,2,3,4,5,6],
  [[[1,2], 1.0],
   [[1,3], 0.3],
   [[2,4], 0.2],
   [[2,5], 0.3],
   [[3,4], 0.1],
   [[3,5], 0.1],
   [[4,6], 1.0],
   [[5,6], 1.0]],
  directed=true)$
(%i3) [flow_value, flow] : max_flow(net, 1, 6);
(%o3) [0.7, [[[1, 2], 0.5], [[1, 3], 0.2], [[2, 4], 0.2], 
[[2, 5], 0.3], [[3, 4], 0.1], [[3, 5], 0.1], [[4, 6], 0.3], 
[[5, 6], 0.4]]]
(%i4) fl : 0$
(%i5) for u in out_neighbors(1, net)
     do fl : fl + assoc([1, u], flow)$
(%i6) fl;
(%o6)                          0.7
Функция: max_independent_set (gr)

Возвращает максимальное независимое множество графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) d : dodecahedron_graph()$
(%i3) mi : max_independent_set(d);
(%o3)             [0, 3, 5, 9, 10, 11, 18, 19]
(%i4) draw_graph(d, show_vertices=mi)$
./figures/graphs05
Функция: max_matching (gr)

Возвращает максимальный набор ребер, не имеющих общих вершин (maximal matching), для графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) d : dodecahedron_graph()$
(%i3) m : max_matching(d);
(%o3) [[1, 2], [3, 4], [0, 15], [11, 16], [12, 17], [13, 18], 
                               [14, 19], [6, 10], [8, 9], [5, 7]]
(%i4) draw_graph(d, show_edges=m)$
./figures/graphs06
Функция: min_degree (gr)

Возвращает минимальную степень вершины графа gr и саму вершину с минимальной степенью.

Пример:

(%i1) load ("graphs")$
(%i2) g : random_graph(100, 0.1)$
(%i3) min_degree(g);
(%o3)                        [4, 83]
(%i4) vertex_degree(21, g);
(%o4)                          12
Функция: min_vertex_cover (gr)

Возвращает минимальное вершинное покрытие графа gr.

Функция: minimum_spanning_tree (gr)

Возвращает минимальный каркас (минимальное остовное дерево) графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) g : graph_product(path_graph(10), path_graph(10))$
(%i3) t : minimum_spanning_tree(g)$
(%i4) draw_graph(g, show_edges=edges(t))$
./figures/graphs07
Функция: neighbors (v, gr)

Возвращает список соседей вершины v в графе gr.

Пример:

(%i1) load ("graphs")$
(%i2) p : petersen_graph()$
(%i3) neighbors(3, p);
(%o3)                       [4, 8, 2]
Функция: odd_girth (gr)

Возвращает длину наикратчайшего нечетного цикла в графе gr.

Пример:

(%i1) load ("graphs")$
(%i2) g : graph_product(cycle_graph(4), cycle_graph(7))$
(%i3) girth(g);
(%o3)                           4
(%i4) odd_girth(g);
(%o4)                           7
Функция: out_neighbors (v, gr)

Возвращает список исходящих соседей (out-neighbors) вершины v ориентированного графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) p : path_digraph(3)$
(%i3) in_neighbors(2, p);
(%o3)                           [1]
(%i4) out_neighbors(2, p);
(%o4)                           []
Функция: planar_embedding (gr)

Возвращает список поверхностных маршрутов (facial walks) в плоской укладке графа gr, и false, если граф gr не является планарным.

Граф gr должен быть бисвязным.

Используется алгоритм Демукрона, который является квадратичным по времени.

Пример:

(%i1) load ("graphs")$
(%i2) planar_embedding(grid_graph(3,3));
(%o2) [[3, 6, 7, 8, 5, 2, 1, 0], [4, 3, 0, 1], [3, 4, 7, 6], 
                                      [8, 7, 4, 5], [1, 2, 5, 4]]
Функция: print_graph (gr)

Выводит некоторую информацию о графе gr.

Пример:

(%i1) load ("graphs")$
(%i2) c5 : cycle_graph(5)$
(%i3) print_graph(c5)$
Graph on 5 vertices with 5 edges.
Adjacencies:
  4 :  0  3
  3 :  4  2
  2 :  3  1
  1 :  2  0
  0 :  4  1
(%i4) dc5 : cycle_digraph(5)$
(%i5) print_graph(dc5)$
Digraph on 5 vertices with 5 arcs.
Adjacencies:
  4 :  0
  3 :  4
  2 :  3
  1 :  2
  0 :  1
(%i6) out_neighbors(0, dc5);
(%o6)                          [1]
Функция: radius (gr)

Возвращает радиус графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) radius(dodecahedron_graph());
(%o2)                           5
Функция: set_edge_weight (e, w, gr)

Присваивает вес w ребру e графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) g : create_graph([1, 2], [[[1,2], 1.2]])$
(%i3) get_edge_weight([1,2], g);
(%o3)                          1.2
(%i4) set_edge_weight([1,2], 2.1, g);
(%o4)                         done
(%i5) get_edge_weight([1,2], g);
(%o5)                          2.1
Функция: set_vertex_label (v, l, gr)

Присваивает метку l вершине v графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) g : create_graph([[1, "One"], [2, "Two"]], [[1,2]])$
(%i3) get_vertex_label(1, g);
(%o3)                           One
(%i4) set_vertex_label(1, "oNE", g);
(%o4)                          done
(%i5) get_vertex_label(1, g);
(%o5)                           oNE
Функция: shortest_path (u, v, gr)

Возвращает кратчайший путь из вершины u в вершину v в графе gr.

Пример:

(%i1) load ("graphs")$
(%i2) d : dodecahedron_graph()$
(%i3) path : shortest_path(0, 7, d);
(%o3)                    [0, 1, 19, 13, 7]
(%i4) draw_graph(d, show_edges=vertices_to_path(path))$
./figures/graphs08
Функция: strong_components (gr)

Возвращает сильную компоненту ориентированного графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) t : random_tournament(4)$
(%i3) strong_components(t);
(%o3)                 [[2], [0], [1], [3]]
(%i4) vertex_out_degree(3, t);
(%o4)                           2
Функция: topological_sort (dag)

Возвращает топологическую сортировку вершин ориентированного графа dag, или пустой список, если dag не является ориентированным ациклическим графом.

Пример:

(%i1) load ("graphs")$
(%i2) g:create_graph(
         [1,2,3,4,5],
         [
          [1,2], [2,5], [5,3],
          [5,4], [3,4], [1,3]
         ],
         directed=true)$
(%i3) topological_sort(g);
(%o3)                     [1, 2, 5, 3, 4]
Функция: vertex_degree (v, gr)

Возвращает степень вершины v в графе gr.

Функция: vertex_distance (u, v, gr)

Возвращает длину кратчайшего пути между вершинами u и v в (ориентированном) графе gr.

Пример:

(%i1) load ("graphs")$
(%i2) d : dodecahedron_graph()$
(%i3) vertex_distance(0, 7, d);
(%o3)                           4
(%i4) shortest_path(0, 7, d);
(%o4)                   [0, 1, 19, 13, 7]
Функция: vertex_eccentricity (v, gr)

Возвращает эксцентриситет вершины v графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) g:cycle_graph(7)$
(%i3) vertex_eccentricity(0, g);
(%o4)                            3
Функция: vertex_in_degree (v, gr)

Возвращает входящую степень вершины v ориентированного графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) p5 : path_digraph(5)$
(%i3) print_graph(p5)$
Digraph on 5 vertices with 4 arcs.
Adjacencies:
  4 :
  3 :  4
  2 :  3
  1 :  2
  0 :  1
(%i4) vertex_in_degree(4, p5);
(%o4)                           1
(%i5) in_neighbors(4, p5);
(%o5)                          [3]
Функция: vertex_out_degree (v, gr)

Возвращает исходящую степень вершины v ориентированного графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) t : random_tournament(10)$
(%i3) vertex_out_degree(0, t);
(%o3)                           6
(%i4) out_neighbors(0, t);
(%o4)                  [9, 6, 4, 3, 2, 1]
Функция: vertices (gr)

Возвращает список вершин графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) vertices(complete_graph(4));
(%o2)                     [3, 2, 1, 0]

50.2.3 Изменение графов

Функция: add_edge (e, gr)

Добавляет ребро e к графу gr.

Пример:

(%i1) load ("graphs")$
(%i2) p : path_graph(4)$
(%i3) neighbors(0, p);
(%o3)                          [1]
(%i4) add_edge([0,3], p);
(%o4)                         done
(%i5) neighbors(0, p);
(%o5)                        [3, 1]
Функция: add_edges (e_list, gr)

Добавляет ребра из списка e_list к графу gr.

Пример:

(%i1) load ("graphs")$
(%i2) g : empty_graph(3)$
(%i3) add_edges([[0,1],[1,2]], g)$
(%i4) print_graph(g)$
Graph on 3 vertices with 2 edges.
Adjacencies:
  2 :  1
  1 :  2  0
  0 :  1
Функция: add_vertex (v, gr)

Добавляет вершину v к графу gr.

Пример:

(%i1) load ("graphs")$
(%i2) g : path_graph(2)$
(%i3) add_vertex(2, g)$
(%i4) print_graph(g)$
Graph on 3 vertices with 1 edges.
Adjacencies:
  2 :
  1 :  0
  0 :  1
Функция: add_vertices (v_list, gr)

Добавляет все вершины из списка v_list к графу gr.

Функция: connect_vertices (v_list, u_list, gr)

Соединяет все вершины из списка v_list с вершинами из списка u_list в графе gr.

v_list и u_list могут быть отдельными вершинами или списками вершин.

Пример:

(%i1) load ("graphs")$
(%i2) g : empty_graph(4)$
(%i3) connect_vertices(0, [1,2,3], g)$
(%i4) print_graph(g)$
Graph on 4 vertices with 3 edges.
Adjacencies:
  3 :  0
  2 :  0
  1 :  0
  0 :  3  2  1
Функция: contract_edge (e, gr)

Стягивает ребро e в графе gr.

Пример:

(%i1) load ("graphs")$
(%i2) g: create_graph(
      8, [[0,3],[1,3],[2,3],[3,4],[4,5],[4,6],[4,7]])$
(%i3) print_graph(g)$
Graph on 8 vertices with 7 edges.
Adjacencies:
  7 :  4
  6 :  4
  5 :  4
  4 :  7  6  5  3
  3 :  4  2  1  0
  2 :  3
  1 :  3
  0 :  3
(%i4) contract_edge([3,4], g)$
(%i5) print_graph(g)$
Graph on 7 vertices with 6 edges.
Adjacencies:
  7 :  3
  6 :  3
  5 :  3
  3 :  5  6  7  2  1  0
  2 :  3
  1 :  3
  0 :  3
Функция: remove_edge (e, gr)

Удаляет ребро e из графа gr.

Пример:

(%i1) load ("graphs")$
(%i2) c3 : cycle_graph(3)$
(%i3) remove_edge([0,1], c3)$
(%i4) print_graph(c3)$
Graph on 3 vertices with 2 edges.
Adjacencies:
  2 :  0  1
  1 :  2
  0 :  2
Функция: remove_vertex (v, gr)

Удаляет вершину v из графа gr.

Функция: vertex_coloring (gr)

Возвращает оптимальную раскраску вершин графа gr.

Функция возвращает хроматическое число и список, описывающий раскраску вершин графа g.

Пример:

(%i1) load ("graphs")$
(%i2) p:petersen_graph()$
(%i3) vertex_coloring(p);
(%o3) [3, [[0, 2], [1, 3], [2, 2], [3, 3], [4, 1], [5, 3], 
                                 [6, 1], [7, 1], [8, 2], [9, 2]]]

50.2.4 Чтение и запись файлов

Функция: dimacs_export (gr, fl)
Функция: dimacs_export (gr, fl, comment1, ..., commentn)

Экспортирует граф в файл fl в формате DIMACS. Необязательный комментарий будет добавлен к началу файла.

Функция: dimacs_import (fl)

Возвращает граф из файла fl, в котором он записан в формате DIMACS.

Функция: graph6_decode (str)

Возвращает граф, закодированный в формате graph6 в строке str.

Функция: graph6_encode (gr)

Возвращает строку – закодированное представление графа gr в формате graph6.

Функция: graph6_export (gr_list, fl)

Экспортирует графы из списка gr_list в файл fl в формате graph6.

Функция: graph6_import (fl)

Возвращает список графов из файла fl, где они закодированы в формате graph6.

Функция: sparse6_decode (str)

Возвращает граф, закодированный в формате sparse6 в строке str.

Функция: sparse6_encode (gr)

Возвращает строку – закодированное представление графа gr в формате sparse6.

Функция: sparse6_export (gr_list, fl)

Экспортирует графы из списка gr_list в файл fl в формате sparse6.

Функция: sparse6_import (fl)

Возвращает список графов из файла fl, где они закодированы в формате sparse6.

50.2.5 Визуализация

Функция: draw_graph (graph)
Функция: draw_graph (graph, option1, ..., optionk)

Изображает граф с помощью пакета draw.

Алгоритм, используемый для размещения вершин, определяется необязательной переменной program. Значение по умолчанию program=spring_embedding. Может также использоваться программа graphviz, но она должна быть установлена отдельно.

Необязательные аргументы draw_graph могут быть:

Пример 1:

(%i1) load ("graphs")$
(%i2) g:grid_graph(10,10)$
(%i3) m:max_matching(g)$
(%i4) draw_graph(g,
   spring_embedding_depth=100,
   show_edges=m, edge_type=dots,
   vertex_size=0)$
./figures/graphs09

Пример 2:

(%i1) load ("graphs")$
(%i2) g:create_graph(16,
    [
     [0,1],[1,3],[2,3],[0,2],[3,4],[2,4],
     [5,6],[6,4],[4,7],[6,7],[7,8],[7,10],[7,11],
     [8,10],[11,10],[8,9],[11,12],[9,15],[12,13],
     [10,14],[15,14],[13,14]
    ])$
(%i3) t:minimum_spanning_tree(g)$
(%i4) draw_graph(
    g,
    show_edges=edges(t),
    show_edge_width=4,
    show_edge_color=green,
    vertex_type=filled_square,
    vertex_size=2
    )$
./figures/graphs10

Пример 3:

(%i1) load ("graphs")$
(%i2) g:create_graph(16,
    [
     [0,1],[1,3],[2,3],[0,2],[3,4],[2,4],
     [5,6],[6,4],[4,7],[6,7],[7,8],[7,10],[7,11],
     [8,10],[11,10],[8,9],[11,12],[9,15],[12,13],
     [10,14],[15,14],[13,14]
    ])$
(%i3) mi : max_independent_set(g)$
(%i4) draw_graph(
    g,
    show_vertices=mi,
    show_vertex_type=filled_up_triangle,
    show_vertex_size=2,
    edge_color=cyan,
    edge_width=3,
    show_id=true,
    text_color=brown
    )$
./figures/graphs11

Пример 4:

(%i1) load ("graphs")$
(%i2) net : create_graph(
    [0,1,2,3,4,5],
    [
     [[0,1], 3], [[0,2], 2],
     [[1,3], 1], [[1,4], 3],
     [[2,3], 2], [[2,4], 2],
     [[4,5], 2], [[3,5], 2]
    ],
    directed=true
    )$
(%i3) draw_graph(
    net,
    show_weight=true,
    vertex_size=0,
    show_vertices=[0,5],
    show_vertex_type=filled_square,
    head_length=0.2,
    head_angle=10,
    edge_color="dark-green",
    text_color=blue
    )$
./figures/graphs12
Управляющая переменная: draw_graph_program

Значение по умолчанию: spring_embedding.

Значение по умолчанию, которое используется для расположения вершин в программе draw_graph.

Функция: vertices_to_path (v_list)

Преобразует список вершин v_list в список ребер пути, определяемого списком v_list.

Функция: vertices_to_cycle (v_list)

Преобразует список вершин v_list в список ребер цикла, определяемого списком v_list.


Next: , Previous: Пакет graphs, Up: Top   [Contents][Index]

51 Пакет grobner


Next: , Previous: Top, Up: Top   [Contents][Index]

51.1 Введение в пакет grobner

Пакет grobner предназначен для работы с базисами Гребнера в Maxima.

Учебные материалы по базисам Гребнера могут быть найдены по адресу

http://www.geocities.com/CapeCanaveral/Hall/3131/

Для использования, описанных ниже функций, необходимо загрузить пакет grobner.lisp.

load("grobner");

Демонстрация может быть запущена так

demo("grobner.demo");

или так

batch("grobner.demo")

Некоторые вычисления в данной демонстрации занимают длительное время, поэтому вывод демонстрации, записанный в файл grobner-demo.output, может быть обнаружен в той же директории, где расположена демонстрация.

51.1.1 О пакете grobner

Пакет написан

Marek Rychlik

http://alamos.math.arizona.edu

и выпущен 2002-05-24 под лицензией General Public License (GPL) (см. файл grobner.lisp. Эта документация извлечена из файлов

README, grobner.lisp, grobner.demo, grobner-demo.output

Günter Nowak. Предложения по усовершенствованию документации можно обсудить в списке рассылки maxima-mailing-list maxima@math.utexas.edu. Код несколько устарел. Современные реализации используют быстрый алгоритм F4, описанный в

A new efficient algorithm for computing Gröbner bases (F4) 
Jean-Charles Faugère
LIP6/CNRS Université Paris VI 
January 20, 1999

51.1.2 Реализации и допустимые способы упорядочивания одночленов в пакете grobner


Previous: Введение в пакет grobner, Up: Top   [Contents][Index]

51.2 Функции и переменные пакета grobner

51.2.1 Глобальные переключатели пакета grobner

Управляющая переменная: poly_monomial_order

Значение по умолчанию: lex

Этот глобальный переключатель управляет тем, какой порядок одночленов используется с многочленах и в вычислении базиса Гребнера. Если значение не задано, то будет использовано lex.

Управляющая переменная: poly_coefficient_ring

Значение по умолчанию: expression_ring

Этот переключатель указывает кольцо коэффициентов многочленов, используемое в вычислениях базиса Гребнера. Если значение не задано, то используется общее кольцо выражений maxima. Если необходимо, значение переключателя может быть установлено равным ring_of_integers.

Управляющая переменная: poly_primary_elimination_order

Значение по умолчанию: false

Определяет порядок исключения переменных в функциях, основанных на исключении переменных. Если значение не задано, то будет использовано lex.

Управляющая переменная: poly_secondary_elimination_order

Значение по умолчанию: false

Определяет порядок сохраняемых переменных в функциях, основанных на исключении переменных. Если значение не задано, то будет использовано lex.

Управляющая переменная: poly_elimination_order

Значение по умолчанию: false

Определяет порядок исключения в вычислениях, основанных на исключении переменных. Если значение задано, то оно перекрывает значение переменных poly_primary_elimination_order и poly_secondary_elimination_order. Пользователь должен обеспечить, что заданный порядок исключения применим для данного числа исключаемых переменных.

Управляющая переменная: poly_return_term_list

Значение по умолчанию: false

Если равно true, то все функции пакета возвращают многочлены в виде списков членов с текущим порядком одночленов, а не в виде выражений maxima.

Управляющая переменная: poly_grobner_debug

Значение по умолчанию: false

Если равно true, то выводится трассировка и отладочная информация.

Управляющая переменная: poly_grobner_algorithm

Значение по умолчанию: buchberger

Возможные значения:

Определяет алгоритм, используемый для поиска базиса Гребнера.

Управляющая переменная: poly_top_reduction_only

Значение по умолчанию: false

Если не равно false, то когда возможно используется только приведение верхнего уровня. Приведение верхнего уровня означает, что алгоритм деления останавливается после первого приведения.

51.2.2 Простые операторы в пакете grobner

poly_add, poly_subtract, poly_multiply и poly_expt являются арифметическими операциями над многочленами. Они осуществляются над внутренним представлением, но результат преобразуется обратно в выражение maxima.

Функция: poly_add (poly1, poly2, varlist)

Складывает два многочлена poly1 и poly2.

(%i1) poly_add(z+x^2*y,x-z,[x,y,z]);
                                    2
(%o1)                              x  y + x
Функция: poly_subtract (poly1, poly2, varlist)

Вычитает многочлен poly2 из poly1.

(%i1) poly_subtract(z+x^2*y,x-z,[x,y,z]);
                                      2
(%o1)                          2 z + x  y - x
Функция: poly_multiply (poly1, poly2, varlist)

Возвращает произведение многочленов poly1 и poly2.

(%i2) poly_multiply(z+x^2*y,x-z,[x,y,z])-(z+x^2*y)*(x-z),expand;
(%o1)                                  0
Функция: poly_s_polynomial (poly1, poly2, varlist)

Возвращает S-многочлен (syzygy polynomial) двух многочленов poly1 и poly2.

Функция: poly_primitive_part (poly1, varlist)

Возвращает многочлен poly деленный на НОД своих коэффициентов.

(%i1) poly_primitive_part(35*y+21*x,[x,y]);
(%o1)                              5 y + 3 x
Функция: poly_normalize (poly, varlist)

Возвращает многочлен poly деленный на свой старший коэффициент. Подразумевается, что деление возможно, что может быть не всегда верно в случае колец не являющихся полями.

51.2.3 Другие функции пакета grobner

Функция: poly_expand (poly, varlist)

Эта функция преобразует многочлен во внутреннее представление и обратно. Она эквивалентна expand(poly), если poly корректно преобразуется в многочлен. Если представление не совместимо с многочленом от переменных varlist, то это приводит к ошибке. Данная функция может быть использована для проверки, возможно ли преобразование выражения во внутреннее представление. Нижеследующие примеры демонстрируют, что допустимы переменные с индексом или в виде трансцендентных функций.

(%i1) poly_expand((x-y)*(y+x),[x,y]);
                                     2    2
(%o1)                               x  - y
(%i2) poly_expand((y+x)^2,[x,y]);
                                2            2
(%o2)                          y  + 2 x y + x
(%i3) poly_expand((y+x)^5,[x,y]);
                  5      4         2  3       3  2      4      5
(%o3)            y  + 5 x y  + 10 x  y  + 10 x  y  + 5 x  y + x
(%i4) poly_expand(-1-x*exp(y)+x^2/sqrt(y),[x]);
                                          2
                                  y      x
(%o4)                       - x %e  + ------- - 1
                                       sqrt(y)

(%i5) poly_expand(-1-sin(x)^2+sin(x),[sin(x)]);
                                2
(%o5)                      - sin (x) + sin(x) - 1

Функция: poly_expt (poly, number, varlist)

возводит многочлен poly в положительную целую степень number. Если number не есть целое положительное число, то сигнализируется ошибка.

(%i1) poly_expt(x-y,3,[x,y])-(x-y)^3,expand;
(%o1)                                  0
Функция: poly_content (poly. varlist)

poly_content вычисляет НОД коэффициентов многочлена

(%i1) poly_content(35*y+21*x,[x,y]);
(%o1)                                  7
Функция: poly_pseudo_divide (poly, polylist, varlist)

Псевдо-деление многочлена poly на список из n многочленов polylist. Возвращает несколько значений. Первое значение – список частных a. Второе значение – остаток r. Третье значение – скалярный коэффициент c, такой что c*poly делимо на polylist в кольце коэффициентов, не обязательно являющимся полем. И наконец, четвертое значение – целое число, дающее число выполненных приведение. Результирующие величины удовлетворяют выражению:

c*poly=sum(a[i]*polylist[i],i=1...n)+r.

Функция: poly_exact_divide (poly1, poly2, varlist)

Делит многочлен poly1 на многочлен poly2. Предполагается, что деление без остатка возможно. Возвращает частное.

Функция: poly_normal_form (poly, polylist, varlist)

Функция poly_normal_form вычисляет нормальную форму многочлена poly по отношению к множеству многочленов polylist.

Функция: poly_buchberger_criterion (polylist, varlist)

Возвращает true если polylist является базисом Гребнера с учетом текущего упорядочивания членов. Использует критерий Бухбергера: для любых двух многочленов h1 и h2 из polylist e S-многочлен S(h1,h2) приводим к 0 по модулю polylist.

Функция: poly_buchberger (polylist_fl varlist)

poly_buchberger применяет алгоритм Бухбергера к списку многочленов и возвращает результирующий базис Гребнера.

51.2.4 Стандартная пост-обработка для базиса Гребнера

Идеал k-го исключения I_k идеала I над K[ x[1],...,x[n] ] есть идеал intersect(I, K[ x[k+1],...,x[n] ]).
Частное идеалов I:J есть идеал {h| для всех w в J: w*h в I}.
Идеал I:p^inf есть идеал {h| существует n в N: p^n*h в I}.
Идеал I:J^inf есть идеал {h| существуют n в N и p в J: p^n*h в I}.
Радикал идеала sqrt(I) есть идеал {h| существует n в N : h^n в I }.

Функция: poly_reduction (polylist, varlist)

poly_reduction приводит список многочленов polylist, так что каждый многочлен полностью приведен по отношению к другим.

Функция: poly_minimization (polylist, varlist)

Возвращает подмножество списка многочленов polylist, порождающих тот же мономиальный идеал, что и polylist но минимальный, т.е. старшие одночлены многочленов из подмножества не делят ни один из других старших одночленов других многочленов этого подмножества.

Функция: poly_normalize_list (polylist, varlist)

poly_normalize_list применяет poly_normalize к каждому многочлену в списке. Т.е. делит каждый из многочленов списка polylist на его старший коэффициент.

Функция: poly_grobner (polylist, varlist)

Возвращает базис Гребнера идеала, порожденного многочленами polylist. Зависит от глобальных флагов.

Функция: poly_reduced_grobner (polylist, varlist)

Возвращает приведенный базис Гребнера идеала, порожденного многочленами polylist. Зависит от глобальных флагов.

Функция: poly_depends_p (poly, var, varlist)

poly_depends проверяет, зависит ли многочлен от переменной var.

Функция: poly_elimination_ideal (polylist, number, varlist)

poly_elimination_ideal возвращает базис Гребнера идеала number-го исключения идеала, порожденного списком многочленов (не обязательно образующих базис Гребнера).

Функция: poly_colon_ideal (polylist1, polylist2, varlist)

Возвращает приведенный базис Гребнера частного идеала

I(polylist1):I(polylist2)

где polylist1 и polylist2 – два списка многочленов.

Функция: poly_ideal_intersection (polylist1, polylist2, varlist)

poly_ideal_intersection возвращает пересечение двух идеалов.

Функция: poly_lcm (poly1, poly2, varlist)

Возвращает наименьший общий множитель многочленов poly1 и poly2.

Функция: poly_gcd (poly1, poly2, varlist)

Возвращает наибольший общий делитель многочленов poly1 и poly2.

Функция: poly_grobner_equal (polylist1, polylist2, varlist)

poly_grobner_equal проверяет порождают ли два базиса Гребнера один и тот же идеал. Возвращает true если два списка многочленов polylist1 и polylist2, предполагаемые базисами Гребнера, порождают один и тот же идеал, и false в противном случае. Это эквивалентно проверке, что каждый многочлен первого базиса приводится к 0 по модулю второго и обратно. Заметим, что в примере ниже первый список не есть базис Гребнера, и по этому результат есть false.

(%i1) poly_grobner_equal([y+x,x-y],[x,y],[x,y]);
(%o1)                         false
Функция: poly_grobner_subsetp (polylist1, polylist2, varlist)

poly_grobner_subsetp проверяет содержится ли идеал, порожденный polylist1, в идеале, порожденном polylist2. Чтобы тест всегда выполнялся, нужно чтобы polylist2 был бы базисом Гребнера.

Функция: poly_grobner_member (poly, polylist, varlist)

Возвращает true, если многочлен poly принадлежит к идеалу, порожденному списком многочленов polylist, который предполагается базисом Гребнера. Иначе возвращает false.

Функция: poly_ideal_saturation1 (polylist, poly, varlist)

Возвращает приведенный базис Гребнера насыщения идеала

I(polylist):poly^inf

Геометрически, над алгебраически замкнутым полем, это есть множество многочленов в идеале, порожденном polylist, которые не исчезают на многообразии poly.

Функция: poly_ideal_saturation (polylist1, polylist2, varlist)

Возвращает приведенный базис Гребнера насыщения идеала

I(polylist1):I(polylist2)^inf

Геометрически, над алгебраически замкнутым полем, это есть множество многочленов в идеале, порожденном polylist1, которые не исчезают на многообразии polylist2.

Функция: poly_ideal_polysaturation1 (polylist1, polylist2, varlist)

polylist2 – есть список n многочленов [poly1,...,polyn]. Возвращает приведенный базис Гребнера идеала

I(polylist):poly1^inf:...:polyn^inf

полученного последовательным насыщением многочленами из списка polylist2 идеала, порожденного списком многочленов polylist1.

Функция: poly_ideal_polysaturation (polylist, polylistlist, varlist)

polylistlist – есть список n списков многочленов [polylist1,...,polylistn]. Возвращает приведенный базис Гребнера насыщения идеала

I(polylist):I(polylist_1)^inf:...:I(polylist_n)^inf

Функция: poly_saturation_extension (poly, polylist, varlist1, varlist2)

poly_saturation_extension реализует знаменитый трюк Рабиновича.

Функция: poly_polysaturation_extension (poly, polylist, varlist1, varlist2)

Next: , Previous: Пакет grobner, Up: Top   [Contents][Index]

52 Пакет impdiff


Previous: Пакет impdiff, Up: Пакет impdiff   [Contents][Index]

52.1 Функции и переменные пакета impdiff

Функция: implicit_derivative (f,indvarlist,orderlist,depvar)

Эта процедура вычисляет неявную производную функции многих переменных. f – функция-массив, с индексами, обозначающими порядок производных по переменным из indvarlist; indvarlist – список независимых переменных; orderlist – требуемый порядок; и depvar – зависимая переменная.

Для того, чтобы использовать эту функцию, сначала напишите load("impdiff").


Next: , Previous: Пакет impdiff, Up: Top   [Contents][Index]

53 Пакет implicit_plot


Previous: Пакет implicit_plot, Up: Пакет implicit_plot   [Contents][Index]

53.1 Функции и переменные пакета implicit_plot

Функция: implicit_plot (expr, x_range, y_range)
Функция: implicit_plot ([expr_1, ..., expr_n], x_range, y_range)

Строит график одного или более неявных выражений. expr – изображаемое выражение, x_range – пределы по горизонтальной оси, y_range – пределы по вертикальной оси. implicit_plot учитывает глобальные установки для gnuplot, задаваемые при помощи функции set_plot_option. Опции могут быть указаны в implicit_plot как дополнительные необязательные аргументы.

Функция implicit_plot работает, отслеживая изменения знака в области, заданной пределами x_range и y_range, и может ошибаться в сложных случаях.

Команда load("implicit_plot") загружает данную функцию.

Пример:

(%i1) implicit_plot (x^2 = y^3 - 3*y + 1, [x, -4, 4], [y, -4, 4],
 [gnuplot_preamble, "set zeroaxis"]);

Next: , Previous: Пакет implicit_plot, Up: Top   [Contents][Index]

54 Пакет interpol


Next: , Previous: Пакет interpol, Up: Пакет interpol   [Contents][Index]

54.1 Введение в пакет interpol

Пакет interpol определяет методы Лагранжа, линейный и и метод кубических сплайнов для полиномиальной интерполяции.

С комментариями, сообщениями об ошибках и предложениями, пожалуйста обращайтесь ко мне по адресу ’mario AT edu DOT xunta DOT es’.


Previous: Введение в пакет interpol, Up: Пакет interpol   [Contents][Index]

54.2 Функции и переменные пакета interpol

Функция: lagrange (points)
Функция: lagrange (points, option)

Вычисляет полиномиальную интерполяцию методом Лагранжа. Аргумент points должен быть либо:

В первых двух случаях, перед проведением вычислений, пары упорядочиваются в соответствии со значением первой координаты.

Аргумент option позволяет выбрать имя независимой переменной, по умолчанию равной 'x. Чтобы задать другую переменную напишите varname='z.

Отметим, что при работе с многочленами высокого порядка, вычисления с плавающей точкой нестабильны.

Примеры:

(%i1) load("interpol")$
(%i2) p:[[7,2],[8,2],[1,5],[3,2],[6,7]]$
(%i3) lagrange(p);
                 4        3         2
             73 x    701 x    8957 x    5288 x   186
(%o3)        ----- - ------ + ------- - ------ + ---
              420     210       420      105      5
(%i4) f(x):=''%;
                     4        3         2
                 73 x    701 x    8957 x    5288 x   186
(%o4)    f(x) := ----- - ------ + ------- - ------ + ---
                  420     210       420      105      5
(%i5) /* Evaluate the polynomial at some points */
      map(f,[2.3,5/7,%pi]);
                             919062
(%o5)  [- 1.567534999999992, ------,
                             84035
                         4          3           2
                   73 %pi    701 %pi    8957 %pi    5288 %pi   186
                   ------- - -------- + --------- - -------- + ---]
                     420       210         420        105       5
(%i6) %,numer;
(%o6) [- 1.567534999999992, 10.9366573451538, 2.89319655125692]
(%i7) load("draw")$  /* load draw package */
(%i8) /* Plot the polynomial together with points */
      draw2d(
        color      = red,
        key        = "Lagrange polynomial",
        explicit(f(x),x,0,10),
        point_size = 3,
        color      = blue,
        key        = "Sample points",
        points(p))$
(%i9) /* Change variable name */
      lagrange(p, varname=w);
                 4        3         2
             73 w    701 w    8957 w    5288 w   186
(%o9)        ----- - ------ + ------- - ------ + ---
              420     210       420      105      5
Функция: charfun2 (x, a, b)

Возвращает true если число x принадлежит интервалу [a, b), и false в противном случае.

Функция: linearinterpol (points)
Функция: linearinterpol (points, option)

Вычисляет полиномиальную интерполяцию линейным методом. Аргумент points должен быть либо:

В первых двух случаях, перед проведением вычислений, пары упорядочиваются в соответствии со значением первой координаты.

Аргумент option позволяет выбрать имя независимой переменной, по умолчанию равной 'x. Чтобы задать другую переменную напишите varname='z.

Примеры:

(%i1) load("interpol")$
(%i2) p: matrix([7,2],[8,3],[1,5],[3,2],[6,7])$
(%i3) linearinterpol(p);
        13   3 x
(%o3)  (-- - ---) charfun2(x, minf, 3)
        2     2
 + (x - 5) charfun2(x, 7, inf) + (37 - 5 x) charfun2(x, 6, 7)
    5 x
 + (--- - 3) charfun2(x, 3, 6)
     3

(%i4) f(x):=''%;
                13   3 x
(%o4)  f(x) := (-- - ---) charfun2(x, minf, 3)
                2     2
 + (x - 5) charfun2(x, 7, inf) + (37 - 5 x) charfun2(x, 6, 7)
    5 x
 + (--- - 3) charfun2(x, 3, 6)
     3
(%i5)  /* Evaluate the polynomial at some points */
       map(f,[7.3,25/7,%pi]);
                            62  5 %pi
(%o5)                 [2.3, --, ----- - 3]
                            21    3
(%i6) %,numer;
(%o6)  [2.3, 2.952380952380953, 2.235987755982989]
(%i7) load("draw")$  /* load draw package */
(%i8)  /* Plot the polynomial together with points */
       draw2d(
         color      = red,
         key        = "Linear interpolator",
         explicit(f(x),x,-5,20),
         point_size = 3,
         color      = blue,
         key        = "Sample points",
         points(args(p)))$
(%i9)  /* Change variable name */
       linearinterpol(p, varname='s);
       13   3 s
(%o9) (-- - ---) charfun2(s, minf, 3)
       2     2
 + (s - 5) charfun2(s, 7, inf) + (37 - 5 s) charfun2(s, 6, 7)
    5 s
 + (--- - 3) charfun2(s, 3, 6)
     3
Функция: cspline (points)
Функция: cspline (points, option1, option2, ...)

Вычисляет полиномиальную интерполяцию методом кубических сплайнов. Аргумент points должен быть либо:

В первых двух случаях, перед проведением вычислений, пары упорядочиваются в соответствии со значением первой координаты.

Существует три специальные опции:

Примеры:

(%i1) load("interpol")$
(%i2) p:[[7,2],[8,2],[1,5],[3,2],[6,7]]$
(%i3) /* Unknown first derivatives at the extremes
         is equivalent to natural cubic splines */
      cspline(p);
              3         2
        1159 x    1159 x    6091 x   8283
(%o3)  (------- - ------- - ------ + ----) charfun2(x, minf, 3)
         3288      1096      3288    1096
            3         2
      2587 x    5174 x    494117 x   108928
 + (- ------- + ------- - -------- + ------) charfun2(x, 7, inf)
       1644       137       1644      137
          3          2
    4715 x    15209 x    579277 x   199575
 + (------- - -------- + -------- - ------) charfun2(x, 6, 7)
     1644       274        1644      274
            3         2
      3287 x    2223 x    48275 x   9609
 + (- ------- + ------- - ------- + ----) charfun2(x, 3, 6)
       4932       274      1644     274

(%i4) f(x):=''%$
(%i5) /* Some evaluations */
      map(f,[2.3,5/7,%pi]), numer;
(%o5) [1.991460766423356, 5.823200187269903, 2.227405312429507]
(%i6) load("draw")$  /* load draw package */
(%i7) /* Plotting interpolating function */
      draw2d(
        color      = red,
        key        = "Cubic splines",
        explicit(f(x),x,0,10),
        point_size = 3,
        color      = blue,
        key        = "Sample points",
        points(p))$
(%i8) /* New call, but giving values at the derivatives */
      cspline(p,d1=0,dn=0);
              3          2
        1949 x    11437 x    17027 x   1247
(%o8)  (------- - -------- + ------- + ----) charfun2(x, minf, 3)
         2256       2256      2256     752
            3          2
      1547 x    35581 x    68068 x   173546
 + (- ------- + -------- - ------- + ------) charfun2(x, 7, inf)
        564       564        141      141
         3          2
    607 x    35147 x    55706 x   38420
 + (------ - -------- + ------- - -----) charfun2(x, 6, 7)
     188       564        141      47
            3         2
      3895 x    1807 x    5146 x   2148
 + (- ------- + ------- - ------ + ----) charfun2(x, 3, 6)
       5076       188      141      47
(%i8) /* Defining new interpolating function */
      g(x):=''%$
(%i9) /* Plotting both functions together */
      draw2d(
        color      = black,
        key        = "Cubic splines (default)",
        explicit(f(x),x,0,10),
        color      = red,
        key        = "Cubic splines (d1=0,dn=0)",
        explicit(g(x),x,0,10),
        point_size = 3,
        color      = blue,
        key        = "Sample points",
        points(p))$

Next: , Previous: Пакет interpol, Up: Top   [Contents][Index]

55 lapack


Next: , Previous: lapack-pkg, Up: lapack-pkg   [Contents][Index]

55.1 Introduction to lapack

lapack is a Common Lisp translation (via the program f2cl) of the Fortran library LAPACK, as obtained from the SLATEC project.


Previous: Introduction to lapack, Up: lapack-pkg   [Contents][Index]

55.2 Functions and Variables for lapack

Function: dgeev
    dgeev (A)
    dgeev (A, right_p, left_p)

Computes the eigenvalues and, optionally, the eigenvectors of a matrix A. All elements of A must be integer or floating point numbers. A must be square (same number of rows and columns). A might or might not be symmetric.

dgeev(A) computes only the eigenvalues of A. dgeev(A, right_p, left_p) computes the eigenvalues of A and the right eigenvectors when right_p = true and the left eigenvectors when left_p = true.

A list of three items is returned. The first item is a list of the eigenvalues. The second item is false or the matrix of right eigenvectors. The third item is false or the matrix of left eigenvectors.

The right eigenvector v(j) (the j-th column of the right eigenvector matrix) satisfies

A . v(j) = lambda(j) . v(j)

where lambda(j) is the corresponding eigenvalue. The left eigenvector u(j) (the j-th column of the left eigenvector matrix) satisfies

u(j)**H . A = lambda(j) . u(j)**H

where u(j)**H denotes the conjugate transpose of u(j). The Maxima function ctranspose computes the conjugate transpose.

The computed eigenvectors are normalized to have Euclidean norm equal to 1, and largest component has imaginary part equal to zero.

Example:

(%i1) load ("lapack")$
(%i2) fpprintprec : 6;
(%o2)                           6
(%i3) M : matrix ([9.5, 1.75], [3.25, 10.45]);
                         [ 9.5   1.75  ]
(%o3)                    [             ]
                         [ 3.25  10.45 ]
(%i4) dgeev (M);
(%o4)          [[7.54331, 12.4067], false, false]
(%i5) [L, v, u] : dgeev (M, true, true);
                           [ - .666642  - .515792 ]
(%o5) [[7.54331, 12.4067], [                      ], 
                           [  .745378   - .856714 ]
                                        [ - .856714  - .745378 ]
                                        [                      ]]
                                        [  .515792   - .666642 ]
(%i6) D : apply (diag_matrix, L);
                      [ 7.54331     0    ]
(%o6)                 [                  ]
                      [    0     12.4067 ]
(%i7) M . v - v . D;
                [      0.0       - 8.88178E-16 ]
(%o7)           [                              ]
                [ - 8.88178E-16       0.0      ]
(%i8) transpose (u) . M - D . transpose (u);
                     [ 0.0  - 4.44089E-16 ]
(%o8)                [                    ]
                     [ 0.0       0.0      ]
Function: dgeqrf (A)

Computes the QR decomposition of the matrix A. All elements of A must be integer or floating point numbers. A may or may not have the same number of rows and columns.

A list of two items is returned. The first item is the matrix Q, which is a square, orthonormal matrix which has the same number of rows as A. The second item is the matrix R, which is the same size as A, and which has all elements equal to zero below the diagonal. The product Q . R, where "." is the noncommutative multiplication operator, is equal to A (ignoring floating point round-off errors).

(%i1) load ("lapack") $
(%i2) fpprintprec : 6 $
(%i3) M : matrix ([1, -3.2, 8], [-11, 2.7, 5.9]) $
(%i4) [q, r] : dgeqrf (M);
       [ - .0905357  .995893  ]
(%o4) [[                      ], 
       [  .995893    .0905357 ]
                               [ - 11.0454   2.97863   5.15148 ]
                               [                               ]]
                               [     0      - 2.94241  8.50131 ]
(%i5) q . r - M;
         [ - 7.77156E-16   1.77636E-15   - 8.88178E-16 ]
(%o5)    [                                             ]
         [      0.0       - 1.33227E-15   8.88178E-16  ]
(%i6) mat_norm (%, 1);
(%o6)                      3.10862E-15
Function: dgesv (A, b)

Computes the solution x of the linear equation A x = b, where A is a square matrix, and b is a matrix of the same number of rows as A and any number of columns. The return value x is the same size as b.

The elements of A and b must evaluate to real floating point numbers via float; thus elements may be any numeric type, symbolic numerical constants, or expressions which evaluate to floats. The elements of x are always floating point numbers. All arithmetic is carried out as floating point operations.

dgesv computes the solution via the LU decomposition of A.

Examples:

dgesv computes the solution of the linear equation A x = b.

(%i1) A : matrix ([1, -2.5], [0.375, 5]);
                               [   1    - 2.5 ]
(%o1)                          [              ]
                               [ 0.375    5   ]
(%i2) b : matrix ([1.75], [-0.625]);
                                  [  1.75   ]
(%o2)                             [         ]
                                  [ - 0.625 ]
(%i3) x : dgesv (A, b);
                            [  1.210526315789474  ]
(%o3)                       [                     ]
                            [ - 0.215789473684211 ]
(%i4) dlange (inf_norm, b - A.x);
(%o4)                                 0.0

b is a matrix with the same number of rows as A and any number of columns. x is the same size as b.

(%i1) A : matrix ([1, -0.15], [1.82, 2]);
                               [  1    - 0.15 ]
(%o1)                          [              ]
                               [ 1.82    2    ]
(%i2) b : matrix ([3.7, 1, 8], [-2.3, 5, -3.9]);
                              [  3.7   1    8   ]
(%o2)                         [                 ]
                              [ - 2.3  5  - 3.9 ]
(%i3) x : dgesv (A, b);
      [  3.103827540695117  1.20985481742191    6.781786185657722 ]
(%o3) [                                                           ]
      [ -3.974483062032557  1.399032116146062  -8.121425428948527 ]
(%i4) dlange (inf_norm, b - A . x);
(%o4)                       1.1102230246251565E-15

The elements of A and b must evaluate to real floating point numbers.

(%i1) A : matrix ([5, -%pi], [1b0, 11/17]);
                               [   5    - %pi ]
                               [              ]
(%o1)                          [         11   ]
                               [ 1.0b0   --   ]
                               [         17   ]
(%i2) b : matrix ([%e], [sin(1)]);
                                  [   %e   ]
(%o2)                             [        ]
                                  [ sin(1) ]
(%i3) x : dgesv (A, b);
                             [ 0.690375643155986 ]
(%o3)                        [                   ]
                             [ 0.233510982552952 ]
(%i4) dlange (inf_norm, b - A . x);
(%o4)                        2.220446049250313E-16
Function: dgesvd
    dgesvd (A)
    dgesvd (A, left_p, right_p)

Computes the singular value decomposition (SVD) of a matrix A, comprising the singular values and, optionally, the left and right singular vectors. All elements of A must be integer or floating point numbers. A might or might not be square (same number of rows and columns).

Let m be the number of rows, and n the number of columns of A. The singular value decomposition of A comprises three matrices, U, Sigma, and V^T, such that

A = U . Sigma . V^T

where U is an m-by-m unitary matrix, Sigma is an m-by-n diagonal matrix, and V^T is an n-by-n unitary matrix.

Let sigma[i] be a diagonal element of Sigma, that is, Sigma[i, i] = sigma[i]. The elements sigma[i] are the so-called singular values of A; these are real and nonnegative, and returned in descending order. The first min(m, n) columns of U and V are the left and right singular vectors of A. Note that dgesvd returns the transpose of V, not V itself.

dgesvd(A) computes only the singular values of A. dgesvd(A, left_p, right_p) computes the singular values of A and the left singular vectors when left_p = true and the right singular vectors when right_p = true.

A list of three items is returned. The first item is a list of the singular values. The second item is false or the matrix of left singular vectors. The third item is false or the matrix of right singular vectors.

Example:

(%i1) load ("lapack")$
(%i2) fpprintprec : 6;
(%o2)                           6
(%i3) M: matrix([1, 2, 3], [3.5, 0.5, 8], [-1, 2, -3], [4, 9, 7]);
                        [  1    2    3  ]
                        [               ]
                        [ 3.5  0.5   8  ]
(%o3)                   [               ]
                        [ - 1   2   - 3 ]
                        [               ]
                        [  4    9    7  ]
(%i4) dgesvd (M);
(%o4)      [[14.4744, 6.38637, .452547], false, false]
(%i5) [sigma, U, VT] : dgesvd (M, true, true);
(%o5) [[14.4744, 6.38637, .452547], 
[ - .256731  .00816168   .959029    - .119523 ]
[                                             ]
[ - .526456   .672116   - .206236   - .478091 ]
[                                             ], 
[  .107997   - .532278  - .0708315  - 0.83666 ]
[                                             ]
[ - .803287  - .514659  - .180867    .239046  ]
[ - .374486  - .538209  - .755044 ]
[                                 ]
[  .130623   - .836799   0.5317   ]]
[                                 ]
[ - .917986   .100488    .383672  ]
(%i6) m : length (U);
(%o6)                           4
(%i7) n : length (VT);
(%o7)                           3
(%i8) Sigma:
        genmatrix(lambda ([i, j], if i=j then sigma[i] else 0),
                  m, n);
                  [ 14.4744     0        0    ]
                  [                           ]
                  [    0     6.38637     0    ]
(%o8)             [                           ]
                  [    0        0     .452547 ]
                  [                           ]
                  [    0        0        0    ]
(%i9) U . Sigma . VT - M;
          [  1.11022E-15        0.0       1.77636E-15 ]
          [                                           ]
          [  1.33227E-15    1.66533E-15       0.0     ]
(%o9)     [                                           ]
          [ - 4.44089E-16  - 8.88178E-16  4.44089E-16 ]
          [                                           ]
          [  8.88178E-16    1.77636E-15   8.88178E-16 ]
(%i10) transpose (U) . U;
       [     1.0      5.55112E-17    2.498E-16     2.77556E-17  ]
       [                                                        ]
       [ 5.55112E-17      1.0       5.55112E-17    4.16334E-17  ]
(%o10) [                                                        ]
       [  2.498E-16   5.55112E-17       1.0       - 2.08167E-16 ]
       [                                                        ]
       [ 2.77556E-17  4.16334E-17  - 2.08167E-16       1.0      ]
(%i11) VT . transpose (VT);
          [      1.0           0.0      - 5.55112E-17 ]
          [                                           ]
(%o11)    [      0.0           1.0       5.55112E-17  ]
          [                                           ]
          [ - 5.55112E-17  5.55112E-17       1.0      ]
Function: dlange (norm, A)
Function: zlange (norm, A)

Computes a norm or norm-like function of the matrix A. If A is a real matrix, use dlange. For a matrix with complex elements, use zlange.

norm specifies the kind of norm to be computed:

max

Compute max(abs(A(i, j))) where i and j range over the rows and columns, respectively, of A. Note that this function is not a proper matrix norm.

one_norm

Compute the L[1] norm of A, that is, the maximum of the sum of the absolute value of elements in each column.

inf_norm

Compute the L[inf] norm of A, that is, the maximum of the sum of the absolute value of elements in each row.

frobenius

Compute the Frobenius norm of A, that is, the square root of the sum of squares of the matrix elements.

Function: dgemm
    dgemm (A, B)
    dgemm (A, B, options)

Compute the product of two matrices and optionally add the product to a third matrix.

In the simplest form, dgemm(A, B) computes the product of the two real matrices, A and B.

In the second form, dgemm computes the alpha * A * B + beta * C where A, B, C are real matrices of the appropriate sizes and alpha and beta are real numbers. Optionally, A and/or B can be transposed before computing the product. The extra parameters are specified by optional keyword arguments: The keyword arguments are optional and may be specified in any order. They all take the form key=val. The keyword arguments are:

C

The matrix C that should be added. The default is false, which means no matrix is added.

alpha

The product of A and B is multiplied by this value. The default is 1.

beta

If a matrix C is given, this value multiplies C before it is added. The default value is 0, which implies that C is not added, even if C is given. Hence, be sure to specify a non-zero value for beta.

transpose_a

If true, the transpose of A is used instead of A for the product. The default is false.

transpose_b

If true, the transpose of B is used instead of B for the product. The default is false.

(%i1) load ("lapack")$
(%i2) A : matrix([1,2,3],[4,5,6],[7,8,9]);
                                  [ 1  2  3 ]
                                  [         ]
(%o2)                             [ 4  5  6 ]
                                  [         ]
                                  [ 7  8  9 ]
(%i3) B : matrix([-1,-2,-3],[-4,-5,-6],[-7,-8,-9]);
                               [ - 1  - 2  - 3 ]
                               [               ]
(%o3)                          [ - 4  - 5  - 6 ]
                               [               ]
                               [ - 7  - 8  - 9 ]
(%i4) C : matrix([3,2,1],[6,5,4],[9,8,7]);
                                  [ 3  2  1 ]
                                  [         ]
(%o4)                             [ 6  5  4 ]
                                  [         ]
                                  [ 9  8  7 ]
(%i5) dgemm(A,B);
                         [ - 30.0   - 36.0   - 42.0  ]
                         [                           ]
(%o5)                    [ - 66.0   - 81.0   - 96.0  ]
                         [                           ]
                         [ - 102.0  - 126.0  - 150.0 ]
(%i6) A . B;
                            [ - 30   - 36   - 42  ]
                            [                     ]
(%o6)                       [ - 66   - 81   - 96  ]
                            [                     ]
                            [ - 102  - 126  - 150 ]
(%i7) dgemm(A,B,transpose_a=true);
                         [ - 66.0  - 78.0   - 90.0  ]
                         [                          ]
(%o7)                    [ - 78.0  - 93.0   - 108.0 ]
                         [                          ]
                         [ - 90.0  - 108.0  - 126.0 ]
(%i8) transpose(A) . B;
                           [ - 66  - 78   - 90  ]
                           [                    ]
(%o8)                      [ - 78  - 93   - 108 ]
                           [                    ]
                           [ - 90  - 108  - 126 ]
(%i9) dgemm(A,B,c=C,beta=1);
                         [ - 27.0  - 34.0   - 41.0  ]
                         [                          ]
(%o9)                    [ - 60.0  - 76.0   - 92.0  ]
                         [                          ]
                         [ - 93.0  - 118.0  - 143.0 ]
(%i10) A . B + C;
                            [ - 27  - 34   - 41  ]
                            [                    ]
(%o10)                      [ - 60  - 76   - 92  ]
                            [                    ]
                            [ - 93  - 118  - 143 ]
(%i11) dgemm(A,B,c=C,beta=1, alpha=-1);
                            [ 33.0   38.0   43.0  ]
                            [                     ]
(%o11)                      [ 72.0   86.0   100.0 ]
                            [                     ]
                            [ 111.0  134.0  157.0 ]
(%i12) -A . B + C;
                               [ 33   38   43  ]
                               [               ]
(%o12)                         [ 72   86   100 ]
                               [               ]
                               [ 111  134  157 ]

Function: zgeev
    zgeev (A)
    zgeev (A, right_p, left_p)

Like dgeev, but the matrix A is complex.

Function: zheev
    zheev (A)
    zheev (A, eigvec_p)

Like dgeev, but the matrix A is assumed to be a square complex Hermitian matrix. If eigvec_p is true, then the eigenvectors of the matrix are also computed.

No check is made that the matrix A is, in fact, Hermitian.

A list of two items is returned, as in dgeev: a list of eigenvalues, and false or the matrix of the eigenvectors.

An example of computing the eigenvalues and then eigenvalues and eigenvectors of an Hermitian matrix.

(%i1) load("lapack")$
(%i2) A: matrix(
     [9.14 +%i*0.00 ,   -4.37 -%i*9.22 ,  -1.98 -%i*1.72 ,  -8.96 -%i*9.50],
     [-4.37 +%i*9.22 ,  -3.35 +%i*0.00 ,   2.25 -%i*9.51 ,   2.57 +%i*2.40],
     [-1.98 +%i*1.72 ,   2.25 +%i*9.51 ,  -4.82 +%i*0.00 ,  -3.24 +%i*2.04],
     [-8.96 +%i*9.50 ,   2.57 -%i*2.40 ,  -3.24 -%i*2.04 ,   8.44 +%i*0.00]);
(%o2) 
  [      9.14       (- 9.22 %i) - 4.37  (- 1.72 %i) - 1.98  (- 9.5 %i) - 8.96 ]
  [                                                                           ]
  [ 9.22 %i - 4.37        - 3.35          2.25 - 9.51 %i      2.4 %i + 2.57   ]
  [                                                                           ]
  [ 1.72 %i - 1.98    9.51 %i + 2.25          - 4.82         2.04 %i - 3.24   ]
  [                                                                           ]
  [ 9.5 %i - 8.96     2.57 - 2.4 %i     (- 2.04 %i) - 3.24        8.44        ]
(%i3) zheev(A);
(%o3) [[- 16.00474647209473, - 6.764970154793324, 6.665711453507098, 
                                                     25.51400517338097], false]
(%i4) E:zheev(A,true)$
(%i5) E[1];
(%o5) [- 16.00474647209474, - 6.764970154793325, 6.665711453507101, 
                                                             25.51400517338096]
(%i6) E[2];
               [   0.2674650533172745 %i + 0.2175453586665017    ]
               [                                                 ]
               [  0.002696730886619885 %i + 0.6968836773391712   ]
(%o6)  Col 1 = [                                                 ]
               [ (- 0.6082406376714117 %i) - 0.01210614292697931 ]
               [                                                 ]
               [               0.1593081858095037                ]
         [   0.2644937470667444 %i + 0.4773693349937472   ]
         [                                                ]
         [ (- 0.2852389036031621 %i) - 0.1414362742011673 ]
 Col 2 = [                                                ]
         [   0.2654607680986639 %i + 0.4467818117184174   ]
         [                                                ]
         [               0.5750762708542709               ]
         [   0.2810649767305922 %i - 0.1335263928245182   ]
         [                                                ]
         [   0.2866310132869556 %i - 0.4536971347853274   ]
 Col 3 = [                                                ]
         [ (- 0.2933684323754295 %i) - 0.4954972425541057 ]
         [                                                ]
         [               0.5325337537576771               ]
         [ (- 0.5737316575503476 %i) - 0.3966146799427706 ]
         [                                                ]
         [  0.01826502619021457 %i + 0.3530557704387017   ]
 Col 4 = [                                                ]
         [  0.1673700900085425 %i + 0.01476684746229564   ]
         [                                                ]
         [               0.6002632636961784               ]

Next: , Previous: lapack-pkg, Up: Top   [Contents][Index]

56 lbfgs


Next: , Up: lbfgs-pkg   [Contents][Index]

56.1 Introduction to lbfgs

lbfgs is an implementation of the L-BFGS algorithm [1] to solve unconstrained minimization problems via a limited-memory quasi-Newton (BFGS) algorithm. It is called a limited-memory method because a low-rank approximation of the Hessian matrix inverse is stored instead of the entire Hessian inverse. The program was originally written in Fortran [2] by Jorge Nocedal, incorporating some functions originally written by Jorge J. Moré and David J. Thuente, and translated into Lisp automatically via the program f2cl. The Maxima package lbfgs comprises the translated code plus an interface function which manages some details.

References:

[1] D. Liu and J. Nocedal. "On the limited memory BFGS method for large scale optimization". Mathematical Programming B 45:503–528 (1989)

[2] https://www.netlib.org/opt/lbfgs_um.shar


Previous: Introduction to lbfgs, Up: lbfgs-pkg   [Contents][Index]

56.2 Functions and Variables for lbfgs

Function: lbfgs
    lbfgs (FOM, X, X0, epsilon, iprint)
    lbfgs ([FOM, grad] X, X0, epsilon, iprint)

Finds an approximate solution of the unconstrained minimization of the figure of merit FOM over the list of variables X, starting from initial estimates X0, such that norm(grad(FOM)) < epsilon*max(1, norm(X)).

grad, if present, is the gradient of FOM with respect to the variables X. grad may be a list or a function that returns a list, with one element for each element of X. If not present, the gradient is computed automatically by symbolic differentiation. If FOM is a function, the gradient grad must be supplied by the user.

The algorithm applied is a limited-memory quasi-Newton (BFGS) algorithm [1]. It is called a limited-memory method because a low-rank approximation of the Hessian matrix inverse is stored instead of the entire Hessian inverse. Each iteration of the algorithm is a line search, that is, a search along a ray in the variables X, with the search direction computed from the approximate Hessian inverse. The FOM is always decreased by a successful line search. Usually (but not always) the norm of the gradient of FOM also decreases.

iprint controls progress messages printed by lbfgs.

iprint[1]

iprint[1] controls the frequency of progress messages.

iprint[1] < 0

No progress messages.

iprint[1] = 0

Messages at the first and last iterations.

iprint[1] > 0

Print a message every iprint[1] iterations.

iprint[2]

iprint[2] controls the verbosity of progress messages.

iprint[2] = 0

Print out iteration count, number of evaluations of FOM, value of FOM, norm of the gradient of FOM, and step length.

iprint[2] = 1

Same as iprint[2] = 0, plus X0 and the gradient of FOM evaluated at X0.

iprint[2] = 2

Same as iprint[2] = 1, plus values of X at each iteration.

iprint[2] = 3

Same as iprint[2] = 2, plus the gradient of FOM at each iteration.

The columns printed by lbfgs are the following.

I

Number of iterations. It is incremented for each line search.

NFN

Number of evaluations of the figure of merit.

FUNC

Value of the figure of merit at the end of the most recent line search.

GNORM

Norm of the gradient of the figure of merit at the end of the most recent line search.

STEPLENGTH

An internal parameter of the search algorithm.

Additional information concerning details of the algorithm are found in the comments of the original Fortran code [2].

See also lbfgs_nfeval_max and lbfgs_ncorrections.

References:

[1] D. Liu and J. Nocedal. "On the limited memory BFGS method for large scale optimization". Mathematical Programming B 45:503–528 (1989)

[2] https://www.netlib.org/opt/lbfgs_um.shar

Examples:

The same FOM as computed by FGCOMPUTE in the program sdrive.f in the LBFGS package from Netlib. Note that the variables in question are subscripted variables. The FOM has an exact minimum equal to zero at u[k] = 1 for k = 1, ..., 8.

(%i1) load ("lbfgs")$
(%i2) t1[j] := 1 - u[j];
(%o2)                     t1  := 1 - u
                            j         j
(%i3) t2[j] := 10*(u[j + 1] - u[j]^2);
                                          2
(%o3)                t2  := 10 (u      - u )
                       j         j + 1    j
(%i4) n : 8;
(%o4)                           8
(%i5) FOM : sum (t1[2*j - 1]^2 + t2[2*j - 1]^2, j, 1, n/2);
                 2 2           2              2 2           2
(%o5) 100 (u  - u )  + (1 - u )  + 100 (u  - u )  + (1 - u )
            8    7           7           6    5           5
                     2 2           2              2 2           2
        + 100 (u  - u )  + (1 - u )  + 100 (u  - u )  + (1 - u )
                4    3           3           2    1           1
(%i6) lbfgs (FOM, '[u[1],u[2],u[3],u[4],u[5],u[6],u[7],u[8]],
       [-1.2, 1, -1.2, 1, -1.2, 1, -1.2, 1], 1e-3, [1, 0]);
*************************************************
  N=    8   NUMBER OF CORRECTIONS=25
       INITIAL VALUES
 F=  9.680000000000000D+01   GNORM=  4.657353755084533D+02
*************************************************
 I NFN   FUNC                    GNORM                   STEPLENGTH

 1   3   1.651479526340304D+01   4.324359291335977D+00   7.926153934390631D-04
 2   4   1.650209316638371D+01   3.575788161060007D+00   1.000000000000000D+00
 3   5   1.645461701312851D+01   6.230869903601577D+00   1.000000000000000D+00
 4   6   1.636867301275588D+01   1.177589920974980D+01   1.000000000000000D+00
 5   7   1.612153014409201D+01   2.292797147151288D+01   1.000000000000000D+00
 6   8   1.569118407390628D+01   3.687447158775571D+01   1.000000000000000D+00
 7   9   1.510361958398942D+01   4.501931728123679D+01   1.000000000000000D+00
 8  10   1.391077875774293D+01   4.526061463810630D+01   1.000000000000000D+00
 9  11   1.165625686278198D+01   2.748348965356907D+01   1.000000000000000D+00
10  12   9.859422687859144D+00   2.111494974231706D+01   1.000000000000000D+00
11  13   7.815442521732282D+00   6.110762325764183D+00   1.000000000000000D+00
12  15   7.346380905773044D+00   2.165281166715009D+01   1.285316401779678D-01
13  16   6.330460634066464D+00   1.401220851761508D+01   1.000000000000000D+00
14  17   5.238763939854303D+00   1.702473787619218D+01   1.000000000000000D+00
15  18   3.754016790406625D+00   7.981845727632704D+00   1.000000000000000D+00
16  20   3.001238402313225D+00   3.925482944745832D+00   2.333129631316462D-01
17  22   2.794390709722064D+00   8.243329982586480D+00   2.503577283802312D-01
18  23   2.563783562920545D+00   1.035413426522664D+01   1.000000000000000D+00
19  24   2.019429976373283D+00   1.065187312340952D+01   1.000000000000000D+00
20  25   1.428003167668592D+00   2.475962450735100D+00   1.000000000000000D+00
21  27   1.197874264859232D+00   8.441707983339661D+00   4.303451060697367D-01
22  28   9.023848942003913D-01   1.113189216665625D+01   1.000000000000000D+00
23  29   5.508226405855795D-01   2.380830599637816D+00   1.000000000000000D+00
24  31   3.902893258879521D-01   5.625595817143044D+00   4.834988416747262D-01
25  32   3.207542206881058D-01   1.149444645298493D+01   1.000000000000000D+00
26  33   1.874468266118200D-01   3.632482152347445D+00   1.000000000000000D+00
27  34   9.575763380282112D-02   4.816497449000391D+00   1.000000000000000D+00
28  35   4.085145106760390D-02   2.087009347116811D+00   1.000000000000000D+00
29  36   1.931106005512628D-02   3.886818624052740D+00   1.000000000000000D+00
30  37   6.894000636920714D-03   3.198505769992936D+00   1.000000000000000D+00
31  38   1.443296008850287D-03   1.590265460381961D+00   1.000000000000000D+00
32  39   1.571766574930155D-04   3.098257002223532D-01   1.000000000000000D+00
33  40   1.288011779655132D-05   1.207784334505595D-02   1.000000000000000D+00
34  41   1.806140190993455D-06   4.587890258846915D-02   1.000000000000000D+00
35  42   1.769004612050548D-07   1.790537363138099D-02   1.000000000000000D+00
36  43   3.312164244118216D-10   6.782068546986653D-04   1.000000000000000D+00
 THE MINIMIZATION TERMINATED WITHOUT DETECTING ERRORS.
 IFLAG = 0
(%o6) [u  = 1.000005339816132, u  = 1.000009942840108, 
        1                       2
u  = 1.000005339816132, u  = 1.000009942840108, 
 3                       4
u  = 1.000005339816132, u  = 1.000009942840108, 
 5                       6
u  = 1.000005339816132, u  = 1.000009942840108]
 7                       8

A regression problem. The FOM is the mean square difference between the predicted value F(X[i]) and the observed value Y[i]. The function F is a bounded monotone function (a so-called "sigmoidal" function). In this example, lbfgs computes approximate values for the parameters of F and plot2d displays a comparison of F with the observed data.

(%i1) load ("lbfgs")$
(%i2) FOM : '((1/length(X))*sum((F(X[i]) - Y[i])^2, i, 1,
                                                length(X)));
                               2
               sum((F(X ) - Y ) , i, 1, length(X))
                       i     i
(%o2)          -----------------------------------
                            length(X)
(%i3) X : [1, 2, 3, 4, 5];
(%o3)                    [1, 2, 3, 4, 5]
(%i4) Y : [0, 0.5, 1, 1.25, 1.5];
(%o4)                [0, 0.5, 1, 1.25, 1.5]
(%i5) F(x) := A/(1 + exp(-B*(x - C)));
                                   A
(%o5)            F(x) := ----------------------
                         1 + exp((- B) (x - C))
(%i6) ''FOM;
                A               2            A                2
(%o6) ((----------------- - 1.5)  + (----------------- - 1.25)
          - B (5 - C)                  - B (4 - C)
        %e            + 1            %e            + 1
            A             2            A               2
 + (----------------- - 1)  + (----------------- - 0.5)
      - B (3 - C)                - B (2 - C)
    %e            + 1          %e            + 1
             2
            A
 + --------------------)/5
      - B (1 - C)     2
   (%e            + 1)
(%i7) estimates : lbfgs (FOM, '[A, B, C], [1, 1, 1], 1e-4, [1, 0]);
*************************************************
  N=    3   NUMBER OF CORRECTIONS=25
       INITIAL VALUES
 F=  1.348738534246918D-01   GNORM=  2.000215531936760D-01
*************************************************

I  NFN  FUNC                    GNORM                   STEPLENGTH
1    3  1.177820636622582D-01   9.893138394953992D-02   8.554435968992371D-01  
2    6  2.302653892214013D-02   1.180098521565904D-01   2.100000000000000D+01  
3    8  1.496348495303004D-02   9.611201567691624D-02   5.257340567840710D-01  
4    9  7.900460841091138D-03   1.325041647391314D-02   1.000000000000000D+00  
5   10  7.314495451266914D-03   1.510670810312226D-02   1.000000000000000D+00  
6   11  6.750147275936668D-03   1.914964958023037D-02   1.000000000000000D+00  
7   12  5.850716021108202D-03   1.028089194579382D-02   1.000000000000000D+00  
8   13  5.778664230657800D-03   3.676866074532179D-04   1.000000000000000D+00  
9   14  5.777818823650780D-03   3.010740179797108D-04   1.000000000000000D+00  
 THE MINIMIZATION TERMINATED WITHOUT DETECTING ERRORS.
 IFLAG = 0
(%o7) [A = 1.461933911464101, B = 1.601593973254801, 
                                           C = 2.528933072164855]
(%i8) plot2d ([F(x), [discrete, X, Y]], [x, -1, 6]), ''estimates;
(%o8) 

Gradient of FOM is specified (instead of computing it automatically). Both the FOM and its gradient are passed as functions to lbfgs.

(%i1) load ("lbfgs")$
(%i2) F(a, b, c) := (a - 5)^2 + (b - 3)^4 + (c - 2)^6$
(%i3) define(F_grad(a, b, c),
             map (lambda ([x], diff (F(a, b, c), x)), [a, b, c]))$
(%i4) estimates : lbfgs ([F, F_grad],
                   [a, b, c], [0, 0, 0], 1e-4, [1, 0]);
*************************************************
  N=    3   NUMBER OF CORRECTIONS=25
       INITIAL VALUES
 F=  1.700000000000000D+02   GNORM=  2.205175729958953D+02
*************************************************

   I  NFN     FUNC                    GNORM                   STEPLENGTH

   1    2     6.632967565917637D+01   6.498411132518770D+01   4.534785987412505D-03  
   2    3     4.368890936228036D+01   3.784147651974131D+01   1.000000000000000D+00  
   3    4     2.685298972775191D+01   1.640262125898520D+01   1.000000000000000D+00  
   4    5     1.909064767659852D+01   9.733664001790506D+00   1.000000000000000D+00  
   5    6     1.006493272061515D+01   6.344808151880209D+00   1.000000000000000D+00  
   6    7     1.215263596054292D+00   2.204727876126877D+00   1.000000000000000D+00  
   7    8     1.080252896385329D-02   1.431637116951845D-01   1.000000000000000D+00  
   8    9     8.407195124830860D-03   1.126344579730008D-01   1.000000000000000D+00  
   9   10     5.022091686198525D-03   7.750731829225275D-02   1.000000000000000D+00  
  10   11     2.277152808939775D-03   5.032810859286796D-02   1.000000000000000D+00  
  11   12     6.489384688303218D-04   1.932007150271009D-02   1.000000000000000D+00  
  12   13     2.075791943844547D-04   6.964319310814365D-03   1.000000000000000D+00  
  13   14     7.349472666162258D-05   4.017449067849554D-03   1.000000000000000D+00  
  14   15     2.293617477985238D-05   1.334590390856715D-03   1.000000000000000D+00  
  15   16     7.683645404048675D-06   6.011057038099202D-04   1.000000000000000D+00  
 THE MINIMIZATION TERMINATED WITHOUT DETECTING ERRORS.
 IFLAG = 0
(%o4) [a = 5.000086823042934, b = 3.052395429705181, 
                                           c = 1.927980629919583]
Variable: lbfgs_nfeval_max

Default value: 100

lbfgs_nfeval_max is the maximum number of evaluations of the figure of merit (FOM) in lbfgs. When lbfgs_nfeval_max is reached, lbfgs returns the result of the last successful line search.

Variable: lbfgs_ncorrections

Default value: 25

lbfgs_ncorrections is the number of corrections applied to the approximate inverse Hessian matrix which is maintained by lbfgs.


Next: , Previous: lbfgs-pkg, Up: Top   [Contents][Index]

57 lindstedt


Previous: lindstedt-pkg, Up: lindstedt-pkg   [Contents][Index]

57.1 Functions and Variables for lindstedt

Function: Lindstedt (eq,pvar,torder,ic)

This is a first pass at a Lindstedt code. It can solve problems with initial conditions entered, which can be arbitrary constants, (just not %k1 and %k2) where the initial conditions on the perturbation equations are z[i]=0, z'[i]=0 for i>0. ic is the list of initial conditions.

Problems occur when initial conditions are not given, as the constants in the perturbation equations are the same as the zero order equation solution. Also, problems occur when the initial conditions for the perturbation equations are not z[i]=0, z'[i]=0 for i>0, such as the Van der Pol equation.

Example:

(%i1) load("makeOrders")$

(%i2) load("lindstedt")$

(%i3) Lindstedt('diff(x,t,2)+x-(e*x^3)/6,e,2,[1,0]);
          2
         e  (cos(5 T) - 24 cos(3 T) + 23 cos(T))
(%o3) [[[---------------------------------------
                          36864
   e (cos(3 T) - cos(T))
 - --------------------- + cos(T)],
            192
          2
       7 e    e
T = (- ---- - -- + 1) t]]
       3072   16

To use this function write first load("makeOrders") and load("lindstedt").


Next: , Previous: lindstedt-pkg, Up: Top   [Contents][Index]

58 linearalgebra


Next: , Up: linearalgebra-pkg   [Contents][Index]

58.1 Introduction to linearalgebra

linearalgebra is a collection of functions for linear algebra.

Example:

(%i1) M : matrix ([1, 2], [1, 2]);
                            [ 1  2 ]
(%o1)                       [      ]
                            [ 1  2 ]
(%i2) nullspace (M);
                               [  1  ]
                               [     ]
(%o2)                     span([   1 ])
                               [ - - ]
                               [   2 ]
(%i3) columnspace (M);
                                [ 1 ]
(%o3)                      span([   ])
                                [ 1 ]
(%i4) ptriangularize (M - z*ident(2), z);
                         [ 1   2 - z   ]
(%o4)                    [             ]
                         [           2 ]
                         [ 0  3 z - z  ]
(%i5) M : matrix ([1, 2, 3], [4, 5, 6], [7, 8, 9]) - z*ident(3);
                     [ 1 - z    2      3   ]
                     [                     ]
(%o5)                [   4    5 - z    6   ]
                     [                     ]
                     [   7      8    9 - z ]
(%i6) MM : ptriangularize (M, z);
              [ 4  5 - z            6            ]
              [                                  ]
              [                2                 ]
              [     66        z    102 z   132   ]
              [ 0   --      - -- + ----- + ---   ]
(%o6)         [     49        7     49     49    ]
              [                                  ]
              [               3        2         ]
              [           49 z    245 z    147 z ]
              [ 0    0    ----- - ------ - ----- ]
              [            264      88      44   ]
(%i7) algebraic : true;
(%o7)                         true
(%i8) tellrat (MM [3, 3]);
                         3       2
(%o8)                  [z  - 15 z  - 18 z]
(%i9) MM : ratsimp (MM);
               [ 4  5 - z           6           ]
               [                                ]
               [                2               ]
(%o9)          [     66      7 z  - 102 z - 132 ]
               [ 0   --    - ------------------ ]
               [     49              49         ]
               [                                ]
               [ 0    0             0           ]
(%i10) nullspace (MM);
                        [        1         ]
                        [                  ]
                        [   2              ]
                        [  z  - 14 z - 16  ]
                        [  --------------  ]
(%o10)             span([        8         ])
                        [                  ]
                        [    2             ]
                        [   z  - 18 z - 12 ]
                        [ - -------------- ]
                        [         12       ]
(%i11) M : matrix ([1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12],
                   [13, 14, 15, 16]);
                       [ 1   2   3   4  ]
                       [                ]
                       [ 5   6   7   8  ]
(%o11)                 [                ]
                       [ 9   10  11  12 ]
                       [                ]
                       [ 13  14  15  16 ]
(%i12) columnspace (M);
                           [ 1  ]  [ 2  ]
                           [    ]  [    ]
                           [ 5  ]  [ 6  ]
(%o12)                span([    ], [    ])
                           [ 9  ]  [ 10 ]
                           [    ]  [    ]
                           [ 13 ]  [ 14 ]
(%i13) apply ('orthogonal_complement, args (nullspace (transpose (M))));
                           [ 0 ]  [  1  ]
                           [   ]  [     ]
                           [ 1 ]  [  0  ]
(%o13)                span([   ], [     ])
                           [ 2 ]  [ - 1 ]
                           [   ]  [     ]
                           [ 3 ]  [ - 2 ]

Previous: Introduction to linearalgebra, Up: linearalgebra-pkg   [Contents][Index]

58.2 Functions and Variables for linearalgebra

Function: addmatrices (f, M_1, …, M_n)

Using the function f as the addition function, return the sum of the matrices M_1, …, M_n. The function f must accept any number of arguments (a Maxima nary function).

Examples:

(%i1) m1 : matrix([1,2],[3,4])$
(%i2) m2 : matrix([7,8],[9,10])$
(%i3) addmatrices('max,m1,m2);
(%o3) matrix([7,8],[9,10])
(%i4) addmatrices('max,m1,m2,5*m1);
(%o4) matrix([7,10],[15,20])
Function: blockmatrixp (M)

Return true if and only if M is a matrix and every entry of M is a matrix.

Function: columnop (M, i, j, theta)

If M is a matrix, return the matrix that results from doing the column operation C_i <- C_i - theta * C_j. If M doesn’t have a row i or j, signal an error.

Function: columnswap (M, i, j)

If M is a matrix, swap columns i and j. If M doesn’t have a column i or j, signal an error.

Function: columnspace (M)

If M is a matrix, return span (v_1, ..., v_n), where the set {v_1, ..., v_n} is a basis for the column space of M. The span of the empty set is {0}. Thus, when the column space has only one member, return span ().

Function: cholesky
    cholesky (M)
    cholesky (M, field)

Return the Cholesky factorization of the matrix selfadjoint (or hermitian) matrix M. The second argument defaults to ’generalring.’ For a description of the possible values for field, see lu_factor.

Function: ctranspose (M)

Return the complex conjugate transpose of the matrix M. The function ctranspose uses matrix_element_transpose to transpose each matrix element.

Function: diag_matrix (d_1, d_2, …, d_n)

Return a diagonal matrix with diagonal entries d_1, d_2, …, d_n. When the diagonal entries are matrices, the zero entries of the returned matrix are zero matrices of the appropriate size; for example:

(%i1) diag_matrix(diag_matrix(1,2),diag_matrix(3,4));

                            [ [ 1  0 ]  [ 0  0 ] ]
                            [ [      ]  [      ] ]
                            [ [ 0  2 ]  [ 0  0 ] ]
(%o1)                       [                    ]
                            [ [ 0  0 ]  [ 3  0 ] ]
                            [ [      ]  [      ] ]
                            [ [ 0  0 ]  [ 0  4 ] ]
(%i2) diag_matrix(p,q);

                                   [ p  0 ]
(%o2)                              [      ]
                                   [ 0  q ]
Function: dotproduct (u, v)

Return the dotproduct of vectors u and v. This is the same as conjugate (transpose (u)) . v. The arguments u and v must be column vectors.

Function: eigens_by_jacobi
    eigens_by_jacobi (A)
    eigens_by_jacobi (A, field_type)

Computes the eigenvalues and eigenvectors of A by the method of Jacobi rotations. A must be a symmetric matrix (but it need not be positive definite nor positive semidefinite). field_type indicates the computational field, either floatfield or bigfloatfield. If field_type is not specified, it defaults to floatfield.

The elements of A must be numbers or expressions which evaluate to numbers via float or bfloat (depending on field_type).

Examples:

(%i1) S: matrix([1/sqrt(2), 1/sqrt(2)],[-1/sqrt(2), 1/sqrt(2)]);
                     [     1         1    ]
                     [  -------   ------- ]
                     [  sqrt(2)   sqrt(2) ]
(%o1)                [                    ]
                     [      1        1    ]
                     [ - -------  ------- ]
                     [   sqrt(2)  sqrt(2) ]
(%i2) L : matrix ([sqrt(3), 0], [0, sqrt(5)]);
                      [ sqrt(3)     0    ]
(%o2)                 [                  ]
                      [    0     sqrt(5) ]
(%i3) M : S . L . transpose (S);
            [ sqrt(5)   sqrt(3)  sqrt(5)   sqrt(3) ]
            [ ------- + -------  ------- - ------- ]
            [    2         2        2         2    ]
(%o3)       [                                      ]
            [ sqrt(5)   sqrt(3)  sqrt(5)   sqrt(3) ]
            [ ------- - -------  ------- + ------- ]
            [    2         2        2         2    ]
(%i4) eigens_by_jacobi (M);
The largest percent change was 0.1454972243679
The largest percent change was 0.0
number of sweeps: 2
number of rotations: 1
(%o4) [[1.732050807568877, 2.23606797749979], 
                        [  0.70710678118655   0.70710678118655 ]
                        [                                      ]]
                        [ - 0.70710678118655  0.70710678118655 ]
(%i5) float ([[sqrt(3), sqrt(5)], S]);
(%o5) [[1.732050807568877, 2.23606797749979], 
                        [  0.70710678118655   0.70710678118655 ]
                        [                                      ]]
                        [ - 0.70710678118655  0.70710678118655 ]
(%i6) eigens_by_jacobi (M, bigfloatfield);
The largest percent change was 1.454972243679028b-1
The largest percent change was 0.0b0
number of sweeps: 2
number of rotations: 1
(%o6) [[1.732050807568877b0, 2.23606797749979b0], 
                [  7.071067811865475b-1   7.071067811865475b-1 ]
                [                                              ]]
                [ - 7.071067811865475b-1  7.071067811865475b-1 ]
Function: get_lu_factors (x)

When x = lu_factor (A), then get_lu_factors returns a list of the form [P, L, U], where P is a permutation matrix, L is lower triangular with ones on the diagonal, and U is upper triangular, and A = P L U.

Function: hankel
    hankel (col)
    hankel (col, row)

Return a Hankel matrix H. The first column of H is col; except for the first entry, the last row of H is row. The default for row is the zero vector with the same length as col.

Function: hessian (f, x)

Returns the Hessian matrix of f with respect to the list of variables x. The (i, j)-th element of the Hessian matrix is diff(f, x[i], 1, x[j], 1).

Examples:

(%i1) hessian (x * sin (y), [x, y]);
                     [   0       cos(y)   ]
(%o1)                [                    ]
                     [ cos(y)  - x sin(y) ]
(%i2) depends (F, [a, b]);
(%o2)                       [F(a, b)]
(%i3) hessian (F, [a, b]);
                        [   2      2   ]
                        [  d F    d F  ]
                        [  ---   ----- ]
                        [    2   da db ]
                        [  da          ]
(%o3)                   [              ]
                        [   2      2   ]
                        [  d F    d F  ]
                        [ -----   ---  ]
                        [ da db     2  ]
                        [         db   ]
Function: hilbert_matrix (n)

Return the n by n Hilbert matrix. When n isn’t a positive integer, signal an error.

Function: identfor
    identfor (M)
    identfor (M, fld)

Return an identity matrix that has the same shape as the matrix M. The diagonal entries of the identity matrix are the multiplicative identity of the field fld; the default for fld is generalring.

The first argument M should be a square matrix or a non-matrix. When M is a matrix, each entry of M can be a square matrix – thus M can be a blocked Maxima matrix. The matrix can be blocked to any (finite) depth.

See also zerofor

Function: invert_by_lu (M, (rng generalring))

Invert a matrix M by using the LU factorization. The LU factorization is done using the ring rng.

Function: jacobian (f, x)

Returns the Jacobian matrix of the list of functions f with respect to the list of variables x. The (i, j)-th element of the Jacobian matrix is diff(f[i], x[j]).

Examples:

(%i1) jacobian ([sin (u - v), sin (u * v)], [u, v]);
                  [ cos(v - u)  - cos(v - u) ]
(%o1)             [                          ]
                  [ v cos(u v)   u cos(u v)  ]
(%i2) depends ([F, G], [y, z]);
(%o2)                  [F(y, z), G(y, z)]
(%i3) jacobian ([F, G], [y, z]);
                           [ dF  dF ]
                           [ --  -- ]
                           [ dy  dz ]
(%o3)                      [        ]
                           [ dG  dG ]
                           [ --  -- ]
                           [ dy  dz ]
Function: kronecker_product (A, B)

Return the Kronecker product of the matrices A and B.

Function: listp
    listp (e, p)
    listp (e)

Given an optional argument p, return true if e is a Maxima list and p evaluates to true for every list element. When listp is not given the optional argument, return true if e is a Maxima list. In all other cases, return false.

Function: locate_matrix_entry (M, r_1, c_1, r_2, c_2, f, rel)

The first argument must be a matrix; the arguments r_1 through c_2 determine a sub-matrix of M that consists of rows r_1 through r_2 and columns c_1 through c_2.

Find an entry in the sub-matrix M that satisfies some property. Three cases:

(1) rel = 'bool and f a predicate:

Scan the sub-matrix from left to right then top to bottom, and return the index of the first entry that satisfies the predicate f. If no matrix entry satisfies f, return false.

(2) rel = 'max and f real-valued:

Scan the sub-matrix looking for an entry that maximizes f. Return the index of a maximizing entry.

(3) rel = 'min and f real-valued:

Scan the sub-matrix looking for an entry that minimizes f. Return the index of a minimizing entry.

Function: lu_backsub (M, b)

When M = lu_factor (A, field), then lu_backsub (M, b) solves the linear system A x = b.

The n by m matrix b, with n the number of rows of the matrix A, contains one right hand side per column. If there is only one right hand side then b must be a n by 1 matrix.

Each column of the matrix x=lu_backsub (M, b) is the solution corresponding to the respective column of b.

Examples:

(%i1) A : matrix ([1 - z, 3], [3, 8 - z]);
                               [ 1 - z    3   ]
(%o1)                          [              ]
                               [   3    8 - z ]
(%i2) M : lu_factor (A,generalring);
               [ 1 - z          3         ]
               [                          ]
(%o2)         [[   3              9       ], [1, 2], generalring]
               [ -----  (- z) - ----- + 8 ]
               [ 1 - z          1 - z     ]
(%i3) b : matrix([a],[c]);
                                     [ a ]
(%o3)                                [   ]
                                     [ c ]
(%i4) x : lu_backsub(M,b);
                           [               3 a     ]
                           [       3 (c - -----)   ]
                           [              1 - z    ]
                           [ a - ----------------- ]
                           [               9       ]
                           [     (- z) - ----- + 8 ]
                           [             1 - z     ]
                           [ --------------------- ]
(%o4)                      [         1 - z         ]
                           [                       ]
                           [            3 a        ]
                           [       c - -----       ]
                           [           1 - z       ]
                           [   -----------------   ]
                           [             9         ]
                           [   (- z) - ----- + 8   ]
                           [           1 - z       ]
(%i5) ratsimp(A . x - b);
                                     [ 0 ]
(%o5)                                [   ]
                                     [ 0 ]
(%i6) B : matrix([a,d],[c,f]);
                                   [ a  d ]
(%o6)                              [      ]
                                   [ c  f ]
(%i7) x : lu_backsub(M,B);
               [               3 a                    3 d     ]
               [       3 (c - -----)          3 (f - -----)   ]
               [              1 - z                  1 - z    ]
               [ a - -----------------  d - ----------------- ]
               [               9                      9       ]
               [     (- z) - ----- + 8      (- z) - ----- + 8 ]
               [             1 - z                  1 - z     ]
               [ ---------------------  --------------------- ]
(%o7)          [         1 - z                  1 - z         ]
               [                                              ]
               [            3 a                    3 d        ]
               [       c - -----              f - -----       ]
               [           1 - z                  1 - z       ]
               [   -----------------      -----------------   ]
               [             9                      9         ]
               [   (- z) - ----- + 8      (- z) - ----- + 8   ]
               [           1 - z                  1 - z       ]
(%i8) ratsimp(A . x - B);
                                   [ 0  0 ]
(%o8)                              [      ]
                                   [ 0  0 ]
Function: lu_factor (M, field)

Return a list of the form [LU, perm, fld], or [LU, perm, fld, lower-cnd upper-cnd], where

(1) The matrix LU contains the factorization of M in a packed form. Packed form means three things: First, the rows of LU are permuted according to the list perm. If, for example, perm is the list [3,2,1], the actual first row of the LU factorization is the third row of the matrix LU. Second, the lower triangular factor of m is the lower triangular part of LU with the diagonal entries replaced by all ones. Third, the upper triangular factor of M is the upper triangular part of LU.

(2) When the field is either floatfield or complexfield, the numbers lower-cnd and upper-cnd are lower and upper bounds for the infinity norm condition number of M. For all fields, the condition number might not be estimated; for such fields, lu_factor returns a two item list. Both the lower and upper bounds can differ from their true values by arbitrarily large factors. (See also mat_cond.)

The argument M must be a square matrix.

The optional argument fld must be a symbol that determines a ring or field. The pre-defined fields and rings are:

(a) generalring – the ring of Maxima expressions,

(b) floatfield – the field of floating point numbers of the type double,

(c) complexfield – the field of complex floating point numbers of the type double,

(d) crering – the ring of Maxima CRE expressions,

(e) rationalfield – the field of rational numbers,

(f) runningerror – track the all floating point rounding errors,

(g) noncommutingring – the ring of Maxima expressions where multiplication is the non-commutative dot operator.

When the field is floatfield, complexfield, or runningerror, the algorithm uses partial pivoting; for all other fields, rows are switched only when needed to avoid a zero pivot.

Floating point addition arithmetic isn’t associative, so the meaning of ’field’ differs from the mathematical definition.

A member of the field runningerror is a two member Maxima list of the form [x,n],where x is a floating point number and n is an integer. The relative difference between the ’true’ value of x and x is approximately bounded by the machine epsilon times n. The running error bound drops some terms that of the order the square of the machine epsilon.

There is no user-interface for defining a new field. A user that is familiar with Common Lisp should be able to define a new field. To do this, a user must define functions for the arithmetic operations and functions for converting from the field representation to Maxima and back. Additionally, for ordered fields (where partial pivoting will be used), a user must define functions for the magnitude and for comparing field members. After that all that remains is to define a Common Lisp structure mring. The file mring has many examples.

To compute the factorization, the first task is to convert each matrix entry to a member of the indicated field. When conversion isn’t possible, the factorization halts with an error message. Members of the field needn’t be Maxima expressions. Members of the complexfield, for example, are Common Lisp complex numbers. Thus after computing the factorization, the matrix entries must be converted to Maxima expressions.

See also get_lu_factors.

Examples:

(%i1) w[i,j] := random (1.0) + %i * random (1.0);
(%o1)          w     := random(1.) + %i random(1.)
                i, j
(%i2) showtime : true$
Evaluation took 0.00 seconds (0.00 elapsed)
(%i3) M : genmatrix (w, 100, 100)$
Evaluation took 7.40 seconds (8.23 elapsed)
(%i4) lu_factor (M, complexfield)$
Evaluation took 28.71 seconds (35.00 elapsed)
(%i5) lu_factor (M, generalring)$
Evaluation took 109.24 seconds (152.10 elapsed)
(%i6) showtime : false$

(%i7) M : matrix ([1 - z, 3], [3, 8 - z]); 
                        [ 1 - z    3   ]
(%o7)                   [              ]
                        [   3    8 - z ]
(%i8) lu_factor (M, generalring);
          [ 1 - z         3        ]
          [                        ]
(%o8)    [[   3            9       ], [1, 2], generalring]
          [ -----  - z - ----- + 8 ]
          [ 1 - z        1 - z     ]
(%i9) get_lu_factors (%);
                  [   1    0 ]  [ 1 - z         3        ]
        [ 1  0 ]  [          ]  [                        ]
(%o9)  [[      ], [   3      ], [                9       ]]
        [ 0  1 ]  [ -----  1 ]  [   0    - z - ----- + 8 ]
                  [ 1 - z    ]  [              1 - z     ]
(%i10) %[1] . %[2] . %[3];
                        [ 1 - z    3   ]
(%o10)                  [              ]
                        [   3    8 - z ]
Function: mat_cond
    mat_cond (M, 1)
    mat_cond (M, inf)

Return the p-norm matrix condition number of the matrix m. The allowed values for p are 1 and inf. This function uses the LU factorization to invert the matrix m. Thus the running time for mat_cond is proportional to the cube of the matrix size; lu_factor determines lower and upper bounds for the infinity norm condition number in time proportional to the square of the matrix size.

Function: mat_norm
    mat_norm (M, 1)
    mat_norm (M, inf)
    mat_norm (M, frobenius)

Return the matrix p-norm of the matrix M. The allowed values for p are 1, inf, and frobenius (the Frobenius matrix norm). The matrix M should be an unblocked matrix.

Function: matrixp
    matrixp (e, p)
    matrixp (e)

Given an optional argument p, return true if e is a matrix and p evaluates to true for every matrix element. When matrixp is not given an optional argument, return true if e is a matrix. In all other cases, return false.

See also blockmatrixp

Function: matrix_size (M)

Return a two member list that gives the number of rows and columns, respectively of the matrix M.

Function: mat_fullunblocker (M)

If M is a block matrix, unblock the matrix to all levels. If M is a matrix, return M; otherwise, signal an error.

Function: mat_trace (M)

Return the trace of the matrix M. If M isn’t a matrix, return a noun form. When M is a block matrix, mat_trace(M) returns the same value as does mat_trace(mat_unblocker(m)).

Function: mat_unblocker (M)

If M is a block matrix, unblock M one level. If M is a matrix, mat_unblocker (M) returns M; otherwise, signal an error.

Thus if each entry of M is matrix, mat_unblocker (M) returns an unblocked matrix, but if each entry of M is a block matrix, mat_unblocker (M) returns a block matrix with one less level of blocking.

If you use block matrices, most likely you’ll want to set matrix_element_mult to "." and matrix_element_transpose to 'transpose. See also mat_fullunblocker.

Example:

(%i1) A : matrix ([1, 2], [3, 4]);
                            [ 1  2 ]
(%o1)                       [      ]
                            [ 3  4 ]
(%i2) B : matrix ([7, 8], [9, 10]);
                            [ 7  8  ]
(%o2)                       [       ]
                            [ 9  10 ]
(%i3) matrix ([A, B]);
                     [ [ 1  2 ]  [ 7  8  ] ]
(%o3)                [ [      ]  [       ] ]
                     [ [ 3  4 ]  [ 9  10 ] ]
(%i4) mat_unblocker (%);
                         [ 1  2  7  8  ]
(%o4)                    [             ]
                         [ 3  4  9  10 ]
Function: nullspace (M)

If M is a matrix, return span (v_1, ..., v_n), where the set {v_1, ..., v_n} is a basis for the nullspace of M. The span of the empty set is {0}. Thus, when the nullspace has only one member, return span ().

Function: nullity (M)

If M is a matrix, return the dimension of the nullspace of M.

Function: orthogonal_complement (v_1, …, v_n)

Return span (u_1, ..., u_m), where the set {u_1, ..., u_m} is a basis for the orthogonal complement of the set (v_1, ..., v_n).

Each vector v_1 through v_n must be a column vector.

Function: polytocompanion (p, x)

If p is a polynomial in x, return the companion matrix of p. For a monic polynomial p of degree n, we have p = (-1)^n charpoly (polytocompanion (p, x)).

When p isn’t a polynomial in x, signal an error.

Function: ptriangularize (M, v)

If M is a matrix with each entry a polynomial in v, return a matrix M2 such that

(1) M2 is upper triangular,

(2) M2 = E_n ... E_1 M, where E_1 through E_n are elementary matrices whose entries are polynomials in v,

(3) |det (M)| = |det (M2)|,

Note: This function doesn’t check that every entry is a polynomial in v.

Function: rowop (M, i, j, theta)

If M is a matrix, return the matrix that results from doing the row operation R_i <- R_i - theta * R_j. If M doesn’t have a row i or j, signal an error.

Function: linalg_rank (M)

Return the rank of the matrix M. This function is equivalent to function rank, but it uses a different algorithm: it finds the columnspace of the matrix and counts its elements, since the rank of a matrix is the dimension of its column space.

(%i1) linalg_rank(matrix([1,2],[2,4]));
(%o1)                           1
(%i2) linalg_rank(matrix([1,b],[c,d]));
(%o2)                           2
Function: rowswap (M, i, j)

If M is a matrix, swap rows i and j. If M doesn’t have a row i or j, signal an error.

Function: toeplitz
    toeplitz (col)
    toeplitz (col, row)

Return a Toeplitz matrix T. The first first column of T is col; except for the first entry, the first row of T is row. The default for row is complex conjugate of col. Example:

(%i1)  toeplitz([1,2,3],[x,y,z]);
                                  [ 1  y  z ]
                                  [         ]
(%o1)                             [ 2  1  y ]
                                  [         ]
                                  [ 3  2  1 ]
(%i2)  toeplitz([1,1+%i]);

                              [   1     1 - %I ]
(%o2)                         [                ]
                              [ %I + 1    1    ]
Function: vandermonde_matrix ([x_1, ..., x_n])

Return a n by n matrix whose i-th row is [1, x_i, x_i^2, ... x_i^(n-1)].

Function: zerofor
    zerofor (M)
    zerofor (M, fld)

Return a zero matrix that has the same shape as the matrix M. Every entry of the zero matrix is the additive identity of the field fld; the default for fld is generalring.

The first argument M should be a square matrix or a non-matrix. When M is a matrix, each entry of M can be a square matrix – thus M can be a blocked Maxima matrix. The matrix can be blocked to any (finite) depth.

See also identfor

Function: zeromatrixp (M)

If M is not a block matrix, return true if is (equal (e, 0)) is true for each element e of the matrix M. If M is a block matrix, return true if zeromatrixp evaluates to true for each element of e.


Next: , Previous: linearalgebra-pkg, Up: Top   [Contents][Index]

59 lsquares


Next: , Previous: lsquares-pkg, Up: lsquares-pkg   [Contents][Index]

59.1 Introduction to lsquares

lsquares is a collection of functions to implement the method of least squares to estimate parameters for a model from numerical data.


Previous: Introduction to lsquares, Up: lsquares-pkg   [Contents][Index]

59.2 Functions and Variables for lsquares

Function: lsquares_estimates
    lsquares_estimates (D, x, e, a)
    lsquares_estimates (D, x, e, a, initial = L, tol = t)

Estimate parameters a to best fit the equation e in the variables x and a to the data D, as determined by the method of least squares. lsquares_estimates first seeks an exact solution, and if that fails, then seeks an approximate solution.

The return value is a list of lists of equations of the form [a = ..., b = ..., c = ...]. Each element of the list is a distinct, equivalent minimum of the mean square error.

The data D must be a matrix. Each row is one datum (which may be called a ‘record’ or ‘case’ in some contexts), and each column contains the values of one variable across all data. The list of variables x gives a name for each column of D, even the columns which do not enter the analysis. The list of parameters a gives the names of the parameters for which estimates are sought. The equation e is an expression or equation in the variables x and a; if e is not an equation, it is treated the same as e = 0.

Additional arguments to lsquares_estimates are specified as equations and passed on verbatim to the function lbfgs which is called to find estimates by a numerical method when an exact result is not found.

If some exact solution can be found (via solve), the data D may contain non-numeric values. However, if no exact solution is found, each element of D must have a numeric value. This includes numeric constants such as %pi and %e as well as literal numbers (integers, rationals, ordinary floats, and bigfloats). Numerical calculations are carried out with ordinary floating-point arithmetic, so all other kinds of numbers are converted to ordinary floats for calculations.

If lsquares_estimates needs excessive amounts of time or runs out of memory lsquares_estimates_approximate, which skips the attempt to find an exact solution, might still succeed.

load("lsquares") loads this function.

See also lsquares_estimates_exact, lsquares_estimates_approximate,
lsquares_mse, lsquares_residuals, and lsquares_residual_mse.

Examples:

A problem for which an exact solution is found.

(%i1) load ("lsquares")$
(%i2) M : matrix (
        [1,1,1], [3/2,1,2], [9/4,2,1], [3,2,2], [2,2,1]);
                           [ 1  1  1 ]
                           [         ]
                           [ 3       ]
                           [ -  1  2 ]
                           [ 2       ]
                           [         ]
(%o2)                      [ 9       ]
                           [ -  2  1 ]
                           [ 4       ]
                           [         ]
                           [ 3  2  2 ]
                           [         ]
                           [ 2  2  1 ]
(%i3) lsquares_estimates (
         M, [z,x,y], (z+D)^2 = A*x+B*y+C, [A,B,C,D]);
                  59        27      10921        107
(%o3)     [[A = - --, B = - --, C = -----, D = - ---]]
                  16        16      1024         32

A problem for which no exact solution is found, so lsquares_estimates resorts to numerical approximation.

(%i1) load ("lsquares")$
(%i2) M : matrix ([1, 1], [2, 7/4], [3, 11/4], [4, 13/4]);
                            [ 1  1  ]
                            [       ]
                            [    7  ]
                            [ 2  -  ]
                            [    4  ]
                            [       ]
(%o2)                       [    11 ]
                            [ 3  -- ]
                            [    4  ]
                            [       ]
                            [    13 ]
                            [ 4  -- ]
                            [    4  ]
(%i3) lsquares_estimates (
  M, [x,y], y=a*x^b+c, [a,b,c], initial=[3,3,3], iprint=[-1,0]);
(%o3) [[a = 1.375751433061394, b = 0.7148891534417651, 
                                       c = - 0.4020908910062951]]

Exponential functions aren’t well-conditioned for least min square fitting. In case that fitting to them fails it might be possible to get rid of the exponential function using an logarithm.

(%i1) load ("lsquares")$
(%i2) yvalues: [1,3,5,60,200,203,80]$
(%i3) time: [1,2,4,5,6,8,10]$
(%i4) f: y=a*exp(b*t);
                                   b t
(%o4)                      y = a %e
(%i5) yvalues_log: log(yvalues)$
(%i6) f_log: log(subst(y=exp(y),f));
                                    b t
(%o6)                   y = log(a %e   )
(%i7) lsquares_estimates (transpose(matrix(yvalues_log,time)),
                          [y,t], f_log, [a,b]);
*************************************************
  N=    2   NUMBER OF CORRECTIONS=25
       INITIAL VALUES
 F=  6.802906290754687D+00   GNORM=  2.851243373781393D+01
*************************************************

I NFN FUNC                  GNORM                 STEPLENGTH

1   3 1.141838765593467D+00 1.067358003667488D-01 1.390943719972406D-02  
2   5 1.141118195694385D+00 1.237977833033414D-01 5.000000000000000D+00  
3   6 1.136945723147959D+00 3.806696991691383D-01 1.000000000000000D+00  
4   7 1.133958243220262D+00 3.865103550379243D-01 1.000000000000000D+00  
5   8 1.131725773805499D+00 2.292258231154026D-02 1.000000000000000D+00  
6   9 1.131625585698168D+00 2.664440547017370D-03 1.000000000000000D+00  
7  10 1.131620564856599D+00 2.519366958715444D-04 1.000000000000000D+00  

 THE MINIMIZATION TERMINATED WITHOUT DETECTING ERRORS.
 IFLAG = 0
(%o7)   [[a = 1.155904145765554, b = 0.5772666876959847]]
Function: lsquares_estimates_exact (MSE, a)

Estimate parameters a to minimize the mean square error MSE, by constructing a system of equations and attempting to solve them symbolically via solve. The mean square error is an expression in the parameters a, such as that returned by lsquares_mse.

The return value is a list of lists of equations of the form [a = ..., b = ..., c = ...]. The return value may contain zero, one, or two or more elements. If two or more elements are returned, each represents a distinct, equivalent minimum of the mean square error.

See also lsquares_estimates, lsquares_estimates_approximate, lsquares_mse, lsquares_residuals, and lsquares_residual_mse.

Example:

(%i1) load ("lsquares")$
(%i2) M : matrix (
         [1,1,1], [3/2,1,2], [9/4,2,1], [3,2,2], [2,2,1]);
                           [ 1  1  1 ]
                           [         ]
                           [ 3       ]
                           [ -  1  2 ]
                           [ 2       ]
                           [         ]
(%o2)                      [ 9       ]
                           [ -  2  1 ]
                           [ 4       ]
                           [         ]
                           [ 3  2  2 ]
                           [         ]
                           [ 2  2  1 ]
(%i3) mse : lsquares_mse (M, [z, x, y], (z + D)^2 = A*x + B*y + C);
         5
        ====
        \                                         2     2
         >    ((- B M    ) - A M     + (M     + D)  - C)
        /            i, 3       i, 2     i, 1
        ====
        i = 1
(%o3)   -------------------------------------------------
                                5
(%i4) lsquares_estimates_exact (mse, [A, B, C, D]);
                  59        27      10921        107
(%o4)     [[A = - --, B = - --, C = -----, D = - ---]]
                  16        16      1024         32
Function: lsquares_estimates_approximate (MSE, a, initial = L, tol = t)

Estimate parameters a to minimize the mean square error MSE, via the numerical minimization function lbfgs. The mean square error is an expression in the parameters a, such as that returned by lsquares_mse.

The solution returned by lsquares_estimates_approximate is a local (perhaps global) minimum of the mean square error. For consistency with lsquares_estimates_exact, the return value is a nested list which contains one element, namely a list of equations of the form [a = ..., b = ..., c = ...].

Additional arguments to lsquares_estimates_approximate are specified as equations and passed on verbatim to the function lbfgs.

MSE must evaluate to a number when the parameters are assigned numeric values. This requires that the data from which MSE was constructed comprise only numeric constants such as %pi and %e and literal numbers (integers, rationals, ordinary floats, and bigfloats). Numerical calculations are carried out with ordinary floating-point arithmetic, so all other kinds of numbers are converted to ordinary floats for calculations.

load("lsquares") loads this function.

See also lsquares_estimates, lsquares_estimates_exact, lsquares_mse,
lsquares_residuals, and lsquares_residual_mse.

Example:

(%i1) load ("lsquares")$
(%i2) M : matrix (
         [1,1,1], [3/2,1,2], [9/4,2,1], [3,2,2], [2,2,1]);
                           [ 1  1  1 ]
                           [         ]
                           [ 3       ]
                           [ -  1  2 ]
                           [ 2       ]
                           [         ]
(%o2)                      [ 9       ]
                           [ -  2  1 ]
                           [ 4       ]
                           [         ]
                           [ 3  2  2 ]
                           [         ]
                           [ 2  2  1 ]
(%i3) mse : lsquares_mse (M, [z, x, y], (z + D)^2 = A*x + B*y + C);
         5
        ====
        \                                         2     2
         >    ((- B M    ) - A M     + (M     + D)  - C)
        /            i, 3       i, 2     i, 1
        ====
        i = 1
(%o3)   -------------------------------------------------
                                5
(%i4) lsquares_estimates_approximate (
        mse, [A, B, C, D], iprint = [-1, 0]);
(%o4) [[A = - 3.678504947401971, B = - 1.683070351177937, 
                 C = 10.63469950148714, D = - 3.340357993175297]]
Function: lsquares_mse (D, x, e)

Returns the mean square error (MSE), a summation expression, for the equation e in the variables x, with data D.

The MSE is defined as:

                    n
                   ====
               1   \                        2
               -    >    (lhs(e ) - rhs(e ))
               n   /           i         i
                   ====
                   i = 1

where n is the number of data and e[i] is the equation e evaluated with the variables in x assigned values from the i-th datum, D[i].

load("lsquares") loads this function.

Example:

(%i1) load ("lsquares")$
(%i2) M : matrix (
         [1,1,1], [3/2,1,2], [9/4,2,1], [3,2,2], [2,2,1]);
                           [ 1  1  1 ]
                           [         ]
                           [ 3       ]
                           [ -  1  2 ]
                           [ 2       ]
                           [         ]
(%o2)                      [ 9       ]
                           [ -  2  1 ]
                           [ 4       ]
                           [         ]
                           [ 3  2  2 ]
                           [         ]
                           [ 2  2  1 ]
(%i3) mse : lsquares_mse (M, [z, x, y], (z + D)^2 = A*x + B*y + C);
         5
        ====
        \                                         2     2
         >    ((- B M    ) - A M     + (M     + D)  - C)
        /            i, 3       i, 2     i, 1
        ====
        i = 1
(%o3)   -------------------------------------------------
                                5
(%i4) diff (mse, D);
(%o4) 
      5
     ====
     \                                                     2
   4  >    (M     + D) ((- B M    ) - A M     + (M     + D)  - C)
     /       i, 1             i, 3       i, 2     i, 1
     ====
     i = 1
   --------------------------------------------------------------
                                 5
(%i5) ''mse, nouns;
               2                 2         9 2               2
(%o5) (((D + 3)  - C - 2 B - 2 A)  + ((D + -)  - C - B - 2 A)
                                           4
           2               2         3 2               2
 + ((D + 2)  - C - B - 2 A)  + ((D + -)  - C - 2 B - A)
                                     2
           2             2
 + ((D + 1)  - C - B - A) )/5
(%i3) mse : lsquares_mse (M, [z, x, y], (z + D)^2 = A*x + B*y + C);
           5
          ====
          \                 2                         2
           >    ((D + M    )  - C - M     B - M     A)
          /            i, 1          i, 3      i, 2
          ====
          i = 1
(%o3)     ---------------------------------------------
                                5
(%i4) diff (mse, D);
         5
        ====
        \                             2
      4  >    (D + M    ) ((D + M    )  - C - M     B - M     A)
        /           i, 1         i, 1          i, 3      i, 2
        ====
        i = 1
(%o4) ----------------------------------------------------------
                                  5
(%i5) ''mse, nouns;
               2                 2         9 2               2
(%o5) (((D + 3)  - C - 2 B - 2 A)  + ((D + -)  - C - B - 2 A)
                                           4
           2               2         3 2               2
 + ((D + 2)  - C - B - 2 A)  + ((D + -)  - C - 2 B - A)
                                     2
           2             2
 + ((D + 1)  - C - B - A) )/5
Function: lsquares_residuals (D, x, e, a)

Returns the residuals for the equation e with specified parameters a and data D.

D is a matrix, x is a list of variables, e is an equation or general expression; if not an equation, e is treated as if it were e = 0. a is a list of equations which specify values for any free parameters in e aside from x.

The residuals are defined as:

                        lhs(e ) - rhs(e )
                             i         i

where e[i] is the equation e evaluated with the variables in x assigned values from the i-th datum, D[i], and assigning any remaining free variables from a.

load("lsquares") loads this function.

Example:

(%i1) load ("lsquares")$
(%i2) M : matrix (
         [1,1,1], [3/2,1,2], [9/4,2,1], [3,2,2], [2,2,1]);
                           [ 1  1  1 ]
                           [         ]
                           [ 3       ]
                           [ -  1  2 ]
                           [ 2       ]
                           [         ]
(%o2)                      [ 9       ]
                           [ -  2  1 ]
                           [ 4       ]
                           [         ]
                           [ 3  2  2 ]
                           [         ]
                           [ 2  2  1 ]
(%i3) a : lsquares_estimates (
          M, [z,x,y], (z+D)^2 = A*x+B*y+C, [A,B,C,D]);
                  59        27      10921        107
(%o3)     [[A = - --, B = - --, C = -----, D = - ---]]
                  16        16      1024         32
(%i4) lsquares_residuals (
          M, [z,x,y], (z+D)^2 = A*x+B*y+C, first(a));
                     13    13    13  13  13
(%o4)               [--, - --, - --, --, --]
                     64    64    32  64  64
Function: lsquares_residual_mse (D, x, e, a)

Returns the residual mean square error (MSE) for the equation e with specified parameters a and data D.

The residual MSE is defined as:

                    n
                   ====
               1   \                        2
               -    >    (lhs(e ) - rhs(e ))
               n   /           i         i
                   ====
                   i = 1

where e[i] is the equation e evaluated with the variables in x assigned values from the i-th datum, D[i], and assigning any remaining free variables from a.

load("lsquares") loads this function.

Example:

(%i1) load ("lsquares")$
(%i2) M : matrix (
         [1,1,1], [3/2,1,2], [9/4,2,1], [3,2,2], [2,2,1]);
                           [ 1  1  1 ]
                           [         ]
                           [ 3       ]
                           [ -  1  2 ]
                           [ 2       ]
                           [         ]
(%o2)                      [ 9       ]
                           [ -  2  1 ]
                           [ 4       ]
                           [         ]
                           [ 3  2  2 ]
                           [         ]
                           [ 2  2  1 ]
(%i3) a : lsquares_estimates (
       M, [z,x,y], (z+D)^2 = A*x+B*y+C, [A,B,C,D]);
                  59        27      10921        107
(%o3)     [[A = - --, B = - --, C = -----, D = - ---]]
                  16        16      1024         32
(%i4) lsquares_residual_mse (
       M, [z,x,y], (z + D)^2 = A*x + B*y + C, first (a));
                              169
(%o4)                         ----
                              2560
Function: plsquares
    plsquares (Mat,VarList,depvars)
    plsquares (Mat,VarList,depvars,maxexpon)
    plsquares (Mat,VarList,depvars,maxexpon,maxdegree)

Multivariable polynomial adjustment of a data table by the "least squares" method. Mat is a matrix containing the data, VarList is a list of variable names (one for each Mat column, but use "-" instead of varnames to ignore Mat columns), depvars is the name of a dependent variable or a list with one or more names of dependent variables (which names should be in VarList), maxexpon is the optional maximum exponent for each independent variable (1 by default), and maxdegree is the optional maximum polynomial degree (maxexpon by default); note that the sum of exponents of each term must be equal or smaller than maxdegree, and if maxdgree = 0 then no limit is applied.

If depvars is the name of a dependent variable (not in a list), plsquares returns the adjusted polynomial. If depvars is a list of one or more dependent variables, plsquares returns a list with the adjusted polynomial(s). The Coefficients of Determination are displayed in order to inform about the goodness of fit, which ranges from 0 (no correlation) to 1 (exact correlation). These values are also stored in the global variable DETCOEF (a list if depvars is a list).

A simple example of multivariable linear adjustment:

(%i1) load("plsquares")$

(%i2) plsquares(matrix([1,2,0],[3,5,4],[4,7,9],[5,8,10]),
                [x,y,z],z);
     Determination Coefficient for z = .9897039897039897
                       11 y - 9 x - 14
(%o2)              z = ---------------
                              3

The same example without degree restrictions:

(%i3) plsquares(matrix([1,2,0],[3,5,4],[4,7,9],[5,8,10]),
                [x,y,z],z,1,0);
     Determination Coefficient for z = 1.0
                    x y + 23 y - 29 x - 19
(%o3)           z = ----------------------
                              6

How many diagonals does a N-sides polygon have? What polynomial degree should be used?

(%i4) plsquares(matrix([3,0],[4,2],[5,5],[6,9],[7,14],[8,20]),
                [N,diagonals],diagonals,5);
     Determination Coefficient for diagonals = 1.0
                                2
                               N  - 3 N
(%o4)              diagonals = --------
                                  2
(%i5) ev(%, N=9);   /* Testing for a 9 sides polygon */
(%o5)                 diagonals = 27

How many ways do we have to put two queens without they are threatened into a n x n chessboard?

(%i6) plsquares(matrix([0,0],[1,0],[2,0],[3,8],[4,44]),
                [n,positions],[positions],4);
     Determination Coefficient for [positions] = [1.0]
                         4       3      2
                      3 n  - 10 n  + 9 n  - 2 n
(%o6)    [positions = -------------------------]
                                  6
(%i7) ev(%[1], n=8); /* Testing for a (8 x 8) chessboard */
(%o7)                positions = 1288

An example with six dependent variables:

(%i8) mtrx:matrix([0,0,0,0,0,1,1,1],[0,1,0,1,1,1,0,0],
                  [1,0,0,1,1,1,0,0],[1,1,1,1,0,0,0,1])$
(%i8) plsquares(mtrx,[a,b,_And,_Or,_Xor,_Nand,_Nor,_Nxor],
                     [_And,_Or,_Xor,_Nand,_Nor,_Nxor],1,0);
      Determination Coefficient for
[_And, _Or, _Xor, _Nand, _Nor, _Nxor] =
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
(%o2) [_And = a b, _Or = - a b + b + a,
_Xor = - 2 a b + b + a, _Nand = 1 - a b,
_Nor = a b - b - a + 1, _Nxor = 2 a b - b - a + 1]

To use this function write first load("lsquares").


Next: , Previous: lsquares-pkg, Up: Top   [Contents][Index]

60 makeOrders


Previous: makeOrders-pkg, Up: makeOrders-pkg   [Contents][Index]

60.1 Functions and Variables for makeOrders

Function: makeOrders (indvarlist,orderlist)

Returns a list of all powers for a polynomial up to and including the arguments.

(%i1) load("makeOrders")$

(%i2) makeOrders([a,b],[2,3]);
(%o2) [[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1],
            [1, 2], [1, 3], [2, 0], [2, 1], [2, 2], [2, 3]]
(%i3) expand((1+a+a^2)*(1+b+b^2+b^3));
       2  3      3    3    2  2      2    2    2
(%o3) a  b  + a b  + b  + a  b  + a b  + b  + a  b + a b
                                                  2
                                           + b + a  + a + 1

where [0, 1] is associated with the term b and [2, 3] with a^2 b^3.

To use this function write first load("makeOrders").


Next: , Previous: makeOrders-pkg, Up: Top   [Contents][Index]

61 mnewton


Next: , Previous: mnewton-pkg, Up: mnewton-pkg   [Contents][Index]

61.1 Introduction to mnewton

mnewton is an implementation of Newton’s method for solving nonlinear equations in one or more variables.


Previous: Introduction to mnewton, Up: mnewton-pkg   [Contents][Index]

61.2 Functions and Variables for mnewton

Option variable: newtonepsilon

Default value: 10.0^(-fpprec/2)

Precision to determine when the mnewton function has converged towards the solution.

When newtonepsilon is a bigfloat, mnewton computations are done with bigfloats; otherwise, ordinary floats are used.

See also mnewton.

Option variable: newtonmaxiter

Default value: 50

Maximum number of iterations to stop the mnewton function if it does not converge or if it converges too slowly.

See also mnewton.

Option variable: newtondebug

Default value: false

When newtondebug is true, mnewton prints out debugging information while solving a problem.

Function: mnewton
    mnewton (FuncList, VarList, GuessList)
    mnewton (FuncList, VarList, GuessList, DF)

Approximate solution of multiple nonlinear equations by Newton’s method.

FuncList is a list of functions to solve, VarList is a list of variable names, and GuessList is a list of initial approximations. The optional argument DF is the Jacobian matrix of the list of functions; if not supplied, it is calculated automatically from FuncList.

FuncList may be specified as a list of equations, in which case the function to be solved is the left-hand side of each equation minus the right-hand side.

If there is only a single function, variable, and initial point, they may be specified as a single expression, variable, and initial value; they need not be lists of one element.

A variable may be a simple symbol or a subscripted symbol.

The solution, if any, is returned as a list of one element, which is a list of equations, one for each variable, specifying an approximate solution; this is the same format as returned by solve. If the solution is not found, [] is returned.

Functions and initial points may contain complex numbers, and solutions likewise may contain complex numbers.

mnewton is governed by global variables newtonepsilon and newtonmaxiter, and the global flag newtondebug.

load("mnewton") loads this function.

See also realroots, allroots, find_root and newton.

Examples:

(%i1) load("mnewton")$

(%i2) mnewton([x1+3*log(x1)-x2^2, 2*x1^2-x1*x2-5*x1+1],
              [x1, x2], [5, 5]);
(%o2) [[x1 = 3.756834008012769, x2 = 2.779849592817897]]
(%i3) mnewton([2*a^a-5],[a],[1]);
(%o3)             [[a = 1.70927556786144]]
(%i4) mnewton([2*3^u-v/u-5, u+2^v-4], [u, v], [2, 2]);
(%o4) [[u = 1.066618389595407, v = 1.552564766841786]]

The variable newtonepsilon controls the precision of the approximations. It also controls if computations are performed with floats or bigfloats.

(%i1) load("mnewton")$

(%i2) (fpprec : 25, newtonepsilon : bfloat(10^(-fpprec+5)))$

(%i3) mnewton([2*3^u-v/u-5, u+2^v-4], [u, v], [2, 2]);
(%o3) [[u = 1.066618389595406772591173b0, 
                               v = 1.552564766841786450100418b0]]

Next: , Previous: mnewton-pkg, Up: Top   [Contents][Index]

62 numericalio


Next: , Previous: mnewton-pkg, Up: numericalio-pkg   [Contents][Index]

62.1 Introduction to numericalio

numericalio is a collection of functions to read and write files and streams. Functions for plain-text input and output can read and write numbers (integer, float, or bigfloat), symbols, and strings. Functions for binary input and output can read and write only floating-point numbers.

If there already exists a list, matrix, or array object to store input data, numericalio input functions can write data into that object. Otherwise, numericalio can guess, to some degree, the structure of an object to store the data, and return that object.

62.1.1 Plain-text input and output

In plain-text input and output, it is assumed that each item to read or write is an atom: an integer, float, bigfloat, string, or symbol, and not a rational or complex number or any other kind of nonatomic expression. The numericalio functions may attempt to do something sensible faced with nonatomic expressions, but the results are not specified here and subject to change.

Atoms in both input and output files have the same format as in Maxima batch files or the interactive console. In particular, strings are enclosed in double quotes, backslash \ prevents any special interpretation of the next character, and the question mark ? is recognized at the beginning of a symbol to mean a Lisp symbol (as opposed to a Maxima symbol). No continuation character (to join broken lines) is recognized.

62.1.2 Separator flag values for input

The functions for plain-text input and output take an optional argument, separator_flag, that tells what character separates data.

For plain-text input, these values of separator_flag are recognized: comma for comma separated values, pipe for values separated by the vertical bar character |, semicolon for values separated by semicolon ;, and space for values separated by space or tab characters. Equivalently, the separator may be specified as a string of one character: "," (comma), "|" (pipe), ";" (semicolon), " " (space), or " " (tab).

If the file name ends in .csv and separator_flag is not specified, comma is assumed. If the file name ends in something other than .csv and separator_flag is not specified, space is assumed.

In plain-text input, multiple successive space and tab characters count as a single separator. However, multiple comma, pipe, or semicolon characters are significant. Successive comma, pipe, or semicolon characters (with or without intervening spaces or tabs) are considered to have false between the separators. For example, 1234,,Foo is treated the same as 1234,false,Foo.

62.1.3 Separator flag values for output

For plain-text output, tab, for values separated by the tab character, is recognized as a value of separator_flag, as well as comma, pipe, semicolon, and space.

In plain-text output, false atoms are written as such; a list [1234, false, Foo] is written 1234,false,Foo, and there is no attempt to collapse the output to 1234,,Foo.

62.1.4 Binary floating-point input and output

numericalio functions can read and write 8-byte IEEE 754 floating-point numbers. These numbers can be stored either least significant byte first or most significant byte first, according to the global flag set by assume_external_byte_order. If not specified, numericalio assumes the external byte order is most-significant byte first.

Other kinds of numbers are coerced to 8-byte floats; numericalio cannot read or write binary non-numeric data.

Some Lisp implementations do not recognize IEEE 754 special values (positive and negative infinity, not-a-number values, denormalized values). The effect of reading such values with numericalio is undefined.

numericalio includes functions to open a stream for reading or writing a stream of bytes.


Next: , Previous: Introduction to numericalio, Up: numericalio-pkg   [Contents][Index]

62.2 Functions and Variables for plain-text input and output

Function: read_matrix
    read_matrix (S)
    read_matrix (S, M)
    read_matrix (S, separator_flag)
    read_matrix (S, M, separator_flag)

read_matrix(S) reads the source S and returns its entire content as a matrix. The size of the matrix is inferred from the input data; each line of the file becomes one row of the matrix. If some lines have different lengths, read_matrix complains.

read_matrix(S, M) read the source S into the matrix M, until M is full or the source is exhausted. Input data are read into the matrix in row-major order; the input need not have the same number of rows and columns as M.

The source S may be a file name or a stream which for example allows skipping the very first line of a file (that may be useful, if you read CSV data, where the first line often contains the description of the columns):

s : openr("data.txt");
readline(s);  /* skip the first line */
M : read_matrix(s, 'comma);  /* read the following (comma-separated) lines into matrix M */
close(s);

The recognized values of separator_flag are comma, pipe, semicolon, and space. Equivalently, the separator may be specified as a string of one character: "," (comma), "|" (pipe), ";" (semicolon), " " (space), or " " (tab). If separator_flag is not specified, the file is assumed space-delimited.

See also openr, read_array, read_hashed_array, read_list, read_binary_matrix, write_data and read_nested_list.

Function: read_array
    read_array (S, A)
    read_array (S, A, separator_flag)

Reads the source S into the array A, until A is full or the source is exhausted. Input data are read into the array in row-major order; the input need not conform to the dimensions of A.

The source S may be a file name or a stream.

The recognized values of separator_flag are comma, pipe, semicolon, and space. Equivalently, the separator may be specified as a string of one character: "," (comma), "|" (pipe), ";" (semicolon), " " (space), or " " (tab). If separator_flag is not specified, the file is assumed space-delimited.

See also openr, read_matrix, read_hashed_array, read_list, read_binary_array and read_nested_list.

Function: read_hashed_array
    read_hashed_array (S, A)
    read_hashed_array (S, A, separator_flag)

Reads the source S and returns its entire content as a `hashed array'. The source S may be a file name or a stream.

read_hashed_array treats the first item on each line as a hash key, and associates the remainder of the line (as a list) with the key. For example, the line 567 12 17 32 55 is equivalent to A[567]: [12, 17, 32, 55]$. Lines need not have the same numbers of elements.

The recognized values of separator_flag are comma, pipe, semicolon, and space. Equivalently, the separator may be specified as a string of one character: "," (comma), "|" (pipe), ";" (semicolon), " " (space), or " " (tab). If separator_flag is not specified, the file is assumed space-delimited.

See also openr, read_matrix, read_array, read_list and read_nested_list.

Function: read_nested_list
    read_nested_list (S)
    read_nested_list (S, separator_flag)

Reads the source S and returns its entire content as a nested list. The source S may be a file name or a stream.

read_nested_list returns a list which has a sublist for each line of input. Lines need not have the same numbers of elements. Empty lines are not ignored: an empty line yields an empty sublist.

The recognized values of separator_flag are comma, pipe, semicolon, and space. Equivalently, the separator may be specified as a string of one character: "," (comma), "|" (pipe), ";" (semicolon), " " (space), or " " (tab). If separator_flag is not specified, the file is assumed space-delimited.

See also openr, read_matrix, read_array, read_list and read_hashed_array.

Function: read_list
    read_list (S)
    read_list (S, L)
    read_list (S, separator_flag)
    read_list (S, L, separator_flag)

read_list(S) reads the source S and returns its entire content as a flat list.

read_list(S, L) reads the source S into the list L, until L is full or the source is exhausted.

The source S may be a file name or a stream.

The recognized values of separator_flag are comma, pipe, semicolon, and space. Equivalently, the separator may be specified as a string of one character: "," (comma), "|" (pipe), ";" (semicolon), " " (space), or " " (tab). If separator_flag is not specified, the file is assumed space-delimited.

See also openr, read_matrix, read_array, read_nested_list, read_binary_list and read_hashed_array.

Function: write_data
    write_data (X, D)
    write_data (X, D, separator_flag)

Writes the object X to the destination D.

write_data writes a matrix in row-major order, with one line per row.

write_data writes an array created by array or make_array in row-major order, with a new line at the end of every slab. Higher-dimensional slabs are separated by additional new lines.

write_data writes a hashed array with each key followed by its associated list on one line.

write_data writes a nested list with each sublist on one line.

write_data writes a flat list all on one line.

The destination D may be a file name or a stream. When the destination is a file name, the global variable file_output_append governs whether the output file is appended or truncated. When the destination is a stream, no special action is taken by write_data after all the data are written; in particular, the stream remains open.

The recognized values of separator_flag are comma, pipe, semicolon, space, and tab. Equivalently, the separator may be specified as a string of one character: "," (comma), "|" (pipe), ";" (semicolon), " " (space), or " " (tab). If separator_flag is not specified, the file is assumed space-delimited.

See also openw and read_matrix.


Previous: Functions and Variables for plain-text input and output, Up: numericalio-pkg   [Contents][Index]

62.3 Functions and Variables for binary input and output

Function: assume_external_byte_order (byte_order_flag)

Tells numericalio the byte order for reading and writing binary data. Two values of byte_order_flag are recognized: lsb which indicates least-significant byte first, also called little-endian byte order; and msb which indicates most-significant byte first, also called big-endian byte order.

If not specified, numericalio assumes the external byte order is most-significant byte first.

Function: openr_binary (file_name)

Returns an input stream of 8-bit unsigned bytes to read the file named by file_name.

See also openw_binary and openr.

Function: openw_binary (file_name)

Returns an output stream of 8-bit unsigned bytes to write the file named by file_name.

See also openr_binary, opena_binary and openw.

Function: opena_binary (file_name)

Returns an output stream of 8-bit unsigned bytes to append the file named by file_name.

Function: read_binary_matrix (S, M)

Reads binary 8-byte floating point numbers from the source S into the matrix M until M is full, or the source is exhausted. Elements of M are read in row-major order.

The source S may be a file name or a stream.

The byte order in elements of the source is specified by assume_external_byte_order.

See also read_matrix.

Function: read_binary_array (S, A)

Reads binary 8-byte floating point numbers from the source S into the array A until A is full, or the source is exhausted. A must be an array created by array or make_array. Elements of A are read in row-major order.

The source S may be a file name or a stream.

The byte order in elements of the source is specified by assume_external_byte_order.

See also read_array.

Function: read_binary_list
    read_binary_list (S)
    read_binary_list (S, L)

read_binary_list(S) reads the entire content of the source S as a sequence of binary 8-byte floating point numbers, and returns it as a list. The source S may be a file name or a stream.

read_binary_list(S, L) reads 8-byte binary floating point numbers from the source S until the list L is full, or the source is exhausted.

The byte order in elements of the source is specified by assume_external_byte_order.

See also read_list.

Function: write_binary_data (X, D)

Writes the object X, comprising binary 8-byte IEEE 754 floating-point numbers, to the destination D. Other kinds of numbers are coerced to 8-byte floats. write_binary_data cannot write non-numeric data.

The object X may be a list, a nested list, a matrix, or an array created by array or make_array; X cannot be a hashed array or any other type of object. write_binary_data writes nested lists, matrices, and arrays in row-major order.

The destination D may be a file name or a stream. When the destination is a file name, the global variable file_output_append governs whether the output file is appended or truncated. When the destination is a stream, no special action is taken by write_binary_data after all the data are written; in particular, the stream remains open.

The byte order in elements of the destination is specified by assume_external_byte_order.

See also write_data.


Next: , Previous: numericalio-pkg, Up: Top   [Contents][Index]

63 opsubst


Previous: opsubst-pkg, Up: opsubst-pkg   [Contents][Index]

63.1 Functions and Variables for opsubst

Function: opsubst
    opsubst (f,g,e)
    opsubst (g=f,e)
    opsubst ([g1=f1,g2=f2,..., gn=fn],e)

The function opsubst is similar to the function subst, except that opsubst only makes substitutions for the operators in an expression. In general, When f is an operator in the expression e, substitute g for f in the expression e.

To determine the operator, opsubst sets inflag to true. This means opsubst substitutes for the internal, not the displayed, operator in the expression.

Examples:

(%i1) load ("opsubst")$

(%i2) opsubst(f,g,g(g(x)));
(%o2)                     f(f(x))
(%i3) opsubst(f,g,g(g));
(%o3)                       f(g)
(%i4) opsubst(f,g[x],g[x](z));
(%o4)                       f(z)
(%i5) opsubst(g[x],f, f(z));
(%o5)                      g (z)
                            x
(%i6) opsubst(tan, sin, sin(sin));
(%o6)                     tan(sin)
(%i7) opsubst([f=g,g=h],f(x));
(%o7)                       h(x)

Internally, Maxima does not use the unary negation, division, or the subtraction operators; thus:

(%i8) opsubst("+","-",a-b);
(%o8)                     a - b
(%i9) opsubst("f","-",-a);
(%o9)                      - a
(%i10) opsubst("^^","/",a/b);
                             a
(%o10)                       -
                             b

The internal representation of -a*b is *(-1,a,b); thus

(%i11) opsubst("[","*", -a*b);
(%o11)                  [- 1, a, b]

When either operator isn’t a Maxima symbol, generally some other function will signal an error:

(%i12) opsubst(a+b,f, f(x));

Improper name or value in functional position:
b + a
 -- an error.  Quitting.  To debug this try debugmode(true);

However, subscripted operators are allowed:

(%i13) opsubst(g[5],f, f(x));
(%o13)                     g (x)
                            5

To use this function write first load("opsubst").


Next: , Previous: opsubst-pkg, Up: Top   [Contents][Index]

64 orthopoly


Next: , Previous: orthopoly-pkg, Up: orthopoly-pkg   [Contents][Index]

64.1 Introduction to orthogonal polynomials

orthopoly is a package for symbolic and numerical evaluation of several kinds of orthogonal polynomials, including Chebyshev, Laguerre, Hermite, Jacobi, Legendre, and ultraspherical (Gegenbauer) polynomials. Additionally, orthopoly includes support for the spherical Bessel, spherical Hankel, and spherical harmonic functions.

For the most part, orthopoly follows the conventions of Abramowitz and Stegun Handbook of Mathematical Functions, Chapter 22 (10th printing, December 1972); additionally, we use Gradshteyn and Ryzhik, Table of Integrals, Series, and Products (1980 corrected and enlarged edition), and Eugen Merzbacher Quantum Mechanics (2nd edition, 1970).

Barton Willis of the University of Nebraska at Kearney (UNK) wrote the orthopoly package and its documentation. The package is released under the GNU General Public License (GPL).

64.1.1 Getting Started with orthopoly

load ("orthopoly") loads the orthopoly package.

To find the third-order Legendre polynomial,

(%i1) legendre_p (3, x);
                      3             2
             5 (1 - x)    15 (1 - x)
(%o1)      - ---------- + ----------- - 6 (1 - x) + 1
                 2             2

To express this as a sum of powers of x, apply ratsimp or rat to the result.

(%i2) [ratsimp (%), rat (%)];
                        3           3
                     5 x  - 3 x  5 x  - 3 x
(%o2)/R/            [----------, ----------]
                         2           2

Alternatively, make the second argument to legendre_p (its “main” variable) a canonical rational expression (CRE).

(%i1) legendre_p (3, rat (x));
                              3
                           5 x  - 3 x
(%o1)/R/                   ----------
                               2

For floating point evaluation, orthopoly uses a running error analysis to estimate an upper bound for the error. For example,

(%i1) jacobi_p (150, 2, 3, 0.2);
(%o1) interval(- 0.062017037936715, 1.533267919277521E-11)

Intervals have the form interval (c, r), where c is the center and r is the radius of the interval. Since Maxima does not support arithmetic on intervals, in some situations, such as graphics, you want to suppress the error and output only the center of the interval. To do this, set the option variable orthopoly_returns_intervals to false.

(%i1) orthopoly_returns_intervals : false;
(%o1)                         false
(%i2) jacobi_p (150, 2, 3, 0.2);
(%o2)                  - 0.062017037936715

Refer to the section see Floating point Evaluation for more information.

Most functions in orthopoly have a gradef property; thus

(%i1) diff (hermite (n, x), x);
(%o1)                     2 n H     (x)
                               n - 1
(%i2) diff (gen_laguerre (n, a, x), x);
              (a)               (a)
           n L   (x) - (n + a) L     (x) unit_step(n)
              n                 n - 1
(%o2)      ------------------------------------------
                               x

The unit step function in the second example prevents an error that would otherwise arise by evaluating with n equal to 0.

(%i3) ev (%, n = 0);
(%o3)                           0

The gradef property only applies to the “main” variable; derivatives with respect other arguments usually result in an error message; for example

(%i1) diff (hermite (n, x), x);
(%o1)                     2 n H     (x)
                               n - 1
(%i2) diff (hermite (n, x), n);

Maxima doesn't know the derivative of hermite with respect the first
argument
 -- an error.  Quitting.  To debug this try debugmode(true);

Generally, functions in orthopoly map over lists and matrices. For the mapping to fully evaluate, the option variables doallmxops and listarith must both be true (the defaults). To illustrate the mapping over matrices, consider

(%i1) hermite (2, x);
                                     2
(%o1)                    - 2 (1 - 2 x )
(%i2) m : matrix ([0, x], [y, 0]);
                            [ 0  x ]
(%o2)                       [      ]
                            [ y  0 ]
(%i3) hermite (2, m);
               [                             2  ]
               [      - 2        - 2 (1 - 2 x ) ]
(%o3)          [                                ]
               [             2                  ]
               [ - 2 (1 - 2 y )       - 2       ]

In the second example, the i, j element of the value is hermite (2, m[i,j]); this is not the same as computing -2 + 4 m . m, as seen in the next example.

(%i4) -2 * matrix ([1, 0], [0, 1]) + 4 * m . m;
                    [ 4 x y - 2      0     ]
(%o4)               [                      ]
                    [     0      4 x y - 2 ]

If you evaluate a function at a point outside its domain, generally orthopoly returns the function unevaluated. For example,

(%i1) legendre_p (2/3, x);
(%o1)                        P   (x)
                              2/3

orthopoly supports translation into TeX; it also does two-dimensional output on a terminal.

(%i1) spherical_harmonic (l, m, theta, phi);
                          m
(%o1)                    Y (theta, phi)
                          l
(%i2) tex (%);
$$Y_{l}^{m}\left(\vartheta,\varphi\right)$$
(%o2)                         false
(%i3) jacobi_p (n, a, a - b, x/2);
                          (a, a - b) x
(%o3)                    P          (-)
                          n          2
(%i4) tex (%);
$$P_{n}^{\left(a,a-b\right)}\left({{x}\over{2}}\right)$$
(%o4)                         false

64.1.2 Limitations

When an expression involves several orthogonal polynomials with symbolic orders, it’s possible that the expression actually vanishes, yet Maxima is unable to simplify it to zero. If you divide by such a quantity, you’ll be in trouble. For example, the following expression vanishes for integers n greater than 1, yet Maxima is unable to simplify it to zero.

(%i1) (2*n - 1) * legendre_p (n - 1, x) * x - n * legendre_p (n, x)
      + (1 - n) * legendre_p (n - 2, x);
(%o1)  (2 n - 1) P     (x) x - n P (x) + (1 - n) P     (x)
                  n - 1           n               n - 2

For a specific n, we can reduce the expression to zero.

(%i2) ev (% ,n = 10, ratsimp);
(%o2)                           0

Generally, the polynomial form of an orthogonal polynomial is ill-suited for floating point evaluation. Here’s an example.

(%i1) p : jacobi_p (100, 2, 3, x)$

(%i2) subst (0.2, x, p);
(%o2)                3.4442767023833592E+35
(%i3) jacobi_p (100, 2, 3, 0.2);
(%o3)  interval(0.18413609135169, 6.8990300925815987E-12)
(%i4) float(jacobi_p (100, 2, 3, 2/10));
(%o4)                   0.18413609135169

The true value is about 0.184; this calculation suffers from extreme subtractive cancellation error. Expanding the polynomial and then evaluating, gives a better result.

(%i5) p : expand(p)$
(%i6) subst (0.2, x, p);
(%o6) 0.18413609766122982

This isn’t a general rule; expanding the polynomial does not always result in an expression that is better suited for numerical evaluation. By far, the best way to do numerical evaluation is to make one or more of the function arguments floating point numbers. By doing that, specialized floating point algorithms are used for evaluation.

Maxima’s float function is somewhat indiscriminate; if you apply float to an expression involving an orthogonal polynomial with a symbolic degree or order parameter, these parameters may be converted into floats; after that, the expression will not evaluate fully. Consider

(%i1) assoc_legendre_p (n, 1, x);
                               1
(%o1)                         P (x)
                               n
(%i2) float (%);
                              1.0
(%o2)                        P   (x)
                              n
(%i3) ev (%, n=2, x=0.9);
                             1.0
(%o3)                       P   (0.9)
                             2

The expression in (%o3) will not evaluate to a float; orthopoly doesn’t recognize floating point values where it requires an integer. Similarly, numerical evaluation of the pochhammer function for orders that exceed pochhammer_max_index can be troublesome; consider

(%i1) x :  pochhammer (1, 10), pochhammer_max_index : 5;
(%o1)                         (1)
                                 10

Applying float doesn’t evaluate x to a float

(%i2) float (x);
(%o2)                       (1.0)
                                 10.0

To evaluate x to a float, you’ll need to bind pochhammer_max_index to 11 or greater and apply float to x.

(%i3) float (x), pochhammer_max_index : 11;
(%o3)                       3628800.0

The default value of pochhammer_max_index is 100; change its value after loading orthopoly.

Finally, be aware that reference books vary on the definitions of the orthogonal polynomials; we’ve generally used the conventions of Abramowitz and Stegun.

Before you suspect a bug in orthopoly, check some special cases to determine if your definitions match those used by orthopoly. Definitions often differ by a normalization; occasionally, authors use “shifted” versions of the functions that makes the family orthogonal on an interval other than (-1, 1). To define, for example, a Legendre polynomial that is orthogonal on (0, 1), define

(%i1) shifted_legendre_p (n, x) := legendre_p (n, 2*x - 1)$

(%i2) shifted_legendre_p (2, rat (x));
                            2
(%o2)/R/                 6 x  - 6 x + 1
(%i3) legendre_p (2, rat (x));
                               2
                            3 x  - 1
(%o3)/R/                    --------
                               2

64.1.3 Floating point Evaluation

Most functions in orthopoly use a running error analysis to estimate the error in floating point evaluation; the exceptions are the spherical Bessel functions and the associated Legendre polynomials of the second kind. For numerical evaluation, the spherical Bessel functions call SLATEC functions. No specialized method is used for numerical evaluation of the associated Legendre polynomials of the second kind.

The running error analysis ignores errors that are second or higher order in the machine epsilon (also known as unit roundoff). It also ignores a few other errors. It’s possible (although unlikely) that the actual error exceeds the estimate.

Intervals have the form interval (c, r), where c is the center of the interval and r is its radius. The center of an interval can be a complex number, and the radius is always a positive real number.

Here is an example.

(%i1) fpprec : 50$

(%i2) y0 : jacobi_p (100, 2, 3, 0.2);
(%o2) interval(0.1841360913516871, 6.8990300925815987E-12)
(%i3) y1 : bfloat (jacobi_p (100, 2, 3, 1/5));
(%o3) 1.8413609135168563091370224958913493690868904463668b-1

Let’s test that the actual error is smaller than the error estimate

(%i4) is (abs (part (y0, 1) - y1) < part (y0, 2));
(%o4)                         true

Indeed, for this example the error estimate is an upper bound for the true error.

Maxima does not support arithmetic on intervals.

(%i1) legendre_p (7, 0.1) + legendre_p (8, 0.1);
(%o1) interval(0.18032072148437508, 3.1477135311021797E-15)
        + interval(- 0.19949294375000004, 3.3769353084291579E-15)

A user could define arithmetic operators that do interval math. To define interval addition, we can define

(%i1) infix ("@+")$

(%i2) "@+"(x,y) := interval (part (x, 1) + part (y, 1), part (x, 2)
      + part (y, 2))$

(%i3) legendre_p (7, 0.1) @+ legendre_p (8, 0.1);
(%o3) interval(- 0.019172222265624955, 6.5246488395313372E-15)

The special floating point routines get called when the arguments are complex. For example,

(%i1) legendre_p (10, 2 + 3.0*%i);
(%o1) interval(- 3.876378825E+7 %i - 6.0787748E+7, 
                                           1.2089173052721777E-6)

Let’s compare this to the true value.

(%i1) float (expand (legendre_p (10, 2 + 3*%i)));
(%o1)          - 3.876378825E+7 %i - 6.0787748E+7

Additionally, when the arguments are big floats, the special floating point routines get called; however, the big floats are converted into double floats and the final result is a double.

(%i1) ultraspherical (150, 0.5b0, 0.9b0);
(%o1) interval(- 0.043009481257265, 3.3750051301228864E-14)

64.1.4 Graphics and orthopoly

To plot expressions that involve the orthogonal polynomials, you must do two things:

  1. Set the option variable orthopoly_returns_intervals to false,
  2. Quote any calls to orthopoly functions.

If function calls aren’t quoted, Maxima evaluates them to polynomials before plotting; consequently, the specialized floating point code doesn’t get called. Here is an example of how to plot an expression that involves a Legendre polynomial.

(%i1) plot2d ('(legendre_p (5, x)), [x, 0, 1]),
                        orthopoly_returns_intervals : false;
(%o1)
figures/orthopoly1

The entire expression legendre_p (5, x) is quoted; this is different than just quoting the function name using 'legendre_p (5, x).

64.1.5 Miscellaneous Functions

The orthopoly package defines the Pochhammer symbol and a unit step function. orthopoly uses the Kronecker delta function and the unit step function in gradef statements.

To convert Pochhammer symbols into quotients of gamma functions, use makegamma.

(%i1) makegamma (pochhammer (x, n));
                          gamma(x + n)
(%o1)                     ------------
                            gamma(x)
(%i2) makegamma (pochhammer (1/2, 1/2));
                                1
(%o2)                       ---------
                            sqrt(%pi)

Derivatives of the Pochhammer symbol are given in terms of the psi function.

(%i1) diff (pochhammer (x, n), x);
(%o1)             (x)  (psi (x + n) - psi (x))
                     n     0             0
(%i2) diff (pochhammer (x, n), n);
(%o2)                   (x)  psi (x + n)
                           n    0

You need to be careful with the expression in (%o1); the difference of the psi functions has polynomials when x = -1, -2, .., -n. These polynomials cancel with factors in pochhammer (x, n) making the derivative a degree n - 1 polynomial when n is a positive integer.

The Pochhammer symbol is defined for negative orders through its representation as a quotient of gamma functions. Consider

(%i1) q : makegamma (pochhammer (x, n));
                          gamma(x + n)
(%o1)                     ------------
                            gamma(x)
(%i2) sublis ([x=11/3, n= -6], q);
                               729
(%o2)                        - ----
                               2240

Alternatively, we can get this result directly.

(%i1) pochhammer (11/3, -6);
                               729
(%o1)                        - ----
                               2240

The unit step function is left-continuous; thus

(%i1) [unit_step (-1/10), unit_step (0), unit_step (1/10)];
(%o1)                       [0, 0, 1]

If you need a unit step function that is neither left or right continuous at zero, define your own using signum; for example,

(%i1) xunit_step (x) := (1 + signum (x))/2$

(%i2) [xunit_step (-1/10), xunit_step (0), xunit_step (1/10)];
                                1
(%o2)                       [0, -, 1]
                                2

Do not redefine unit_step itself; some code in orthopoly requires that the unit step function be left-continuous.

64.1.6 Algorithms

Generally, orthopoly does symbolic evaluation by using a hypergeometic representation of the orthogonal polynomials. The hypergeometic functions are evaluated using the (undocumented) functions hypergeo11 and hypergeo21. The exceptions are the half-integer Bessel functions and the associated Legendre function of the second kind. The half-integer Bessel functions are evaluated using an explicit representation, and the associated Legendre function of the second kind is evaluated using recursion.

For floating point evaluation, we again convert most functions into a hypergeometic form; we evaluate the hypergeometic functions using forward recursion. Again, the exceptions are the half-integer Bessel functions and the associated Legendre function of the second kind. Numerically, the half-integer Bessel functions are evaluated using the SLATEC code.


Previous: Introduction to orthogonal polynomials, Up: orthopoly-pkg   [Contents][Index]

64.2 Functions and Variables for orthogonal polynomials

Function: assoc_legendre_p (n, m, x)

The associated Legendre function of the first kind of degree n and order m, \(P_{n}^{m}(z)\), is a solution of the differential equation:

$$ (1-z^2){d^2 w\over dz^2} - 2z{dw\over dz} + \left[n(n+1)-{m^2\over 1-z^2}\right] w = 0 $$

This is related to the Legendre polynomial, \(P_n(x)\) via

$$ P_n^m(x) = (-1)^m\left(1-x^2\right)^{m/2} {d^m\over dx^m} P_n(x) $$

Reference: A&S eqn 22.5.37, A&S eqn 8.6.6, and A&S eqn 8.2.5.

Some examples:

(%i1) assoc_legendre_p(2,0,x);
                                                 2
                                        3 (1 - x)
(%o1)                   (- 3 (1 - x)) + ---------- + 1
                                            2
(%i2) factor(%);
                                      2
                                   3 x  - 1
(%o2)                              --------
                                      2
(%i3) factor(assoc_legendre_p(2,1,x));
                                              2
(%o3)                         - 3 x sqrt(1 - x )

(%i4) (-1)^1*(1-x^2)^(1/2)*diff(legendre_p(2,x),x);
                                                    2
(%o4)                   - (3 - 3 (1 - x)) sqrt(1 - x )

(%i5) factor(%);
                                              2
(%o5)                         - 3 x sqrt(1 - x )
Function: assoc_legendre_q (n, m, x)

The associated Legendre function of the second kind of degree n and order m, \(Q_{n}^{m}(z)\), is a solution of the differential equation:

$$ (1-z^2){d^2 w\over dz^2} - 2z{dw\over dz} + \left[n(n+1)-{m^2\over 1-z^2}\right] w = 0 $$

Reference: Abramowitz and Stegun, equation 8.5.3 and 8.1.8.

Some examples:

(%i1) assoc_legendre_q(0,0,x);
                                       x + 1
                                 log(- -----)
                                       x - 1
(%o1)                            ------------
                                      2
(%i2) assoc_legendre_q(1,0,x);
                                    x + 1
                              log(- -----) x - 2
                                    x - 1
(%o2)/R/                      ------------------
                                      2
(%i3) assoc_legendre_q(1,1,x);
(%o3)/R/ 
          x + 1            2   2               2            x + 1            2
    log(- -----) sqrt(1 - x ) x  - 2 sqrt(1 - x ) x - log(- -----) sqrt(1 - x )
          x - 1                                             x - 1
  - ---------------------------------------------------------------------------
                                        2
                                     2 x  - 2
Function: chebyshev_t (n, x)

The Chebyshev polynomial of the first kind of degree n, \(T_n(x).\)

Reference: A&S eqn 22.5.47.

The polynomials \(T_n(x)\) can be written in terms of a hypergeometric function:

$$ T_n(x) = {_{2}}F_{1}\left(-n, n; {1\over 2}; {1-x\over 2}\right) $$

The polynomials can also be defined in terms of the sum

$$ T_n(x) = {n\over 2} \sum_{r=0}^{\lfloor {n/2}\rfloor} {(-1)^r\over n-r} {n-r\choose k}(2x)^{n-2r} $$

or the Rodrigues formula

$$ T_n(x) = {1\over \kappa_n w(x)} {d^n\over dx^n}\left(w(x)(1-x^2)^n\right) $$

where

$$ \eqalign{ w(x) &= 1/\sqrt{1-x^2} \cr \kappa_n &= (-2)^n\left(1\over 2\right)_n } $$

Some examples:

(%i1) chebyshev_t(2,x);
                                                 2
(%o1)                   (- 4 (1 - x)) + 2 (1 - x)  + 1
(%i2) factor(%);
                                      2
(%o2)                              2 x  - 1
(%i3) factor(chebyshev_t(3,x));
                                       2
(%o3)                            x (4 x  - 3)
(%i4) factor(hgfred([-3,3],[1/2],(1-x)/2));
                                       2
(%o4)                            x (4 x  - 3)
Function: chebyshev_u (n, x)

The Chebyshev polynomial of the second kind of degree n, \(U_n(x)\).

Reference: A&S eqn 22.5.48.

The polynomials \(U_n(x)\) can be written in terms of a hypergeometric function:

$$ U_n(x) = (n+1)\; {_{2}F_{1}}\left(-n, n+2; {3\over 2}; {1-x\over 2}\right) $$

The polynomials can also be defined in terms of the sum

$$ U_n(x) = \sum_{r=0}^{\lfloor n/2 \rfloor} (-1)^r {n-r \choose r} (2x)^{n-2r} $$

or the Rodrigues formula

$$ U_n(x) = {1\over \kappa_n w(x)} {d^n\over dx^n}\left(w(x)(1-x^2)^n\right) $$

where

$$ \eqalign{ w(x) &= \sqrt{1-x^2} \cr \kappa_n &= {(-2)^n\left({3\over 2}\right)_n \over n+1} } $$

.

(%i1) chebyshev_u(2,x);
                                                  2
                            8 (1 - x)    4 (1 - x)
(%o1)                 3 ((- ---------) + ---------- + 1)
                                3            3
(%i2) expand(%);
                                      2
(%o2)                              4 x  - 1
(%i3) expand(chebyshev_u(3,x));
                                     3
(%o3)                             8 x  - 4 x
(%i4) expand(4*hgfred([-3,5],[3/2],(1-x)/2));
                                     3
(%o4)                             8 x  - 4 x
Function: gen_laguerre (n, a, x)

The generalized Laguerre polynomial of degree n, \(L_n^{(\alpha)}(x)\).

These can be defined by

$$ L_n^{(\alpha)}(x) = {n+\alpha \choose n}\; {_1F_1}(-n; \alpha+1; x) $$

The polynomials can also be defined by the sum

$$ L_n^{(\alpha)}(x) = \sum_{k=0}^n {(\alpha + k + 1)_{n-k} \over (n-k)! k!} (-x)^k $$

or the Rodrigues formula

$$ L_n^{(\alpha)}(x) = {1\over \kappa_n w(x)} {d^n\over dx^n}\left(w(x)x^n\right) $$

where

$$ \eqalign{ w(x) &= e^{-x}x^{\alpha} \cr \kappa_n &= n! } $$

Reference: A&S eqn 22.5.54.

Some examples:

(%i1) gen_laguerre(1,k,x);
                                             x
(%o1)                         (k + 1) (1 - -----)
                                           k + 1
(%i2) gen_laguerre(2,k,x);
                                         2
                                        x            2 x
                 (k + 1) (k + 2) (--------------- - ----- + 1)
                                  (k + 1) (k + 2)   k + 1
(%o2)            ---------------------------------------------
                                       2
(%i3) binomial(2+k,2)*hgfred([-2],[1+k],x);
                                         2
                                        x            2 x
                 (k + 1) (k + 2) (--------------- - ----- + 1)
                                  (k + 1) (k + 2)   k + 1
(%o3)            ---------------------------------------------
                                       2

Function: hermite (n, x)

The Hermite polynomial of degree n, \(H_n(x)\).

These polynomials may be defined by a hypergeometric function

$$ H_n(x) = (2x)^n\; {_2F_0}\left(-{1\over 2} n, -{1\over 2}n+{1\over 2};;-{1\over x^2}\right) $$

or by the series

$$ H_n(x) = n! \sum_{k=0}^{\lfloor n/2 \rfloor} {(-1)^k(2x)^{n-2k} \over k! (n-2k)!} $$

or the Rodrigues formula

$$ H_n(x) = {1\over \kappa_n w(x)} {d^n\over dx^n}\left(w(x)\right) $$

where

$$ \eqalign{ w(x) &= e^{-{x^2/2}} \cr \kappa_n &= (-1)^n } $$

Reference: A&S eqn 22.5.55.

Some examples:

(%i1) hermite(3,x);
                                              2
                                           2 x
(%o1)                          - 12 x (1 - ----)
                                            3
(%i2) expand(%);
                                     3
(%o2)                             8 x  - 12 x
(%i3) expand(hermite(4,x));
                                  4       2
(%o3)                         16 x  - 48 x  + 12
(%i4) expand((2*x)^4*hgfred([-2,-2+1/2],[],-1/x^2));
                                  4       2
(%o4)                         16 x  - 48 x  + 12
(%i5) expand(4!*sum((-1)^k*(2*x)^(4-2*k)/(k!*(4-2*k)!),k,0,floor(4/2)));
                                  4       2
(%o5)                         16 x  - 48 x  + 12
Function: intervalp (e)

Return true if the input is an interval and return false if it isn’t.

Function: jacobi_p (n, a, b, x)

The Jacobi polynomial, \(P_n^{(a,b)}(x)\).

The Jacobi polynomials are actually defined for all a and b; however, the Jacobi polynomial weight (1 - x)^a (1 + x)^b isn’t integrable for \(a \le -1\) or \(b \le -1\).

Reference: A&S eqn 22.5.42.

The polynomial may be defined in terms of hypergeometric functions:

$$ P_n^{(a,b)}(x) = {n+a\choose n} {_1F_2}\left(-n, n + a + b + 1; a+1; {1-x\over 2}\right) $$

or the Rodrigues formula

$$ P_n^{(a, b)}(x) = {1\over \kappa_n w(x)} {d^n\over dx^n}\left(w(x)\left(1-x^2\right)^n\right) $$

where

$$ \eqalign{ w(x) &= (1-x)^a(1-x)^b \cr \kappa_n &= (-2)^n n! } $$

Some examples:

(%i1) jacobi_p(0,a,b,x);
(%o1)                                  1
(%i2) jacobi_p(1,a,b,x);
                                    (b + a + 2) (1 - x)
(%o2)                  (a + 1) (1 - -------------------)
                                         2 (a + 1)
Function: laguerre (n, x)

The Laguerre polynomial, \(L_n(x)\) of degree n.

Reference: A&S eqn 22.5.16 and A&S eqn 22.5.54.

These are related to the generalized Laguerre polynomial by

$$ L_n(x) = L_n^{(0)}(x) $$

The polynomials are given by the sum

$$ L_n(x) = \sum_{k=0}^{n} {(-1)^k\over k!}{n \choose k} x^k $$

Some examples:

(%i1) laguerre(1,x);
(%o1)                                1 - x
(%i2) laguerre(2,x);
                                  2
                                 x
(%o2)                            -- - 2 x + 1
                                 2
(%i3) gen_laguerre(2,0,x);
                                  2
                                 x
(%o3)                            -- - 2 x + 1
                                 2
(%i4) sum((-1)^k/k!*binomial(2,k)*x^k,k,0,2);
                                  2
                                 x
(%o4)                            -- - 2 x + 1
                                 2
Function: legendre_p (n, x)

The Legendre polynomial of the first kind, \(P_n(x)\), of degree n.

Reference: A&S eqn 22.5.50 and A&S eqn 22.5.51.

The Legendre polynomial is related to the Jacobi polynomials by

$$ P_n(x) = P_n^{(0,0)}(x) $$

or the Rodrigues formula

$$ P_n(x) = {1\over \kappa_n w(x)} {d^n\over dx^n}\left(w(x)\left(1-x^2\right)^n\right) $$

where

$$ \eqalign{ w(x) &= 1 \cr \kappa_n &= (-2)^n n! } $$

Some examples:

(%i1) legendre_p(1,x);
(%o1)                                  x
(%i2) legendre_p(2,x);
                                                 2
                                        3 (1 - x)
(%o2)                   (- 3 (1 - x)) + ---------- + 1
                                            2
(%i3) expand(%);
                                      2
                                   3 x    1
(%o3)                              ---- - -
                                    2     2
(%i4) expand(legendre_p(3,x));
                                     3
                                  5 x    3 x
(%o4)                             ---- - ---
                                   2      2
(%i5) expand(jacobi_p(3,0,0,x));
                                     3
                                  5 x    3 x
(%o5)                             ---- - ---
                                   2      2
Function: legendre_q (n, x)

The Legendre function of the second kind, \(Q_n(x)\) of degree n.

Reference: Abramowitz and Stegun, equations 8.5.3 and 8.1.8.

These are related to \(Q_n^m(x)\) by

$$ Q_n(x) = Q_n^0(x) $$

Some examples:

(%i1) legendre_q(0,x);
                                       x + 1
                                 log(- -----)
                                       x - 1
(%o1)                            ------------
                                      2
(%i2) legendre_q(1,x);
                                    x + 1
                              log(- -----) x - 2
                                    x - 1
(%o2)/R/                      ------------------
                                      2
(%i3) assoc_legendre_q(1,0,x);
                                    x + 1
                              log(- -----) x - 2
                                    x - 1
(%o3)/R/                      ------------------
                                      2
Function: orthopoly_recur (f, args)

Returns a recursion relation for the orthogonal function family f with arguments args. The recursion is with respect to the polynomial degree.

(%i1) orthopoly_recur (legendre_p, [n, x]);
                    (2 n + 1) P (x) x - n P     (x)
                               n           n - 1
(%o1)   P     (x) = -------------------------------
         n + 1                   n + 1

The second argument to orthopoly_recur must be a list with the correct number of arguments for the function f; if it isn’t, Maxima signals an error.

(%i1) orthopoly_recur (jacobi_p, [n, x]);

Function jacobi_p needs 4 arguments, instead it received 2
 -- an error.  Quitting.  To debug this try debugmode(true);

Additionally, when f isn’t the name of one of the families of orthogonal polynomials, an error is signalled.

(%i1) orthopoly_recur (foo, [n, x]);

A recursion relation for foo isn't known to Maxima
 -- an error.  Quitting.  To debug this try debugmode(true);
Variable: orthopoly_returns_intervals

Default value: true

When orthopoly_returns_intervals is true, floating point results are returned in the form interval (c, r), where c is the center of an interval and r is its radius. The center can be a complex number; in that case, the interval is a disk in the complex plane.

Function: orthopoly_weight (f, args)

Returns a three element list; the first element is the formula of the weight for the orthogonal polynomial family f with arguments given by the list args; the second and third elements give the lower and upper endpoints of the interval of orthogonality. For example,

(%i1) w : orthopoly_weight (hermite, [n, x]);
                            2
                         - x
(%o1)                 [%e    , - inf, inf]
(%i2) integrate(w[1]*hermite(3, x)*hermite(2, x), x, w[2], w[3]);
(%o2)                           0

The main variable of f must be a symbol; if it isn’t, Maxima signals an error.

Function: pochhammer (x, n)

The Pochhammer symbol, \((x)_n\). (See A&S eqn 6.1.22 and DLMF 5.2.iii).

For nonnegative integers n with n <= pochhammer_max_index, the expression \((x)_n\) evaluates to the product \(x(x+1)(x+2)\cdots(x+n-1)\) when \(n > 0\) and to 1 when n = 0. For negative n, \((x)_n\) is defined as \((-1)^n/(1-x)_{-n}.\)

Thus

(%i1) pochhammer (x, 3);
(%o1)                   x (x + 1) (x + 2)
(%i2) pochhammer (x, -3);
                                 1
(%o2)               - -----------------------
                      (1 - x) (2 - x) (3 - x)

To convert a Pochhammer symbol into a quotient of gamma functions, (see A&S eqn 6.1.22) use makegamma; for example

(%i1) makegamma (pochhammer (x, n));
                          gamma(x + n)
(%o1)                     ------------
                            gamma(x)

When n exceeds pochhammer_max_index or when n is symbolic, pochhammer returns a noun form.

(%i1) pochhammer (x, n);
(%o1)                         (x)
                                 n
Variable: pochhammer_max_index

Default value: 100

pochhammer (n, x) expands to a product if and only if n <= pochhammer_max_index.

Examples:

(%i1) pochhammer (x, 3), pochhammer_max_index : 3;
(%o1)                   x (x + 1) (x + 2)
(%i2) pochhammer (x, 4), pochhammer_max_index : 3;
(%o2)                         (x)
                                 4

Reference: A&S eqn 6.1.16.

Function: spherical_bessel_j (n, x)

The spherical Bessel function of the first kind, \(j_n(x).\)

Reference: A&S eqn 10.1.8 and A&S eqn 10.1.15.

It is related to the Bessel function by

$$ j_n(x) = \sqrt{\pi\over 2x} J_{n+1/2}(x) $$

Some examples:

(%i1) spherical_bessel_j(1,x);
                                sin(x)
                                ------ - cos(x)
                                  x
(%o1)                           ---------------
                                       x
(%i2) spherical_bessel_j(2,x);
                                3             3 cos(x)
                        (- (1 - --) sin(x)) - --------
                                 2               x
                                x
(%o2)                   ------------------------------
                                      x
(%i3) expand(%);
                          sin(x)    3 sin(x)   3 cos(x)
(%o3)                  (- ------) + -------- - --------
                            x           3          2
                                       x          x
(%i4) expand(sqrt(%pi/(2*x))*bessel_j(2+1/2,x)),besselexpand:true;
                          sin(x)    3 sin(x)   3 cos(x)
(%o4)                  (- ------) + -------- - --------
                            x           3          2
                                       x          x
Function: spherical_bessel_y (n, x)

The spherical Bessel function of the second kind, \(y_n(x).\)

Reference: A&S eqn 10.1.9 and A&S eqn 10.1.15.

It is related to the Bessel function by

$$ y_n(x) = \sqrt{\pi\over 2x} Y_{n+1/2}(x) $$
(%i1) spherical_bessel_y(1,x);
                                           cos(x)
                              (- sin(x)) - ------
                                             x
(%o1)                         -------------------
                                       x
(%i2) spherical_bessel_y(2,x);
                           3 sin(x)        3
                           -------- - (1 - --) cos(x)
                              x             2
                                           x
(%o2)                    - --------------------------
                                       x
(%i3) expand(%);
                          3 sin(x)    cos(x)   3 cos(x)
(%o3)                  (- --------) + ------ - --------
                              2         x          3
                             x                    x
(%i4) expand(sqrt(%pi/(2*x))*bessel_y(2+1/2,x)),besselexpand:true;
                          3 sin(x)    cos(x)   3 cos(x)
(%o4)                  (- --------) + ------ - --------
                              2         x          3
                             x                    x
Function: spherical_hankel1 (n, x)

The spherical Hankel function of the first kind, \(h_n^{(1)}(x).\)

Reference: A&S eqn 10.1.36.

This is defined by

$$ h_n^{(1)}(x) = j_n(x) + iy_n(x) $$
Function: spherical_hankel2 (n, x)

The spherical Hankel function of the second kind, \(h_n^{(2)}(x).\)

Reference: A&S eqn 10.1.17.

This is defined by

$$ h_n^{(2)}(x) = j_n(x) + iy_n(x) $$
Function: spherical_harmonic (n, m, theta, phi)

The spherical harmonic function, \(Y_n^m(\theta, \phi)\).

Spherical harmonics satisfy the angular part of Laplace’s equation in spherical coordinates.

For integers n and m such that \(n \geq |m|\) and for \(\theta \in [0, \pi]\), Maxima’s spherical harmonic function can be defined by

$$ Y_n^m(\theta, \phi) = (-1)^m \sqrt{{2n+1\over 4\pi} {(n-m)!\over (n+m)!}} P_n^m(\cos\theta) e^{im\phi} $$

Further, when \(n < |m|\), the spherical harmonic function vanishes.

The factor (-1)^m, frequently used in Quantum mechanics, is called the Condon-Shortely phase. Some references, including NIST Digital Library of Mathematical Functions omit this factor; see http://dlmf.nist.gov/14.30.E1.

Reference: Merzbacher 9.64.

Some examples:

(%i1) spherical_harmonic(1,0,theta,phi);
                              sqrt(3) cos(theta)
(%o1)                         ------------------
                                 2 sqrt(%pi)
(%i2) spherical_harmonic(1,1,theta,phi);
                                    %i phi
                          sqrt(3) %e       sin(theta)
(%o2)                     ---------------------------
                                 3/2
                                2    sqrt(%pi)
(%i3) spherical_harmonic(1,-1,theta,phi);
                                    - %i phi
                          sqrt(3) %e         sin(theta)
(%o3)                   - -----------------------------
                                  3/2
                                 2    sqrt(%pi)
(%i4) spherical_harmonic(2,0,theta,phi);
                                                              2
                                            3 (1 - cos(theta))
          sqrt(5) ((- 3 (1 - cos(theta))) + ------------------- + 1)
                                                     2
(%o4)     ----------------------------------------------------------
                                 2 sqrt(%pi)
(%i5) factor(%);
                                        2
                          sqrt(5) (3 cos (theta) - 1)
(%o5)                     ---------------------------
                                  4 sqrt(%pi)
Function: unit_step (x)

The left-continuous unit step function; thus unit_step (x) vanishes for x <= 0 and equals 1 for x > 0.

If you want a unit step function that takes on the value 1/2 at zero, use `hstep'.

Function: ultraspherical (n, a, x)

The ultraspherical polynomial, \(C_n^{(a)}(x)\) (also known as the Gegenbauer polynomial).

Reference: A&S eqn 22.5.46.

These polynomials can be given in terms of Jacobi polynomials:

$$ C_n^{(\alpha)}(x) = {\Gamma\left(\alpha + {1\over 2}\right) \over \Gamma(2\alpha)} {\Gamma(n+2\alpha) \over \Gamma\left(n+\alpha + {1\over 2}\right)} P_n^{(\alpha-1/2, \alpha-1/2)}(x) $$

or the series

$$ C_n^{(\alpha)}(x) = \sum_{k=0}^{\lfloor n/2 \rfloor} {(-1)^k (\alpha)_{n-k} \over k! (n-2k)!}(2x)^{n-2k} $$

or the Rodrigues formula

$$ C_n^{(\alpha)}(x) = {1\over \kappa_n w(x)} {d^n\over dx^n}\left(w(x)\left(1-x^2\right)^n\right) $$

where

$$ \eqalign{ w(x) &= \left(1-x^2\right)^{\alpha-{1\over 2}} \cr \kappa_n &= {(-2)^n\left(\alpha + {1\over 2}\right)_n n!\over (2\alpha)_n} \cr } $$

Some examples:

(%i1) ultraspherical(1,a,x);
                                   (2 a + 1) (1 - x)
(%o1)                     2 a (1 - -----------------)
                                              1
                                       2 (a + -)
                                              2
(%i2) factor(%);
(%o2)                                2 a x
(%i3) factor(ultraspherical(2,a,x));
                                     2      2
(%o3)                        a (2 a x  + 2 x  - 1)

Next: , Previous: orthopoly-pkg, Up: Top   [Contents][Index]

65 romberg


Up: romberg-pkg   [Contents][Index]

65.1 Functions and Variables for romberg

Function: romberg
    romberg (expr, x, a, b)
    romberg (F, a, b)

Computes a numerical integration by Romberg’s method.

romberg(expr, x, a, b) returns an estimate of the integral integrate(expr, x, a, b). expr must be an expression which evaluates to a floating point value when x is bound to a floating point value.

romberg(F, a, b) returns an estimate of the integral integrate(F(x), x, a, b) where x represents the unnamed, sole argument of F; the actual argument is not named x. F must be a Maxima or Lisp function which returns a floating point value when the argument is a floating point value. F may name a translated or compiled Maxima function.

The accuracy of romberg is governed by the global variables rombergabs and rombergtol. romberg terminates successfully when the absolute difference between successive approximations is less than rombergabs, or the relative difference in successive approximations is less than rombergtol. Thus when rombergabs is 0.0 (the default) only the relative error test has any effect on romberg.

romberg halves the stepsize at most rombergit times before it gives up; the maximum number of function evaluations is therefore 2^rombergit. If the error criterion established by rombergabs and rombergtol is not satisfied, romberg prints an error message. romberg always makes at least rombergmin iterations; this is a heuristic intended to prevent spurious termination when the integrand is oscillatory.

romberg repeatedly evaluates the integrand after binding the variable of integration to a specific value (and not before). This evaluation policy makes it possible to nest calls to romberg, to compute multidimensional integrals. However, the error calculations do not take the errors of nested integrations into account, so errors may be underestimated. Also, methods devised especially for multidimensional problems may yield the same accuracy with fewer function evaluations.

See also Introduction to QUADPACK, a collection of numerical integration functions.

Examples:

A 1-dimensional integration.

(%i1) f(x) := 1/((x - 1)^2 + 1/100) + 1/((x - 2)^2 + 1/1000)
              + 1/((x - 3)^2 + 1/200);
                    1                 1                1
(%o1) f(x) := -------------- + --------------- + --------------
                     2    1           2    1            2    1
              (x - 1)  + ---   (x - 2)  + ----   (x - 3)  + ---
                         100              1000              200
(%i2) rombergtol : 1e-6;
(%o2)                 9.999999999999999e-7
(%i3) rombergit : 15;
(%o3)                          15
(%i4) estimate : romberg (f(x), x, -5, 5);
(%o4)                   173.6730736617464
(%i5) exact : integrate (f(x), x, -5, 5);
        3/2          3/2      3/2          3/2
(%o5) 10    atan(7 10   ) + 10    atan(3 10   )
      3/2         9/2       3/2         5/2
 + 5 2    atan(5 2   ) + 5 2    atan(5 2   ) + 10 atan(60)
 + 10 atan(40)
(%i6) abs (estimate - exact) / exact, numer;
(%o6)                 7.552722451569877e-11

A 2-dimensional integration, implemented by nested calls to romberg.

(%i1) g(x, y) := x*y / (x + y);
                                    x y
(%o1)                   g(x, y) := -----
                                   x + y
(%i2) rombergtol : 1e-6;
(%o2)                 9.999999999999999e-7
(%i3) estimate : romberg (romberg (g(x, y), y, 0, x/2), x, 1, 3);
(%o3)                  0.8193023962835647
(%i4) assume (x > 0);
(%o4)                        [x > 0]
(%i5) integrate (integrate (g(x, y), y, 0, x/2), x, 1, 3);
                                           3
                                     2 log(-) - 1
                    9                      2        9
(%o5)      (- 9 log(-)) + 9 log(3) + ------------ + -
                    2                     6         2
(%i6) exact : radcan (%);
                    26 log(3) - 26 log(2) - 13
(%o6)             - --------------------------
                                3
(%i7) abs (estimate - exact) / exact, numer;
(%o7)                 1.371197987185102e-10
Option variable: rombergabs

Default value: 0.0

The accuracy of romberg is governed by the global variables rombergabs and rombergtol. romberg terminates successfully when the absolute difference between successive approximations is less than rombergabs, or the relative difference in successive approximations is less than rombergtol. Thus when rombergabs is 0.0 (the default) only the relative error test has any effect on romberg.

See also rombergit and rombergmin.

Option variable: rombergit

Default value: 11

romberg halves the stepsize at most rombergit times before it gives up; the maximum number of function evaluations is therefore 2^rombergit. romberg always makes at least rombergmin iterations; this is a heuristic intended to prevent spurious termination when the integrand is oscillatory.

See also rombergabs and rombergtol.

Option variable: rombergmin

Default value: 0

romberg always makes at least rombergmin iterations; this is a heuristic intended to prevent spurious termination when the integrand is oscillatory.

See also rombergit, rombergabs, and rombergtol.

Option variable: rombergtol

Default value: 1e-4

The accuracy of romberg is governed by the global variables rombergabs and rombergtol. romberg terminates successfully when the absolute difference between successive approximations is less than rombergabs, or the relative difference in successive approximations is less than rombergtol. Thus when rombergabs is 0.0 (the default) only the relative error test has any effect on romberg.

See also rombergit and rombergmin.


Next: , Previous: romberg-pkg, Up: Top   [Contents][Index]

66 simplex


Next: , Previous: simplex-pkg, Up: simplex-pkg   [Contents][Index]

66.1 Introduction to simplex

simplex is a package for linear optimization using the simplex algorithm.

Example:

(%i1) load("simplex")$
(%i2) minimize_lp(x+y, [3*x+2*y>2, x+4*y>3]);
                  9        7       1
(%o2)            [--, [y = --, x = -]]
                  10       10      5

66.1.1 Tests for simplex

There are some tests in the directory share/simplex/Tests.

66.1.1.1 klee_minty

The function klee_minty produces input for linear_program, for which exponential time for solving is required without scaling.

Example:

load("klee_minty")$
apply(linear_program, klee_minty(6));

A better approach:

epsilon_sx : 0$
scale_sx : true$
apply(linear_program, klee_minty(10));

66.1.1.2 NETLIB

Some smaller problems from netlib (https://www.netlib.org/lp/data/) test suite are converted to a format, readable by Maxima. Problems are adlittle, afiro, kb2, sc50a and share2b. Each problem has three input files in CSV format for matrix A and vectors b and c.

Example:

A : read_matrix("adlittle_A.csv", 'csv)$
b : read_list("adlittle_b.csv", 'csv)$
c : read_list("adlittle_c.csv", 'csv)$
linear_program(A, b, c)$
%[2];
=> 225494.9631623802

Results:

PROBLEM        MINIMUM                  SCALING
adlittle       +2.2549496316E+05        false
afiro          -4.6475314286E+02        false
kb2            -1.7499001299E+03        true
sc50a          -6.4575077059E+01        false
share2b        -4.1573518187E+02        false

The Netlib website https://www.netlib.org/lp/data/readme lists the values as

PROBLEM        MINIMUM
adlittle       +2.2549496316E+05
afiro          -4.6475314286E+02
kb2            -1.7499001299E+03
sc50a          -6.4575077059E+01
share2b        -4.1573224074E+02

Previous: Introduction to simplex, Up: simplex-pkg   [Contents][Index]

66.2 Functions and Variables for simplex

Option variable: epsilon_lp

Default value: 10^-8

Epsilon used for numerical computations in linear_program; it is set to 0 in linear_program when all inputs are rational.

Example:

(%i1) load("simplex")$

(%i2) minimize_lp(-x, [1e-9*x + y <= 1], [x,y]);
Warning: linear_program(A,b,c): non-rat inputs found, epsilon_lp= 1.0e-8
Warning: Solution may be incorrect.
(%o2)                        Problem not bounded!
(%i3) minimize_lp(-x, [10^-9*x + y <= 1], [x,y]);
(%o3)               [- 1000000000, [y = 0, x = 1000000000]]
(%i4) minimize_lp(-x, [1e-9*x + y <= 1], [x,y]), epsilon_lp=0;
(%o4)     [- 9.999999999999999e+8, [y = 0, x = 9.999999999999999e+8]]

See also: linear_program, `ratnump'.

Function: linear_program (A, b, c)

linear_program is an implementation of the simplex algorithm. linear_program(A, b, c) computes a vector x for which c.x is minimum possible among vectors for which A.x = b and x >= 0. Argument A is a matrix and arguments b and c are lists.

linear_program returns a list which contains the minimizing vector x and the minimum value c.x. If the problem is not bounded, it returns "Problem not bounded!" and if the problem is not feasible, it returns "Problem not feasible!".

To use this function first load the simplex package with load("simplex");.

Example:

(%i2) A: matrix([1,1,-1,0], [2,-3,0,-1], [4,-5,0,0])$
(%i3) b: [1,1,6]$
(%i4) c: [1,-2,0,0]$
(%i5) linear_program(A, b, c);
                   13     19        3
(%o5)            [[--, 4, --, 0], - -]
                   2      2         2

See also: minimize_lp, scale_lp, and epsilon_lp.

Function: maximize_lp (obj, cond, [pos])

Maximizes linear objective function obj subject to some linear constraints cond. See minimize_lp for detailed description of arguments and return value.

See also: minimize_lp.

Function: minimize_lp (obj, cond, [pos])

Minimizes a linear objective function obj subject to some linear constraints cond. cond a list of linear equations or inequalities. In strict inequalities > is replaced by >= and < by <=. The optional argument pos is a list of decision variables which are assumed to be positive.

If the minimum exists, minimize_lp returns a list which contains the minimum value of the objective function and a list of decision variable values for which the minimum is attained. If the problem is not bounded, minimize_lp returns "Problem not bounded!" and if the problem is not feasible, it returns "Problem not feasible!".

The decision variables are not assumed to be non-negative by default. If all decision variables are non-negative, set nonnegative_lp to true or include all in the optional argument pos. If only some of decision variables are positive, list them in the optional argument pos (note that this is more efficient than adding constraints).

minimize_lp uses the simplex algorithm which is implemented in maxima linear_program function.

To use this function first load the simplex package with load("simplex");.

Examples:

(%i1) minimize_lp(x+y, [3*x+y=0, x+2*y>2]);
                      4       6        2
(%o1)                [-, [y = -, x = - -]]
                      5       5        5
(%i2) minimize_lp(x+y, [3*x+y>0, x+2*y>2]), nonnegative_lp=true;
(%o2)                [1, [y = 1, x = 0]]
(%i3) minimize_lp(x+y, [3*x+y>0, x+2*y>2], all);
(%o3)                         [1, [y = 1, x = 0]]
(%i4) minimize_lp(x+y, [3*x+y=0, x+2*y>2]), nonnegative_lp=true;
(%o4)                Problem not feasible!
(%i5) minimize_lp(x+y, [3*x+y>0]);
(%o5)                Problem not bounded!

There is also a limited ability to solve linear programs with symbolic constants.

(%i1) declare(c,constant)$
(%i2) maximize_lp(x+y, [y<=-x/c+3, y<=-x+4], [x, y]), epsilon_lp=0;
Is (c-1)*c positive, negative or zero?
p;
Is c*(2*c-1) positive, negative or zero?
p;
Is c positive or negative?
p;
Is c-1 positive, negative or zero?
p;
Is 2*c-1 positive, negative or zero?
p;
Is 3*c-4 positive, negative or zero?
p;
                                 1                1
(%o2)                 [4, [x = -----, y = 3 - ---------]]
                                   1               1
                               1 - -          (1 - -) c
                                   c               c
(%i1) (assume(c>4/3), declare(c,constant))$
(%i2) maximize_lp(x+y, [y<=-x/c+3, y<=-x+4], [x, y]), epsilon_lp=0;
                                 1                1
(%o2)                 [4, [x = -----, y = 3 - ---------]]
                                   1               1
                               1 - -          (1 - -) c
                                   c               c

See also: maximize_lp, nonnegative_lp, epsilon_lp.

Option variable: nonnegative_lp
Option variable: nonegative_lp

Default value: false

If nonnegative_lp is true all decision variables to minimize_lp and maximize_lp are assumed to be non-negative. nonegative_lp is a deprecated alias.

See also: minimize_lp.

Option variable: scale_lp

Default value: false

When scale_lp is true, linear_program scales its input so that the maximum absolute value in each row or column is 1.

Variable: pivot_count_sx

After linear_program returns, pivot_count_sx is the number of pivots in last computation.

Variable: pivot_max_sx

pivot_max_sx is the maximum number of pivots allowed by linear_program.


Next: , Previous: simplex-pkg, Up: Top   [Contents][Index]

67 simplification


Next: , Previous: simplification-pkg, Up: simplification-pkg   [Contents][Index]

67.1 Introduction to simplification

The directory maxima/share/simplification contains several scripts which implement simplification rules and functions, and also some functions not related to simplification.


Next: , Previous: Introduction to simplification, Up: simplification-pkg   [Contents][Index]

67.2 Package absimp

The absimp package contains pattern-matching rules that extend the built-in simplification rules for the abs and signum functions. absimp respects relations established with the built-in assume function and by declarations such as mode_declare (m, even, n, odd) for even or odd integers.

absimp defines unitramp and unitstep functions in terms of abs and signum.

load ("absimp") loads this package. demo ("absimp") shows a demonstration of this package.

Examples:

(%i1) load ("absimp")$
(%i2) (abs (x))^2;
                                2
(%o2)                          x
(%i3) diff (abs (x), x);
                               x
(%o3)                        ------
                             abs(x)
(%i4) cosh (abs (x));
(%o4)                        cosh(x)

Next: , Previous: Package absimp, Up: simplification-pkg   [Contents][Index]

67.3 Package facexp

The facexp package contains several related functions that provide the user with the ability to structure expressions by controlled expansion. This capability is especially useful when the expression contains variables that have physical meaning, because it is often true that the most economical form of such an expression can be obtained by fully expanding the expression with respect to those variables, and then factoring their coefficients. While it is true that this procedure is not difficult to carry out using standard Maxima functions, additional fine-tuning may also be desirable, and these finishing touches can be more difficult to apply.

The function facsum and its related forms provide a convenient means for controlling the structure of expressions in this way. Another function, collectterms, can be used to add two or more expressions that have already been simplified to this form, without resimplifying the whole expression again. This function may be useful when the expressions are very large.

load ("facexp") loads this package. demo ("facexp") shows a demonstration of this package.

Function: facsum (expr, arg_1, ..., arg_n)

Returns a form of expr which depends on the arguments arg_1, ..., arg_n. The arguments can be any form suitable for ratvars, or they can be lists of such forms. If the arguments are not lists, then the form returned is fully expanded with respect to the arguments, and the coefficients of the arguments are factored. These coefficients are free of the arguments, except perhaps in a non-rational sense.

If any of the arguments are lists, then all such lists are combined into a single list, and instead of calling factor on the coefficients of the arguments, facsum calls itself on these coefficients, using this newly constructed single list as the new argument list for this recursive call. This process can be repeated to arbitrary depth by nesting the desired elements in lists.

It is possible that one may wish to facsum with respect to more complicated subexpressions, such as log (x + y). Such arguments are also permissible.

Occasionally the user may wish to obtain any of the above forms for expressions which are specified only by their leading operators. For example, one may wish to facsum with respect to all log’s. In this situation, one may include among the arguments either the specific log’s which are to be treated in this way, or alternatively, either the expression operator (log) or 'operator (log). If one wished to facsum the expression expr with respect to the operators op_1, ..., op_n, one would evaluate facsum (expr, operator (op_1, ..., op_n)). The operator form may also appear inside list arguments.

In addition, the setting of the switches facsum_combine and nextlayerfactor may affect the result of facsum.

Global variable: nextlayerfactor

Default value: false

When nextlayerfactor is true, recursive calls of facsum are applied to the factors of the factored form of the coefficients of the arguments.

When false, facsum is applied to each coefficient as a whole whenever recursive calls to facsum occur.

Inclusion of the atom nextlayerfactor in the argument list of facsum has the effect of nextlayerfactor: true, but for the next level of the expression only. Since nextlayerfactor is always bound to either true or false, it must be presented single-quoted whenever it appears in the argument list of facsum.

Global variable: facsum_combine

Default value: true

facsum_combine controls the form of the final result returned by facsum when its argument is a quotient of polynomials. If facsum_combine is false then the form will be returned as a fully expanded sum as described above, but if true, then the expression returned is a ratio of polynomials, with each polynomial in the form described above.

The true setting of this switch is useful when one wants to facsum both the numerator and denominator of a rational expression, but does not want the denominator to be multiplied through the terms of the numerator.

Function: factorfacsum (expr, arg_1, ... arg_n)

Returns a form of expr which is obtained by calling facsum on the factors of expr with arg_1, ... arg_n as arguments. If any of the factors of expr is raised to a power, both the factor and the exponent will be processed in this way.

Function: collectterms (expr, arg_1, …, arg_n)

Collects all terms that contain arg_1 ... arg_n. If several expressions have been simplified with the following functions facsum, factorfacsum, factenexpand, facexpten or factorfacexpten, and they are to be added together, it may be desirable to combine them using the function collecterms. collecterms can take as arguments all of the arguments that can be given to these other associated functions with the exception of nextlayerfactor, which has no effect on collectterms. The advantage of collectterms is that it returns a form similar to facsum, but since it is adding forms that have already been processed by facsum, it does not need to repeat that effort. This capability is especially useful when the expressions to be summed are very large.

See also factor.

Example:

(%i1) (exp(x)+2)*x+exp(x);
                             x          x
(%o1)                   x (%e  + 2) + %e
(%i2) collectterms(expand(%),exp(x));
                                  x
(%o2)                   (x + 1) %e  + 2 x

Next: , Previous: Package facexp, Up: simplification-pkg   [Contents][Index]

67.4 Package functs

Function: rempart (expr, n)

Removes part n from the expression expr.

If n is a list of the form [l, m] then parts l thru m are removed.

To use this function write first load("functs").

Function: wronskian ([f_1, ..., f_n], x)

Returns the Wronskian matrix of the list of expressions [f_1, ..., f_n] in the variable x. The determinant of the Wronskian matrix is the Wronskian determinant of the list of expressions.

To use wronskian, first load("functs"). Example:

(%i1) load ("functs")$
(%i2) wronskian([f(x), g(x)],x);
                    [   f(x)       g(x)    ]
                    [                      ]
(%o2)               [ d          d         ]
                    [ -- (f(x))  -- (g(x)) ]
                    [ dx         dx        ]
Function: tracematrix (M)

Returns the trace (sum of the diagonal elements) of matrix M.

To use this function write first load("functs").

Function: rational (z)

Multiplies numerator and denominator of z by the complex conjugate of denominator, thus rationalizing the denominator. Returns canonical rational expression (CRE) form if given one, else returns general form.

To use this function write first load("functs").

Function: nonzeroandfreeof (x, expr)

Returns true if expr is nonzero and freeof (x, expr) returns true. Returns false otherwise.

To use this function write first load("functs").

Function: linear (expr, x)

When expr is an expression of the form a*x + b where a is nonzero, and a and b are free of x, linear returns a list of three equations, one for each of the three formal variables b, a, and x. Otherwise, linear returns false.

load("antid") loads this function.

Example:

(%i1) load ("antid");
(%o1)  /maxima/share/integration/antid.mac
(%i2) linear ((1 - w)*(1 - x)*z, z);
(%o2) [bargumentb = 0, aargumenta = (w - 1) x - w + 1, 
                                                  xargumentx = z]
(%i3) linear (cos(u - v) + cos(u + v), u);
(%o3)                         false
Function: gcdivide (p, q)

When the option variable takegcd is true which is the default, gcdivide divides the polynomials p and q by their greatest common divisor and returns the ratio of the results. gcdivde calls the function ezgcd to divide the polynomials by the greatest common divisor.

When takegcd is false, gcdivide returns the ratio p/q.

To use this function write first load("functs").

See also ezgcd, gcd, gcdex, and poly_gcd.

Example:

(%i1) load("functs")$

(%i2) p1:6*x^3+19*x^2+19*x+6; 
                        3       2
(%o2)                6 x  + 19 x  + 19 x + 6
(%i3) p2:6*x^5+13*x^4+12*x^3+13*x^2+6*x;
                  5       4       3       2
(%o3)          6 x  + 13 x  + 12 x  + 13 x  + 6 x
(%i4) gcdivide(p1, p2);
                             x + 1
(%o4)                        ------
                              3
                             x  + x
(%i5) takegcd:false;
(%o5)                         false
(%i6) gcdivide(p1, p2);
                       3       2
                    6 x  + 19 x  + 19 x + 6
(%o6)          ----------------------------------
                  5       4       3       2
               6 x  + 13 x  + 12 x  + 13 x  + 6 x
(%i7) ratsimp(%);
                             x + 1
(%o7)                        ------
                              3
                             x  + x
Function: arithmetic (a, d, n)

Returns the n-th term of the arithmetic series a, a + d, a + 2*d, ..., a + (n - 1)*d.

To use this function write first load("functs").

Function: geometric (a, r, n)

Returns the n-th term of the geometric series a, a*r, a*r^2, ..., a*r^(n - 1).

To use this function write first load("functs").

Function: harmonic (a, b, c, n)

Returns the n-th term of the harmonic series a/b, a/(b + c), a/(b + 2*c), ..., a/(b + (n - 1)*c).

To use this function write first load("functs").

Function: arithsum (a, d, n)

Returns the sum of the arithmetic series from 1 to n.

To use this function write first load("functs").

Function: geosum (a, r, n)

Returns the sum of the geometric series from 1 to n. If n is infinity (inf) then a sum is finite only if the absolute value of r is less than 1.

To use this function write first load("functs").

Function: gaussprob (x)

Returns the Gaussian probability function %e^(-x^2/2) / sqrt(2*%pi).

To use this function write first load("functs").

Function: gd (x)

Returns the Gudermannian function 2*atan(%e^x)-%pi/2.

To use this function write first load("functs").

Function: agd (x)

Returns the inverse Gudermannian function log (tan (%pi/4 + x/2)).

To use this function write first load("functs").

Function: vers (x)

Returns the versed sine 1 - cos (x).

To use this function write first load("functs").

Function: covers (x)

Returns the coversed sine 1 - sin (x).

To use this function write first load("functs").

Function: exsec (x)

Returns the exsecant sec (x) - 1.

To use this function write first load("functs").

Function: hav (x)

Returns the haversine (1 - cos(x))/2.

To use this function write first load("functs").

Function: combination (n, r)

Returns the number of combinations of n objects taken r at a time.

To use this function write first load("functs").

Function: permutation (n, r)

Returns the number of permutations of r objects selected from a set of n objects.

To use this function write first load("functs").


Next: , Previous: Package functs, Up: simplification-pkg   [Contents][Index]

67.5 Package ineq

The ineq package contains simplification rules for inequalities.

Example session:

(%i1) load("ineq")$
tellsimp: warning: rule will treat '+
                          ' as noncommutative and nonassociative.
tellsimp: warning: rule will treat '+
                          ' as noncommutative and nonassociative.
tellsimp: warning: rule will treat '+
                          ' as noncommutative and nonassociative.
tellsimp: warning: rule will treat '+
                          ' as noncommutative and nonassociative.
tellsimp: warning: rule will treat '+
                          ' as noncommutative and nonassociative.
tellsimp: warning: rule will treat '+
                          ' as noncommutative and nonassociative.
tellsimp: warning: rule will treat '+
                          ' as noncommutative and nonassociative.
tellsimp: warning: rule will treat '+
                          ' as noncommutative and nonassociative.
(%i2) a>=4;  /* a sample inequality */
(%o2)                        a >= 4
(%o3)                     b + a > c + 4
(%o4)                       7 x < 7 y
(%o5)                    - 2 x <= - 6 z
                                 2
(%o6)                      1 <= a  + 1
(%o8)                       2 x < 3 x
(%o9)                        a >= b
(%o10)                   a + 3 >= b + 3
(%o11)                       a >= b
(%o12)                     a >= c - b
(%o13)                     b + a >= c
(%o14)                 (- c) + b + a >= 0
(%o15)                   c - b - a <= 0
                               2
(%o16)                  (z - 1)  > - 2 z
                            2
(%o17)                     z  + 1 > 0
(%o18)                        true
(%i19) (b>c)+%; /* add a second, strict inequality */

Be careful about using parentheses around the inequalities: when the user types in (A > B) + (C = 5) the result is A + C > B + 5, but A > B + C = 5 is a syntax error, and (A > B + C) = 5 is something else entirely.

Do disprule (all) to see a complete listing of the rule definitions.

The user will be queried if Maxima is unable to decide the sign of a quantity multiplying an inequality.

The most common mis-feature is illustrated by:

(%i1) eq: a > b;
(%o1)                         a > b
(%i2) 2*eq;
(%o2)                       2 (a > b)
(%i3) % - eq;
(%o3)                         a > b

Another problem is 0 times an inequality; the default to have this turn into 0 has been left alone. However, if you type X*some_inequality and Maxima asks about the sign of X and you respond zero (or z), the program returns X*some_inequality and not use the information that X is 0. You should do ev (%, x: 0) in such a case, as the database will only be used for comparison purposes in decisions, and not for the purpose of evaluating X.

The user may note a slower response when this package is loaded, as the simplifier is forced to examine more rules than without the package, so you might wish to remove the rules after making use of them. Do kill (rules) to eliminate all of the rules (including any that you might have defined); or you may be more selective by killing only some of them; or use remrule on a specific rule.

Note that if you load this package after defining your own rules you will clobber your rules that have the same name. The rules in this package are: *rule1, ..., *rule8, +rule1, ..., +rule18, and you must enclose the rulename in quotes to refer to it, as in remrule ("+", "+rule1") to specifically remove the first rule on "+" or disprule ("*rule2") to display the definition of the second multiplicative rule.


Next: , Previous: Package ineq, Up: simplification-pkg   [Contents][Index]

67.6 Package rducon

Function: reduce_consts (expr)

Replaces constant subexpressions of expr with constructed constant atoms, saving the definition of all these constructed constants in the list of equations const_eqns, and returning the modified expr. Those parts of expr are constant which return true when operated on by the function constantp. Hence, before invoking reduce_consts, one should do

declare ([objects to be given the constant property], constant)$

to set up a database of the constant quantities occurring in your expressions.

If you are planning to generate Fortran output after these symbolic calculations, one of the first code sections should be the calculation of all constants. To generate this code segment, do

map ('fortran, const_eqns)$

Variables besides const_eqns which affect reduce_consts are:

const_prefix (default value: xx) is the string of characters used to prefix all symbols generated by reduce_consts to represent constant subexpressions.

const_counter (default value: 1) is the integer index used to generate unique symbols to represent each constant subexpression found by reduce_consts.

load ("rducon") loads this function. demo ("rducon") shows a demonstration of this function.


Previous: Package rducon, Up: simplification-pkg   [Contents][Index]

67.7 Package scifac

Function: gcfac (expr)

gcfac is a factoring function that attempts to apply the same heuristics which scientists apply in trying to make expressions simpler. gcfac is limited to monomial-type factoring. For a sum, gcfac does the following:

  1. Factors over the integers.
  2. Factors out the largest powers of terms occurring as coefficients, regardless of the complexity of the terms.
  3. Uses (1) and (2) in factoring adjacent pairs of terms.
  4. Repeatedly and recursively applies these techniques until the expression no longer changes.

Item (3) does not necessarily do an optimal job of pairwise factoring because of the combinatorially-difficult nature of finding which of all possible rearrangements of the pairs yields the most compact pair-factored result.

load ("scifac") loads this function. demo ("scifac") shows a demonstration of this function.


Next: , Previous: simplification-pkg, Up: Top   [Contents][Index]

68 solve_rec


Next: , Previous: solve_rec-pkg, Up: solve_rec-pkg   [Contents][Index]

68.1 Introduction to solve_rec

solve_rec is a package for solving linear recurrences with polynomial coefficients.

A demo is available with demo("solve_rec");.

Example:

(%i1) load("solve_rec")$
(%i2) solve_rec((n+4)*s[n+2] + s[n+1] - (n+1)*s[n], s[n]);
                                    n
                 %k  (2 n + 3) (- 1)          %k
                   1                            2
(%o2)       s  = -------------------- + ---------------
             n     (n + 1) (n + 2)      (n + 1) (n + 2)

Previous: Introduction to solve_rec, Up: solve_rec-pkg   [Contents][Index]

68.2 Functions and Variables for solve_rec

Function: harmonic_number (x)

When x is positive integer n, harmonic_number is the n’th harmonic number. More generally, harmonic_number(x) = psi[0](x+1) + %gamma. (See polygamma).

(%i1) load("simplify_sum")$
(%i2) harmonic_number(5);
                               137
(%o2)                          ---
                               60
(%i3) sum(1/k, k, 1, 5);
                               137
(%o3)                          ---
                               60
(%i4) float(harmonic_number(sqrt(2)));
(%o4)              %gamma + 0.6601971549171388
(%i5) float(psi[0](1+sqrt(2)))+%gamma;
(%o5)              %gamma + 0.6601971549171388
Function: harmonic_to_psi (x)

Converts expressions with harmonic_number to the equivalent expression involving psi[0] (see polygamma).

(%i1) load("simplify_sum")$
(%i2) harmonic_to_psi(harmonic_number(sqrt(2)));
(%o2)              psi (sqrt(2) + 1) + %gamma
                      0
Function: reduce_order (rec, sol, var)

Reduces the order of linear recurrence rec when a particular solution sol is known. The reduced reccurence can be used to get other solutions.

Example:

(%i3) rec: x[n+2] = x[n+1] + x[n]/n;
                                      x
                                       n
(%o3)               x      = x      + --
                     n + 2    n + 1   n
(%i4) solve_rec(rec, x[n]);
WARNING: found some hypergeometrical solutions! 
(%o4)                    x  = %k  n
                          n     1
(%i5) reduce_order(rec, n, x[n]);
(%t5)                    x  = n %z
                          n       n

                           n - 1
                           ====
                           \
(%t6)                %z  =  >     %u
                       n   /        %j
                           ====
                           %j = 0

(%o6)             (- n - 2) %u     - %u
                              n + 1     n
(%i6) solve_rec((n+2)*%u[n+1] + %u[n], %u[n]);
                                     n
                            %k  (- 1)
                              1
(%o6)                 %u  = ----------
                        n    (n + 1)!

So the general solution is

             n - 1
             ====        j
             \      (- 1)
       %k  n  >    -------- + %k  n
         2   /     (j + 1)!     1
             ====
             j = 0
Option variable: simplify_products

Default value: true

If simplify_products is true, solve_rec will try to simplify products in result.

See also: solve_rec.

Function: simplify_sum (expr)

Tries to simplify all sums appearing in expr to a closed form.

To use this function first load the simplify_sum package with load("simplify_sum").

Example:

(%i1) load("simplify_sum")$
(%i2) sum(binomial(n+k,k)/2^k, k, 1, n) + sum(binomial(2*n, 2*k), k, 1,n);
        n                          n
       ====                       ====
       \     binomial(n + k, k)   \
(%o2)   >    ------------------ +  >    binomial(2 n, 2 k)
       /              k           /
       ====          2            ====
       k = 1                      k = 1
(%i3) simplify_sum(%);
                         2 n - 1    n
(%o3)                   2        + 2  - 2
Function: solve_rec (eqn, var, [init])

Solves for hypergeometrical solutions to linear recurrence eqn with polynomials coefficient in variable var. Optional arguments init are initial conditions.

solve_rec can solve linear recurrences with constant coefficients, finds hypergeometrical solutions to homogeneous linear recurrences with polynomial coefficients, rational solutions to linear recurrences with polynomial coefficients and can solve Ricatti type recurrences.

Note that the running time of the algorithm used to find hypergeometrical solutions is exponential in the degree of the leading and trailing coefficient.

To use this function first load the solve_rec package with load("solve_rec");.

Example of linear recurrence with constant coefficients:

(%i2) solve_rec(a[n]=a[n-1]+a[n-2]+n/2^n, a[n]);
                        n          n
           (sqrt(5) - 1)  %k  (- 1)
                            1           n
(%o2) a  = ------------------------- - ----
       n               n                  n
                      2                5 2
                                                n
                                   (sqrt(5) + 1)  %k
                                                    2    2
                                 + ------------------ - ----
                                            n              n
                                           2            5 2

Example of linear recurrence with polynomial coefficients:

(%i7) 2*x*(x+1)*y[x] - (x^2+3*x-2)*y[x+1] + (x-1)*y[x+2];
                         2
(%o7) (x - 1) y      - (x  + 3 x - 2) y      + 2 x (x + 1) y
               x + 2                   x + 1                x
(%i8) solve_rec(%, y[x], y[1]=1, y[3]=3);
                              x
                           3 2    x!
(%o9)                 y  = ---- - --
                       x    4     2

Example of Ricatti type recurrence:

(%i2) x*y[x+1]*y[x] - y[x+1]/(x+2) + y[x]/(x-1) = 0;
                            y         y
                             x + 1     x
(%o2)         x y  y      - ------ + ----- = 0
                 x  x + 1   x + 2    x - 1
(%i3) solve_rec(%, y[x], y[3]=5)$
(%i4) ratsimp(minfactorial(factcomb(%)));
                                   3
                               30 x  - 30 x
(%o4) y  = - -------------------------------------------------
       x        6      5       4       3       2
             5 x  - 3 x  - 25 x  + 15 x  + 20 x  - 12 x - 1584

See also: solve_rec_rat, simplify_products and product_use_gamma.

Function: solve_rec_rat (eqn, var, [init])

Solves for rational solutions to linear recurrences. See solve_rec for description of arguments.

To use this function first load the solve_rec package with load("solve_rec");.

Example:

(%i1) (x+4)*a[x+3] + (x+3)*a[x+2] - x*a[x+1] + (x^2-1)*a[x];
(%o1)  (x + 4) a      + (x + 3) a      - x a
                x + 3            x + 2      x + 1
                                                   2
                                               + (x  - 1) a
                                                            x
(%i2) solve_rec_rat(% = (x+2)/(x+1), a[x]);
                       1
(%o2)      a  = ---------------
            x   (x - 1) (x + 1)

See also: solve_rec.

Option variable: product_use_gamma

Default value: true

When simplifying products, solve_rec introduces gamma function into the expression if product_use_gamma is true.

See also: simplify_products, solve_rec.

Function: summand_to_rec
    summand_to_rec (summand, k, n)
    summand_to_rec (summand, [k, lo, hi], n)

Returns the recurrence satisfied by the sum

     hi
    ====
    \
     >     summand
    /
    ====
  k = lo

where summand is hypergeometrical in k and n. If lo and hi are omitted, they are assumed to be lo = -inf and hi = inf.

To use this function first load the simplify_sum package with load("simplify_sum").

Example:

(%i1) load("simplify_sum")$
(%i2) summand: binom(n,k);
(%o2)                           binomial(n, k)
(%i3) summand_to_rec(summand,k,n);
(%o3)                      2 sm  - sm      = 0
                               n     n + 1
(%i7) summand: binom(n, k)/(k+1);
                                binomial(n, k)
(%o7)                           --------------
                                    k + 1
(%i8) summand_to_rec(summand, [k, 0, n], n);
(%o8)               2 (n + 1) sm  - (n + 2) sm      = - 1
                                n             n + 1

Next: , Previous: solve_rec-pkg, Up: Top   [Contents][Index]

69 stats


Next: , Up: stats-pkg   [Contents][Index]

69.1 Introduction to stats

Package stats contains a set of classical statistical inference and hypothesis testing procedures.

All these functions return an inference_result Maxima object which contains the necessary results for population inferences and decision making.

Global variable stats_numer controls whether results are given in floating point or symbolic and rational format; its default value is true and results are returned in floating point format.

Package descriptive contains some utilities to manipulate data structures (lists and matrices); for example, to extract subsamples. It also contains some examples on how to use package numericalio to read data from plain text files. See descriptive and numericalio for more details.

Package stats loads packages descriptive, distrib and inference_result.

For comments, bugs or suggestions, please contact the author at

’mario AT edu DOT xunta DOT es’.


Next: , Previous: Introduction to stats, Up: stats-pkg   [Contents][Index]

69.2 Functions and Variables for inference_result

Function: inference_result (title, values, numbers)

Constructs an inference_result object of the type returned by the stats functions. Argument title is a string with the name of the procedure; values is a list with elements of the form symbol = value and numbers is a list with positive integer numbers ranging from one to length(values), indicating which values will be shown by default.

Example:

This is a simple example showing results concerning a rectangle. The title of this object is the string "Rectangle", it stores five results, named 'base, 'height, 'diagonal, 'area, and 'perimeter, but only the first, second, fifth, and fourth will be displayed. The 'diagonal is stored in this object, but it is not displayed; to access its value, make use of function take_inference.

(%i1) load("inference_result")$
(%i2) b: 3$ h: 2$
(%i3) inference_result("Rectangle",
                        ['base=b,
                         'height=h,
                         'diagonal=sqrt(b^2+h^2),
                         'area=b*h,
                         'perimeter=2*(b+h)],
                        [1,2,5,4] );
                        |   Rectangle
                        |
                        |    base = 3
                        |
(%o3)                   |   height = 2
                        |
                        | perimeter = 10
                        |
                        |    area = 6
(%i4) take_inference('diagonal,%);
(%o4)                        sqrt(13)

See also take_inference.

Function: inferencep (obj)

Returns true or false, depending on whether obj is an inference_result object or not.

Function: items_inference (obj)

Returns a list with the names of the items stored in obj, which must be an inference_result object.

Example:

The inference_result object stores two values, named 'pi and 'e, but only the second is displayed. The items_inference function returns the names of all items, no matter they are displayed or not.

(%i1) load("inference_result")$
(%i2) inference_result("Hi", ['pi=%pi,'e=%e],[2]);
                            |   Hi
(%o2)                       |
                            | e = %e
(%i3) items_inference(%);
(%o3)                        [pi, e]
Function: take_inference
    take_inference (n, obj)
    take_inference (name, obj)
    take_inference (list, obj)

Returns the n-th value stored in obj if n is a positive integer, or the item named name if this is the name of an item. If the first argument is a list of numbers and/or symbols, function take_inference returns a list with the corresponding results.

Example:

Given an inference_result object, function take_inference is called in order to extract some information stored in it.

(%i1) load("inference_result")$
(%i2) b: 3$ h: 2$
(%i3) sol: inference_result("Rectangle",
                            ['base=b,
                             'height=h,
                             'diagonal=sqrt(b^2+h^2),
                             'area=b*h,
                             'perimeter=2*(b+h)],
                            [1,2,5,4] );
                        |   Rectangle
                        |
                        |    base = 3
                        |
(%o3)                   |   height = 2
                        |
                        | perimeter = 10
                        |
                        |    area = 6
(%i4) take_inference('base,sol);
(%o4)                           3
(%i5) take_inference(5,sol);
(%o5)                          10
(%i6) take_inference([1,'diagonal],sol);
(%o6)                     [3, sqrt(13)]
(%i7) take_inference(items_inference(sol),sol);
(%o7)                [3, 2, sqrt(13), 6, 10]

See also inference_result, and take_inference.


Next: , Previous: Functions and Variables for inference_result, Up: stats-pkg   [Contents][Index]

69.3 Functions and Variables for stats

Option variable: stats_numer

Default value: true

If stats_numer is true, inference statistical functions return their results in floating point numbers. If it is false, results are given in symbolic and rational format.

Function: test_mean
    test_mean (x)
    test_mean (x, options ...)

This is the mean t-test. Argument x is a list or a column matrix containing an one dimensional sample. It also performs an asymptotic test based on the Central Limit Theorem if option 'asymptotic is true.

Options:

The output of function test_mean is an inference_result Maxima object showing the following results:

  1. 'mean_estimate: the sample mean.
  2. 'conf_level: confidence level selected by the user.
  3. 'conf_interval: confidence interval for the population mean.
  4. 'method: inference procedure.
  5. 'hypotheses: null and alternative hypotheses to be tested.
  6. 'statistic: value of the sample statistic used for testing the null hypothesis.
  7. 'distribution: distribution of the sample statistic, together with its parameter(s).
  8. 'p_value: p-value of the test.

Examples:

Performs an exact t-test with unknown variance. The null hypothesis is H_0: mean=50 against the one sided alternative H_1: mean<50; according to the results, the p-value is too great, there are no evidence for rejecting H_0.

(%i1) load("stats")$
(%i2) data: [78,64,35,45,45,75,43,74,42,42]$
(%i3) test_mean(data,'conflevel=0.9,'alternative='less,'mean=50);
          |                 MEAN TEST
          |
          |            mean_estimate = 54.3
          |
          |              conf_level = 0.9
          |
          | conf_interval = [minf, 61.51314273502712]
          |
(%o3)     |  method = Exact t-test. Unknown variance.
          |
          | hypotheses = H0: mean = 50 , H1: mean < 50
          |
          |       statistic = .8244705235071678
          |
          |       distribution = [student_t, 9]
          |
          |        p_value = .7845100411786889

This time Maxima performs an asymptotic test, based on the Central Limit Theorem. The null hypothesis is H_0: equal(mean, 50) against the two sided alternative H_1: not equal(mean, 50); according to the results, the p-value is very small, H_0 should be rejected in favor of the alternative H_1. Note that, as indicated by the Method component, this procedure should be applied to large samples.

(%i1) load("stats")$
(%i2) test_mean([36,118,52,87,35,256,56,178,57,57,89,34,25,98,35,
              98,41,45,198,54,79,63,35,45,44,75,42,75,45,45,
              45,51,123,54,151],
              'asymptotic=true,'mean=50);
          |                       MEAN TEST
          |
          |           mean_estimate = 74.88571428571429
          |
          |                   conf_level = 0.95
          |
          | conf_interval = [57.72848600856194, 92.04294256286663]
          |
(%o2)     |    method = Large sample z-test. Unknown variance.
          |
          |       hypotheses = H0: mean = 50 , H1: mean # 50
          |
          |             statistic = 2.842831192874313
          |
          |             distribution = [normal, 0, 1]
          |
          |             p_value = .004471474652002261
Function: test_means_difference
    test_means_difference (x1, x2)
    test_means_difference (x1, x2, options ...)

This is the difference of means t-test for two samples. Arguments x1 and x2 are lists or column matrices containing two independent samples. In case of different unknown variances (see options 'dev1, 'dev2 and 'varequal bellow), the degrees of freedom are computed by means of the Welch approximation. It also performs an asymptotic test based on the Central Limit Theorem if option 'asymptotic is set to true.

Options:

The output of function test_means_difference is an inference_result Maxima object showing the following results:

  1. 'diff_estimate: the difference of means estimate.
  2. 'conf_level: confidence level selected by the user.
  3. 'conf_interval: confidence interval for the difference of means.
  4. 'method: inference procedure.
  5. 'hypotheses: null and alternative hypotheses to be tested.
  6. 'statistic: value of the sample statistic used for testing the null hypothesis.
  7. 'distribution: distribution of the sample statistic, together with its parameter(s).
  8. 'p_value: p-value of the test.

Examples:

The equality of means is tested with two small samples x and y, against the alternative H_1: m_1>m_2, being m_1 and m_2 the populations means; variances are unknown and supposed to be different.

(%i1) load("stats")$
(%i2) x: [20.4,62.5,61.3,44.2,11.1,23.7]$
(%i3) y: [1.2,6.9,38.7,20.4,17.2]$
(%i4) test_means_difference(x,y,'alternative='greater);
            |              DIFFERENCE OF MEANS TEST
            |
            |         diff_estimate = 20.31999999999999
            |
            |                 conf_level = 0.95
            |
            |    conf_interval = [- .04597417812882298, inf]
            |
(%o4)       |        method = Exact t-test. Welch approx.
            |
            | hypotheses = H0: mean1 = mean2 , H1: mean1 > mean2
            |
            |           statistic = 1.838004300728477
            |
            |    distribution = [student_t, 8.62758740184604]
            |
            |            p_value = .05032746527991905

The same test as before, but now variances are supposed to be equal.

(%i1) load("stats")$
(%i2) x: [20.4,62.5,61.3,44.2,11.1,23.7]$
(%i3) y: matrix([1.2],[6.9],[38.7],[20.4],[17.2])$
(%i4) test_means_difference(x,y,'alternative='greater,
                                                 'varequal=true);
            |              DIFFERENCE OF MEANS TEST
            |
            |         diff_estimate = 20.31999999999999
            |
            |                 conf_level = 0.95
            |
            |     conf_interval = [- .7722627696897568, inf]
            |
(%o4)       |   method = Exact t-test. Unknown equal variances
            |
            | hypotheses = H0: mean1 = mean2 , H1: mean1 > mean2
            |
            |           statistic = 1.765996124515009
            |
            |           distribution = [student_t, 9]
            |
            |            p_value = .05560320992529344
Function: test_variance
    test_variance (x)
    test_variance (x, options, ...)

This is the variance chi^2-test. Argument x is a list or a column matrix containing an one dimensional sample taken from a normal population.

Options:

The output of function test_variance is an inference_result Maxima object showing the following results:

  1. 'var_estimate: the sample variance.
  2. 'conf_level: confidence level selected by the user.
  3. 'conf_interval: confidence interval for the population variance.
  4. 'method: inference procedure.
  5. 'hypotheses: null and alternative hypotheses to be tested.
  6. 'statistic: value of the sample statistic used for testing the null hypothesis.
  7. 'distribution: distribution of the sample statistic, together with its parameter.
  8. 'p_value: p-value of the test.

Examples:

It is tested whether the variance of a population with unknown mean is equal to or greater than 200.

(%i1) load("stats")$
(%i2) x: [203,229,215,220,223,233,208,228,209]$
(%i3) test_variance(x,'alternative='greater,'variance=200);
             |                  VARIANCE TEST
             |
             |              var_estimate = 110.75
             |
             |                conf_level = 0.95
             |
             |     conf_interval = [57.13433376937479, inf]
             |
(%o3)        | method = Variance Chi-square test. Unknown mean.
             |
             |    hypotheses = H0: var = 200 , H1: var > 200
             |
             |                 statistic = 4.43
             |
             |             distribution = [chi2, 8]
             |
             |           p_value = .8163948512777689
Function: test_variance_ratio
    test_variance_ratio (x1, x2)
    test_variance_ratio (x1, x2, options ...)

This is the variance ratio F-test for two normal populations. Arguments x1 and x2 are lists or column matrices containing two independent samples.

Options:

The output of function test_variance_ratio is an inference_result Maxima object showing the following results:

  1. 'ratio_estimate: the sample variance ratio.
  2. 'conf_level: confidence level selected by the user.
  3. 'conf_interval: confidence interval for the variance ratio.
  4. 'method: inference procedure.
  5. 'hypotheses: null and alternative hypotheses to be tested.
  6. 'statistic: value of the sample statistic used for testing the null hypothesis.
  7. 'distribution: distribution of the sample statistic, together with its parameters.
  8. 'p_value: p-value of the test.

Examples:

The equality of the variances of two normal populations is checked against the alternative that the first is greater than the second.

(%i1) load("stats")$
(%i2) x: [20.4,62.5,61.3,44.2,11.1,23.7]$
(%i3) y: [1.2,6.9,38.7,20.4,17.2]$
(%i4) test_variance_ratio(x,y,'alternative='greater);
              |              VARIANCE RATIO TEST
              |
              |       ratio_estimate = 2.316933391522034
              |
              |               conf_level = 0.95
              |
              |    conf_interval = [.3703504689507268, inf]
              |
(%o4)         | method = Variance ratio F-test. Unknown means.
              |
              | hypotheses = H0: var1 = var2 , H1: var1 > var2
              |
              |         statistic = 2.316933391522034
              |
              |            distribution = [f, 5, 4]
              |
              |          p_value = .2179269692254457
Function: test_proportion
    test_proportion (x, n)
    test_proportion (x, n, options ...)

Inferences on a proportion. Argument x is the number of successes in n trials in a Bernoulli experiment with unknown probability.

Options:

The output of function test_proportion is an inference_result Maxima object showing the following results:

  1. 'sample_proportion: the sample proportion.
  2. 'conf_level: confidence level selected by the user.
  3. 'conf_interval: Wilson confidence interval for the proportion.
  4. 'method: inference procedure.
  5. 'hypotheses: null and alternative hypotheses to be tested.
  6. 'statistic: value of the sample statistic used for testing the null hypothesis.
  7. 'distribution: distribution of the sample statistic, together with its parameters.
  8. 'p_value: p-value of the test.

Examples:

Performs an exact test. The null hypothesis is H_0: p=1/2 against the one sided alternative H_1: p<1/2.

(%i1) load("stats")$
(%i2) test_proportion(45, 103, alternative = less);
         |            PROPORTION TEST              
         |                                         
         | sample_proportion = .4368932038834951   
         |                                         
         |           conf_level = 0.95             
         |                                         
         | conf_interval = [0, 0.522714149150231]  
         |                                         
(%o2)    |     method = Exact binomial test.       
         |                                         
         | hypotheses = H0: p = 0.5 , H1: p < 0.5  
         |                                         
         |             statistic = 45              
         |                                         
         |  distribution = [binomial, 103, 0.5]    
         |                                         
         |      p_value = .1184509388901454 

A two sided asymptotic test. Confidence level is 99/100.

(%i1) load("stats")$
(%i2) fpprintprec:7$
(%i3) test_proportion(45, 103, 
                  conflevel = 99/100, asymptotic=true);
      |                 PROPORTION TEST                  
      |                                                  
      |           sample_proportion = .43689             
      |                                                  
      |                conf_level = 0.99                 
      |                                                  
      |        conf_interval = [.31422, .56749]          
      |                                                  
(%o3) | method = Asympthotic test with Yates correction.
      |                                                  
      |     hypotheses = H0: p = 0.5 , H1: p # 0.5       
      |                                                  
      |               statistic = .43689                 
      |                                                  
      |      distribution = [normal, 0.5, .048872]       
      |                                                  
      |                p_value = .19662
Function: test_proportions_difference
    test_proportions_difference (x1, n1, x2, n2)
    test_proportions_difference (x1, n1, x2, n2, options …)

Inferences on the difference of two proportions. Argument x1 is the number of successes in n1 trials in a Bernoulli experiment in the first population, and x2 and n2 are the corresponding values in the second population. Samples are independent and the test is asymptotic.

Options:

The output of function test_proportions_difference is an inference_result Maxima object showing the following results:

  1. 'proportions: list with the two sample proportions.
  2. 'conf_level: confidence level selected by the user.
  3. 'conf_interval: Confidence interval for the difference of proportions p1 - p2.
  4. 'method: inference procedure and warning message in case of any of the samples sizes is less than 10.
  5. 'hypotheses: null and alternative hypotheses to be tested.
  6. 'statistic: value of the sample statistic used for testing the null hypothesis.
  7. 'distribution: distribution of the sample statistic, together with its parameters.
  8. 'p_value: p-value of the test.

Examples:

A machine produced 10 defective articles in a batch of 250. After some maintenance work, it produces 4 defective in a batch of 150. In order to know if the machine has improved, we test the null hypothesis H0:p1=p2, against the alternative H0:p1>p2, where p1 and p2 are the probabilities for one produced article to be defective before and after maintenance. According to the p value, there is not enough evidence to accept the alternative.

(%i1) load("stats")$
(%i2) fpprintprec:7$
(%i3) test_proportions_difference(10, 250, 4, 150,
                                alternative = greater);
      |       DIFFERENCE OF PROPORTIONS TEST         
      |                                              
      |       proportions = [0.04, .02666667]        
      |                                              
      |              conf_level = 0.95               
      |                                              
      |      conf_interval = [- .02172761, 1]        
      |                                              
(%o3) | method = Asymptotic test. Yates correction.  
      |                                              
      |   hypotheses = H0: p1 = p2 , H1: p1 > p2     
      |                                              
      |            statistic = .01333333             
      |                                              
      |    distribution = [normal, 0, .01898069]     
      |                                              
      |             p_value = .2411936 

Exact standard deviation of the asymptotic normal distribution when the data are unknown.

(%i1) load("stats")$
(%i2) stats_numer: false$
(%i3) sol: test_proportions_difference(x1,n1,x2,n2)$
(%i4) last(take_inference('distribution,sol));
               1    1                  x2 + x1
              (-- + --) (x2 + x1) (1 - -------)
               n2   n1                 n2 + n1
(%o4)    sqrt(---------------------------------)
                           n2 + n1
Function: test_sign
    test_sign (x)
    test_sign (x, options …)

This is the non parametric sign test for the median of a continuous population. Argument x is a list or a column matrix containing an one dimensional sample.

Options:

The output of function test_sign is an inference_result Maxima object showing the following results:

  1. 'med_estimate: the sample median.
  2. 'method: inference procedure.
  3. 'hypotheses: null and alternative hypotheses to be tested.
  4. 'statistic: value of the sample statistic used for testing the null hypothesis.
  5. 'distribution: distribution of the sample statistic, together with its parameter(s).
  6. 'p_value: p-value of the test.

Examples:

Checks whether the population from which the sample was taken has median 6, against the alternative H_1: median > 6.

(%i1) load("stats")$
(%i2) x: [2,0.1,7,1.8,4,2.3,5.6,7.4,5.1,6.1,6]$
(%i3) test_sign(x,'median=6,'alternative='greater);
               |                  SIGN TEST
               |
               |              med_estimate = 5.1
               |
               |      method = Non parametric sign test.
               |
(%o3)          | hypotheses = H0: median = 6 , H1: median > 6
               |
               |                statistic = 7
               |
               |      distribution = [binomial, 10, 0.5]
               |
               |         p_value = .05468749999999989
Function: test_signed_rank
    test_signed_rank (x)
    test_signed_rank (x, options …)

This is the Wilcoxon signed rank test to make inferences about the median of a continuous population. Argument x is a list or a column matrix containing an one dimensional sample. Performs normal approximation if the sample size is greater than 20, or if there are zeroes or ties.

See also pdf_rank_test and cdf_rank_test

Options:

The output of function test_signed_rank is an inference_result Maxima object with the following results:

  1. 'med_estimate: the sample median.
  2. 'method: inference procedure.
  3. 'hypotheses: null and alternative hypotheses to be tested.
  4. 'statistic: value of the sample statistic used for testing the null hypothesis.
  5. 'distribution: distribution of the sample statistic, together with its parameter(s).
  6. 'p_value: p-value of the test.

Examples:

Checks the null hypothesis H_0: median = 15 against the alternative H_1: median > 15. This is an exact test, since there are no ties.

(%i1) load("stats")$
(%i2) x: [17.1,15.9,13.7,13.4,15.5,17.6]$
(%i3) test_signed_rank(x,median=15,alternative=greater);
                 |             SIGNED RANK TEST
                 |
                 |           med_estimate = 15.7
                 |
                 |           method = Exact test
                 |
(%o3)            | hypotheses = H0: med = 15 , H1: med > 15
                 |
                 |              statistic = 14
                 |
                 |     distribution = [signed_rank, 6]
                 |
                 |            p_value = 0.28125

Checks the null hypothesis H_0: equal(median, 2.5) against the alternative H_1: not equal(median, 2.5). This is an approximated test, since there are ties.

(%i1) load("stats")$
(%i2) y:[1.9,2.3,2.6,1.9,1.6,3.3,4.2,4,2.4,2.9,1.5,3,2.9,4.2,3.1]$
(%i3) test_signed_rank(y,median=2.5);
             |                 SIGNED RANK TEST
             |
             |                med_estimate = 2.9
             |
             |          method = Asymptotic test. Ties
             |
(%o3)        |    hypotheses = H0: med = 2.5 , H1: med # 2.5
             |
             |                 statistic = 76.5
             |
             | distribution = [normal, 60.5, 17.58195097251724]
             |
             |           p_value = .3628097734643669
Function: test_rank_sum
    test_rank_sum (x1, x2)
    test_rank_sum (x1, x2, option)

This is the Wilcoxon-Mann-Whitney test for comparing the medians of two continuous populations. The first two arguments x1 and x2 are lists or column matrices with the data of two independent samples. Performs normal approximation if any of the sample sizes is greater than 10, or if there are ties.

Option:

The output of function test_rank_sum is an inference_result Maxima object with the following results:

  1. 'method: inference procedure.
  2. 'hypotheses: null and alternative hypotheses to be tested.
  3. 'statistic: value of the sample statistic used for testing the null hypothesis.
  4. 'distribution: distribution of the sample statistic, together with its parameters.
  5. 'p_value: p-value of the test.

Examples:

Checks whether populations have similar medians. Samples sizes are small and an exact test is made.

(%i1) load("stats")$
(%i2) x:[12,15,17,38,42,10,23,35,28]$
(%i3) y:[21,18,25,14,52,65,40,43]$
(%i4) test_rank_sum(x,y);
              |                 RANK SUM TEST
              |
              |              method = Exact test
              |
              | hypotheses = H0: med1 = med2 , H1: med1 # med2
(%o4)         |
              |                 statistic = 22
              |
              |        distribution = [rank_sum, 9, 8]
              |
              |          p_value = .1995886466474702

Now, with greater samples and ties, the procedure makes normal approximation. The alternative hypothesis is H_1: median1 < median2.

(%i1) load("stats")$
(%i2) x: [39,42,35,13,10,23,15,20,17,27]$
(%i3) y: [20,52,66,19,41,32,44,25,14,39,43,35,19,56,27,15]$
(%i4) test_rank_sum(x,y,'alternative='less);
             |                  RANK SUM TEST
             |
             |          method = Asymptotic test. Ties
             |
             |  hypotheses = H0: med1 = med2 , H1: med1 < med2
(%o4)        |
             |                 statistic = 48.5
             |
             | distribution = [normal, 79.5, 18.95419580097078]
             |
             |           p_value = .05096985666598441
Function: test_normality (x)

Shapiro-Wilk test for normality. Argument x is a list of numbers, and sample size must be greater than 2 and less or equal than 5000, otherwise, function test_normality signals an error message.

Reference:

[1] Algorithm AS R94, Applied Statistics (1995), vol.44, no.4, 547-551

The output of function test_normality is an inference_result Maxima object with the following results:

  1. 'statistic: value of the W statistic.
  2. 'p_value: p-value under normal assumption.

Examples:

Checks for the normality of a population, based on a sample of size 9.

(%i1) load("stats")$
(%i2) x:[12,15,17,38,42,10,23,35,28]$
(%i3) test_normality(x);
                       |      SHAPIRO - WILK TEST
                       |
(%o3)                  | statistic = .9251055695162436
                       |
                       |  p_value = .4361763918860381
Function: linear_regression
    linear_regression (x)
    linear_regression (x option)

Multivariate linear regression, y_i = b0 + b1*x_1i + b2*x_2i + ... + bk*x_ki + u_i, where u_i are N(0,sigma) independent random variables. Argument x must be a matrix with more than one column. The last column is considered as the responses (y_i).

Option:

The output of function linear_regression is an inference_result Maxima object with the following results:

  1. 'b_estimation: regression coefficients estimates.
  2. 'b_covariances: covariance matrix of the regression coefficients estimates.
  3. b_conf_int: confidence intervals of the regression coefficients.
  4. b_statistics: statistics for testing coefficient.
  5. b_p_values: p-values for coefficient tests.
  6. b_distribution: probability distribution for coefficient tests.
  7. v_estimation: unbiased variance estimator.
  8. v_conf_int: variance confidence interval.
  9. v_distribution: probability distribution for variance test.
  10. residuals: residuals.
  11. adc: adjusted determination coefficient.
  12. aic: Akaike’s information criterion.
  13. bic: Bayes’s information criterion.

Only items 1, 4, 5, 6, 7, 8, 9 and 11 above, in this order, are shown by default. The rest remain hidden until the user makes use of functions items_inference and take_inference.

Example:

Fitting a linear model to a trivariate sample. The last column is considered as the responses (y_i).

(%i2) load("stats")$
(%i3) X:matrix(
    [58,111,64],[84,131,78],[78,158,83],
    [81,147,88],[82,121,89],[102,165,99],
    [85,174,101],[102,169,102])$
(%i4) fpprintprec: 4$
(%i5) res: linear_regression(X);
             |       LINEAR REGRESSION MODEL         
             |                                       
             | b_estimation = [9.054, .5203, .2397]  
             |                                       
             | b_statistics = [.6051, 2.246, 1.74]   
             |                                       
             | b_p_values = [.5715, .07466, .1423]   
             |                                       
(%o5)        |   b_distribution = [student_t, 5]     
             |                                       
             |         v_estimation = 35.27          
             |                                       
             |     v_conf_int = [13.74, 212.2]       
             |                                       
             |      v_distribution = [chi2, 5]       
             |                                       
             |             adc = .7922               
(%i6) items_inference(res);
(%o6) [b_estimation, b_covariances, b_conf_int, b_statistics, 
b_p_values, b_distribution, v_estimation, v_conf_int, 
v_distribution, residuals, adc, aic, bic]
(%i7) take_inference('b_covariances, res);
                  [  223.9    - 1.12   - .8532  ]
                  [                             ]
(%o7)             [ - 1.12    .05367   - .02305 ]
                  [                             ]
                  [ - .8532  - .02305   .01898  ]
(%i8) take_inference('bic, res);
(%o8)                          30.98
(%i9) load("draw")$
(%i10) draw2d(
    points_joined = true,
    grid = true,
    points(take_inference('residuals, res)) )$

Previous: Functions and Variables for stats, Up: stats-pkg   [Contents][Index]

69.4 Functions and Variables for special distributions

Function: pdf_signed_rank (x, n)

Probability density function of the exact distribution of the signed rank statistic. Argument x is a real number and n a positive integer.

See also test_signed_rank.

Function: cdf_signed_rank (x, n)

Cumulative density function of the exact distribution of the signed rank statistic. Argument x is a real number and n a positive integer.

See also test_signed_rank.

Function: pdf_rank_sum (x, n, m)

Probability density function of the exact distribution of the rank sum statistic. Argument x is a real number and n and m are both positive integers.

See also test_rank_sum.

Function: cdf_rank_sum (x, n, m)

Cumulative density function of the exact distribution of the rank sum statistic. Argument x is a real number and n and m are both positive integers.

See also test_rank_sum.


Next: , Previous: stats-pkg, Up: Top   [Contents][Index]

70 Пакет stirling


Previous: Пакет stirling, Up: Пакет stirling   [Contents][Index]

70.1 Формула Стирлинга

Функция: stirling (z,n)

Заменяет gamma(x) по формуле Стирлинга O(1/x^(2n-1)). Сообщает об ошибке, если n не является неотрицательным целым числом.

См. Abramowitz & Stegun, "Handbook of mathematical functions", 6.1.40.

Примеры:

(%i1) load ("stirling")$

(%i2) stirling(gamma(%alpha+x)/gamma(x),1);
       1/2 - x             x + %alpha - 1/2
(%o2) x        (x + %alpha)
                                   1           1
                            --------------- - ---- - %alpha
                            12 (x + %alpha)   12 x
                          %e
(%i3) taylor(%,x,inf,1);
                    %alpha       2    %alpha
          %alpha   x       %alpha  - x       %alpha
(%o3)/T/ x       + -------------------------------- + . . .
                                 2 x
(%i4) map('factor,%);
                                       %alpha - 1
         %alpha   (%alpha - 1) %alpha x
(%o4)   x       + -------------------------------
                                  2

Функция stirling различает переменную ’gamma’ и функцию gamma:

(%i5) stirling(gamma + gamma(x),0);
                                    x - 1/2   - x
(%o5)    gamma + sqrt(2) sqrt(%pi) x        %e
(%i6) stirling(gamma(y) + gamma(x),0);
                         y - 1/2   - y
(%o6) sqrt(2) sqrt(%pi) y        %e
                                              x - 1/2   - x
                         + sqrt(2) sqrt(%pi) x        %e

Для использования этой функции сначала напишите load("stirling").


Next: , Previous: Пакет stirling, Up: Top   [Contents][Index]

71 stringproc


Next: , Previous: stringproc-pkg, Up: stringproc-pkg   [Contents][Index]

71.1 Introduction to String Processing

The package stringproc contains functions for processing strings and characters including formatting, encoding and data streams. This package is completed by some tools for cryptography, e.g. base64 and hash functions.

It can be directly loaded via load("stringproc") or automatically by using one of its functions.

For questions and bug reports please contact the author. The following command prints his e-mail-address.

printf(true, "~{~a~}@gmail.com", split(sdowncase("Volker van Nek")))$

A string is constructed by typing e.g. "Text". When the option variable stringdisp is set to false, which is the default, the double quotes won’t be printed. stringp is a test, if an object is a string.

(%i1) str: "Text";
(%o1)                         Text
(%i2) stringp(str);
(%o2)                         true

Characters are represented by a string of length 1. charp is the corresponding test.

(%i1) char: "e";
(%o1)                           e
(%i2) charp(char);
(%o2)                         true

In Maxima position indices in strings are like in list 1-indexed which results to the following consistency.

(%i1) is(charat("Lisp",1) = charlist("Lisp")[1]);
(%o1)                         true

A string may contain Maxima expressions. These can be parsed with parse_string.

(%i1) map(parse_string, ["42" ,"sqrt(2)", "%pi"]);
(%o1)                   [42, sqrt(2), %pi]
(%i2) map('float, %);
(%o2)        [42.0, 1.414213562373095, 3.141592653589793]

Strings can be processed as characters or in binary form as octets. Functions for conversions are string_to_octets and octets_to_string. Usable encodings depend on the platform, the application and the underlying Lisp. (The following shows Maxima in GNU/Linux, compiled with SBCL.)

(%i1) obase: 16.$
(%i2) string_to_octets("$£€", "cp1252");
(%o2)                     [24, 0A3, 80]
(%i3) string_to_octets("$£€", "utf-8");
(%o3)               [24, 0C2, 0A3, 0E2, 82, 0AC]

Strings may be written to character streams or as octets to binary streams. The following example demonstrates file in and output of characters.

openw returns an output stream to a file, printf writes formatted to that file and by e.g. close all characters contained in the stream are written to the file.

(%i1) s: openw("file.txt");
(%o1)                #<output stream file.txt>
(%i2) printf(s, "~%~d ~f ~a ~a ~f ~e ~a~%", 
42, 1.234, sqrt(2), %pi, 1.0e-2, 1.0e-2, 1.0b-2)$
(%i3) close(s)$

openr then returns an input stream from the previously used file and readline returns the line read as a string. The string may be tokenized by e.g. split or tokens and finally parsed by parse_string.

(%i4) s: openr("file.txt");
(%o4)                 #<input stream file.txt>
(%i5) readline(s);
(%o5)          42 1.234 sqrt(2) %pi 0.01 1.0E-2 1.0b-2
(%i6) map(parse_string, split(%));
(%o6)       [42, 1.234, sqrt(2), %pi, 0.01, 0.01, 1.0b-2]
(%i7) close(s)$

Next: , Previous: Introduction to String Processing, Up: stringproc-pkg   [Contents][Index]

71.2 String Input and Output

Example: Formatted printing to a file.

(%i1) s: openw("file.txt");
(%o1)                      #<output stream file.txt>
(%i2) control: 
"~2tAn atom: ~20t~a~%~2tand a list: ~20t~{~r ~}~%~2t\
and an integer: ~20t~d~%"$
(%i3) printf( s,control, 'true,[1,2,3],42 )$
(%o3)                                false
(%i4) close(s);
(%o4)                                true
(%i5) s: openr("file.txt");
(%o5)                      #<input stream file.txt>
(%i6) while stringp( tmp:readline(s) ) do print(tmp)$
  An atom:          true 
  and a list:       one two three  
  and an integer:   42 
(%i7) close(s)$
Function: close (stream)

Closes stream and returns true if stream had been open.

Function: flength (stream)

stream has to be an open stream from or to a file. flength then returns the number of bytes which are currently present in this file.

Example: See writebyte .

Function: flush_output (stream)

Flushes stream where stream has to be an output stream to a file.

Example: See writebyte .

Function: fposition
    fposition (stream)
    fposition (stream, pos)

Returns the current position in stream, if pos is not used. If pos is used, fposition sets the position in stream. stream has to be a stream from or to a file and pos has to be a positive number.

Positions in data streams are like in strings or lists 1-indexed, i.e. the first element in stream is in position 1.

Function: freshline
    freshline ()
    freshline (stream)

Writes a new line to the standard output stream if the position is not at the beginning of a line and returns true. Using the optional argument stream the new line is written to that stream. There are some cases, where freshline() does not work as expected.

See also newline.

Function: get_output_stream_string (stream)

Returns a string containing all the characters currently present in stream which must be an open string-output stream. The returned characters are removed from stream.

Example: See make_string_output_stream .

Function: make_string_input_stream
    make_string_input_stream (string)
    make_string_input_stream (string, start)
    make_string_input_stream (string, start, end)

Returns an input stream which contains parts of string and an end of file. Without optional arguments the stream contains the entire string and is positioned in front of the first character. start and end define the substring contained in the stream. The first character is available at position 1.

(%i1) istream : make_string_input_stream("text", 1, 4);
(%o1)              #<string-input stream from "text">
(%i2) (while (c : readchar(istream)) # false do sprint(c), newline())$
t e x 
(%i3) close(istream)$
Function: make_string_output_stream ()

Returns an output stream that accepts characters. Characters currently present in this stream can be retrieved by get_output_stream_string.

(%i1) ostream : make_string_output_stream();
(%o1)               #<string-output stream 09622ea0>
(%i2) printf(ostream, "foo")$

(%i3) printf(ostream, "bar")$

(%i4) string : get_output_stream_string(ostream);
(%o4)                            foobar
(%i5) printf(ostream, "baz")$

(%i6) string : get_output_stream_string(ostream);
(%o6)                              baz
(%i7) close(ostream)$
Function: newline
    newline ()
    newline (stream)

Writes a new line to the standard output stream. Using the optional argument stream the new line is written to that stream. There are some cases, where newline() does not work as expected.

See sprint for an example of using newline().

Function: opena (file)

Returns a character output stream to file. If an existing file is opened, opena appends elements at the end of file.

For binary output see opena_binary .

Function: openr
    openr (file)
    openr (file, encoding)

Returns a character input stream to file. openr assumes that file already exists. If reading the file results in a lisp error about its encoding passing the correct string as the argument encoding might help. The available encodings and their names depend on the lisp being used. For sbcl a list of suitable strings can be found at http://www.sbcl.org/manual/#External-Formats.

For binary input see openr_binary . See also close and openw.

(%i1) istream : openr("data.txt","EUC-JP");
(%o1)     #<FD-STREAM for "file /home/gunter/data.txt" {10099A3AE3}>
(%i2) close(istream);
(%o2)                                true
Function: openw (file)

Returns a character output stream to file. If file does not exist, it will be created. If an existing file is opened, openw destructively modifies file.

For binary output see openw_binary .

See also close and openr.

Function: printf
    printf (dest, string)
    printf (dest, string, expr_1, ..., expr_n)

Produces formatted output by outputting the characters of control-string string and observing that a tilde introduces a directive. The character after the tilde, possibly preceded by prefix parameters and modifiers, specifies what kind of formatting is desired. Most directives use one or more elements of the arguments expr_1, ..., expr_n to create their output.

If dest is a stream or true, then printf returns false. Otherwise, printf returns a string containing the output. By default the streams stdin, stdout and stderr are defined. If Maxima is running as a network client (which is the normal case if Maxima is communicating with a graphical user interface, which must be the server) setup-client will define old_stdout and old_stderr, too.

printf provides the Common Lisp function format in Maxima. The following example illustrates the general relation between these two functions.

(%i1) printf(true, "R~dD~d~%", 2, 2);
R2D2
(%o1)                                false
(%i2) :lisp (format t "R~dD~d~%" 2 2)
R2D2
NIL

The following description is limited to a rough sketch of the possibilities of printf. The Lisp function format is described in detail in many reference books. Of good help is e.g. the free available online-manual "Common Lisp the Language" by Guy L. Steele. See chapter 22.3.3 there.

In addition, printf recognizes two format directives which are not known to Lisp format. The format directive ~m indicates Maxima pretty printer output. The format directive ~h indicates a bigfloat number.

   ~%       new line
   ~&       fresh line
   ~t       tab
   ~$       monetary
   ~d       decimal integer
   ~b       binary integer
   ~o       octal integer
   ~x       hexadecimal integer
   ~br      base-b integer
   ~r       spell an integer
   ~p       plural
   ~f       floating point
   ~e       scientific notation
   ~g       ~f or ~e, depending upon magnitude
   ~h       bigfloat
   ~a       uses Maxima function string
   ~m       Maxima pretty printer output
   ~s       like ~a, but output enclosed in "double quotes"
   ~~       ~
   ~<       justification, ~> terminates
   ~(       case conversion, ~) terminates 
   ~[       selection, ~] terminates 
   ~{       iteration, ~} terminates

Note that the directive ~* is not supported.

If dest is a stream or true, then printf returns false. Otherwise, printf returns a string containing the output.

(%i1) printf( false, "~a ~a ~4f ~a ~@r", 
              "String",sym,bound,sqrt(12),144), bound = 1.234;
(%o1)                 String sym 1.23 2*sqrt(3) CXLIV
(%i2) printf( false,"~{~a ~}",["one",2,"THREE"] );
(%o2)                          one 2 THREE 
(%i3) printf(true,"~{~{~9,1f ~}~%~}",mat ),
          mat = args(matrix([1.1,2,3.33],[4,5,6],[7,8.88,9]))$
      1.1       2.0       3.3 
      4.0       5.0       6.0 
      7.0       8.9       9.0 
(%i4) control: "~:(~r~) bird~p ~[is~;are~] singing."$
(%i5) printf( false,control, n,n,if n=1 then 1 else 2 ), n=2;
(%o5)                    Two birds are singing.

The directive ~h has been introduced to handle bigfloats.

~w,d,e,x,o,p@H
 w : width
 d : decimal digits behind floating point
 e : minimal exponent digits
 x : preferred exponent
 o : overflow character
 p : padding character
 @ : display sign for positive numbers
(%i1) fpprec : 1000$
(%i2) printf(true, "|~h|~%", 2.b0^-64)$
|0.0000000000000000000542101086242752217003726400434970855712890625|
(%i3) fpprec : 26$
(%i4) printf(true, "|~h|~%", sqrt(2))$
|1.4142135623730950488016887|
(%i5) fpprec : 24$
(%i6) printf(true, "|~h|~%", sqrt(2))$
|1.41421356237309504880169|
(%i7) printf(true, "|~28h|~%", sqrt(2))$
|   1.41421356237309504880169|
(%i8) printf(true, "|~28,,,,,'*h|~%", sqrt(2))$
|***1.41421356237309504880169|
(%i9) printf(true, "|~,18h|~%", sqrt(2))$
|1.414213562373095049|
(%i10) printf(true, "|~,,,-3h|~%", sqrt(2))$
|1414.21356237309504880169b-3|
(%i11) printf(true, "|~,,2,-3h|~%", sqrt(2))$
|1414.21356237309504880169b-03|
(%i12) printf(true, "|~20h|~%", sqrt(2))$
|1.41421356237309504880169|
(%i13) printf(true, "|~20,,,,'+h|~%", sqrt(2))$
|++++++++++++++++++++|

For conversion of objects to strings also see concat, sconcat, string and simplode.

Function: readbyte (stream)

Removes and returns the first byte in stream which must be a binary input stream. If the end of file is encountered readbyte returns false.

Example: Read the first 16 bytes from a file encrypted with AES in OpenSSL.

(%i1) ibase: obase: 16.$

(%i2) in: openr_binary("msg.bin");
(%o2)                       #<input stream msg.bin>
(%i3) (L:[],  thru 16. do push(readbyte(in), L),  L:reverse(L));
(%o3) [53, 61, 6C, 74, 65, 64, 5F, 5F, 88, 56, 0DE, 8A, 74, 0FD,
       0AD, 0F0]
(%i4) close(in);
(%o4)                                true
(%i5) map(ascii, rest(L,-8));
(%o5)                      [S, a, l, t, e, d, _, _]
(%i6) salt: octets_to_number(rest(L,8));
(%o6)                          8856de8a74fdadf0
Function: readchar (stream)

Removes and returns the first character in stream. If the end of file is encountered readchar returns false.

Example: See make_string_input_stream.

Function: readline (stream)

Returns a string containing all characters starting at the current position in stream up to the end of the line or false if the end of the file is encountered.

Function: sprint (expr_1, …, expr_n)

Evaluates and displays its arguments one after the other ‘on a line’ starting at the leftmost position. The expressions are printed with a space character right next to the number, and it disregards line length. newline() might be used for line breaking.

Example: Sequential printing with sprint. Creating a new line with newline().

(%i1) for n:0 thru 19 do sprint(fib(n))$
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
(%i2) for n:0 thru 22 do ( 
         sprint(fib(n)), 
         if mod(n,10) = 9 then newline() )$
0 1 1 2 3 5 8 13 21 34 
55 89 144 233 377 610 987 1597 2584 4181 
6765 10946 17711 
Function: writebyte (byte, stream)

Writes byte to stream which must be a binary output stream. writebyte returns byte.

Example: Write some bytes to a binary file output stream. In this example all bytes correspond to printable characters and are printed by printfile. The bytes remain in the stream until flush_output or close have been called.

(%i1) ibase: obase: 16.$

(%i2) bytes: map(cint, charlist("GNU/Linux"));
(%o2)                [47, 4E, 55, 2F, 4C, 69, 6E, 75, 78]
(%i3) out: openw_binary("test.bin");
(%o3)                      #<output stream test.bin>
(%i4) for i thru 3 do writebyte(bytes[i], out);
(%o4)                                done
(%i5) printfile("test.bin")$

(%i6) flength(out);
(%o6)                                  0
(%i7) flush_output(out);
(%o7)                                true
(%i8) flength(out);
(%o8)                                  3
(%i9) printfile("test.bin")$
GNU
(%i0A) for b in rest(bytes,3) do writebyte(b, out);
(%o0A)                               done
(%i0B) close(out);
(%o0B)                               true
(%i0C) printfile("test.bin")$
GNU/Linux

Next: , Previous: String Input and Output, Up: stringproc-pkg   [Contents][Index]

71.3 Characters

Characters are strings of length 1.

Function: adjust_external_format ()

Prints information about the current external format of the Lisp reader and in case the external format encoding differs from the encoding of the application which runs Maxima adjust_external_format tries to adjust the encoding or prints some help or instruction. adjust_external_format returns true when the external format has been changed and false otherwise.

Functions like cint, unicode, octets_to_string and string_to_octets need UTF-8 as the external format of the Lisp reader to work properly over the full range of Unicode characters.

Examples (Maxima on Windows, March 2016): Using adjust_external_format when the default external format is not equal to the encoding provided by the application.

1. Command line Maxima

In case a terminal session is preferred it is recommended to use Maxima compiled with SBCL. Here Unicode support is provided by default and calls to adjust_external_format are unnecessary.

If Maxima is compiled with CLISP or GCL it is recommended to change the terminal encoding from CP850 to CP1252. adjust_external_format prints some help.

CCL reads UTF-8 while the terminal input is CP850 by default. CP1252 is not supported by CCL. adjust_external_format prints instructions for changing the terminal encoding and external format both to iso-8859-1.

2. wxMaxima

In wxMaxima SBCL reads CP1252 by default but the input from the application is UTF-8 encoded. Adjustment is needed.

Calling adjust_external_format and restarting Maxima permanently changes the default external format to UTF-8.

(%i1)adjust_external_format();
The line
(setf sb-impl::*default-external-format* :utf-8)
has been appended to the init file
C:/Users/Username/.sbclrc
Please restart Maxima to set the external format to UTF-8.
(%i1) false

Restarting Maxima.

(%i1) adjust_external_format();
The external format is currently UTF-8
and has not been changed.
(%i1) false
Function: alphacharp (char)

Returns true if char is an alphabetic character.

To identify a non-US-ASCII character as an alphabetic character the underlying Lisp must provide full Unicode support. E.g. a German umlaut is detected as an alphabetic character with SBCL in GNU/Linux but not with GCL. (In Windows Maxima, when compiled with SBCL, must be set to UTF-8. See adjust_external_format for more.)

Example: Examination of non-US-ASCII characters.

The underlying Lisp (SBCL, GNU/Linux) is able to convert the typed character into a Lisp character and to examine.

(%i1) alphacharp("ü");
(%o1)                          true

In GCL this is not possible. An error break occurs.

(%i1) alphacharp("u");
(%o1)                          true
(%i2) alphacharp("ü");

package stringproc: ü cannot be converted into a Lisp character.
 -- an error.
Function: alphanumericp (char)

Returns true if char is an alphabetic character or a digit (only corresponding US-ASCII characters are regarded as digits).

Note: See remarks on alphacharp.

Function: ascii (int)

Returns the US-ASCII character corresponding to the integer int which has to be less than 128.

See unicode for converting code points larger than 127.

Examples:

(%i1) for n from 0 thru 127 do ( 
        ch: ascii(n), 
        if alphacharp(ch) then sprint(ch),
        if n = 96 then newline() )$
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 
a b c d e f g h i j k l m n o p q r s t u v w x y z
Function: cequal (char_1, char_2)

Returns true if char_1 and char_2 are the same character.

Function: cequalignore (char_1, char_2)

Like cequal but ignores case which is only possible for non-US-ASCII characters when the underlying Lisp is able to recognize a character as an alphabetic character. See remarks on alphacharp.

Function: cgreaterp (char_1, char_2)

Returns true if the code point of char_1 is greater than the code point of char_2.

Function: cgreaterpignore (char_1, char_2)

Like cgreaterp but ignores case which is only possible for non-US-ASCII characters when the underlying Lisp is able to recognize a character as an alphabetic character. See remarks on alphacharp.

Function: charp (obj)

Returns true if obj is a Maxima-character. See introduction for example.

Function: cint (char)

Returns the Unicode code point of char which must be a Maxima character, i.e. a string of length 1.

Examples: The hexadecimal code point of some characters (Maxima with SBCL on GNU/Linux).

(%i1) obase: 16.$
(%i2) map(cint, ["$","£","€"]);
(%o2)                           [24, 0A3, 20AC]

Warning: It is not possible to enter characters corresponding to code points larger than 16 bit in wxMaxima with SBCL on Windows when the external format has not been set to UTF-8. See adjust_external_format.

CMUCL doesn’t process these characters as one character. cint then returns false. Converting a character to a code point via UTF-8-octets may serve as a workaround:

utf8_to_unicode(string_to_octets(character));

See utf8_to_unicode, string_to_octets.

Function: clessp (char_1, char_2)

Returns true if the code point of char_1 is less than the code point of char_2.

Function: clesspignore (char_1, char_2)

Like clessp but ignores case which is only possible for non-US-ASCII characters when the underlying Lisp is able to recognize a character as an alphabetic character. See remarks on alphacharp.

Function: constituent (char)

Returns true if char is a graphic character but not a space character. A graphic character is a character one can see, plus the space character. (constituent is defined by Paul Graham. See Paul Graham, ANSI Common Lisp, 1996, page 67.)

(%i1) for n from 0 thru 255 do ( 
tmp: ascii(n), if constituent(tmp) then sprint(tmp) )$
! " #  %  ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B
C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c
d e f g h i j k l m n o p q r s t u v w x y z { | } ~
Function: digitcharp (char)

Returns true if char is a digit where only the corresponding US-ASCII-character is regarded as a digit.

Function: lowercasep (char)

Returns true if char is a lowercase character.

Note: See remarks on alphacharp.

Variable: newline

The newline character (ASCII-character 10).

Variable: space

The space character.

Variable: tab

The tab character.

Function: unicode (arg)

Returns the character defined by arg which might be a Unicode code point or a name string if the underlying Lisp provides full Unicode support.

Example: Characters defined by hexadecimal code points (Maxima with SBCL on GNU/Linux).

(%i1) ibase: 16.$
(%i2) map(unicode, [24, 0A3, 20AC]);
(%o2)                            [$, £, €]

Warning: In wxMaxima with SBCL on Windows it is not possible to convert code points larger than 16 bit to characters when the external format has not been set to UTF-8. See adjust_external_format for more information.

CMUCL doesn’t process code points larger than 16 bit. In these cases unicode returns false. Converting a code point to a character via UTF-8 octets may serve as a workaround:

octets_to_string(unicode_to_utf8(code_point));

See octets_to_string, unicode_to_utf8.

In case the underlying Lisp provides full Unicode support the character might be specified by its name. The following is possible in ECL, CLISP and SBCL, where in SBCL on Windows the external format has to be set to UTF-8. unicode(name) is supported by CMUCL too but again limited to 16 bit characters.

The string argument to unicode is basically the same string returned by printf using the "~@c" specifier. But as shown below the prefix "#\" must be omitted. Underlines might be replaced by spaces and uppercase letters by lowercase ones.

Example (continued): Characters defined by names (Maxima with SBCL on GNU/Linux).

(%i3) printf(false, "~@c", unicode(0DF));
(%o3)                    #\LATIN_SMALL_LETTER_SHARP_S
(%i4) unicode("LATIN_SMALL_LETTER_SHARP_S");
(%o4)                                  ß
(%i5) unicode("Latin small letter sharp s");
(%o5)                                  ß
Function: unicode_to_utf8 (code_point)

Returns a list containing the UTF-8 code corresponding to the Unicode code_point.

Examples: Converting Unicode code points to UTF-8 and vice versa.

(%i1) ibase: obase: 16.$
(%i2) map(cint, ["$","£","€"]);
(%o2)                           [24, 0A3, 20AC]
(%i3) map(unicode_to_utf8, %);
(%o3)                 [[24], [0C2, 0A3], [0E2, 82, 0AC]]
(%i4) map(utf8_to_unicode, %);
(%o4)                           [24, 0A3, 20AC]
Function: uppercasep (char)

Returns true if char is an uppercase character.

Note: See remarks on alphacharp.

Variable: us_ascii_only

This option variable affects Maxima when the character encoding provided by the application which runs Maxima is UTF-8 but the external format of the Lisp reader is not equal to UTF-8.

On GNU/Linux this is true when Maxima is built with GCL and on Windows in wxMaxima with GCL- and SBCL-builds. With SBCL it is recommended to change the external format to UTF-8. Setting us_ascii_only is unnecessary then. See adjust_external_format for details.

us_ascii_only is false by default. Maxima itself then (i.e. in the above described situation) parses the UTF-8 encoding.

When us_ascii_only is set to true it is assumed that all strings used as arguments to string processing functions do not contain Non-US-ASCII characters. Given that promise, Maxima avoids parsing UTF-8 and strings can be processed more efficiently.

Function: utf8_to_unicode (list)

Returns a Unicode code point corresponding to the list which must contain the UTF-8 encoding of a single character.

Examples: See unicode_to_utf8.


Next: , Previous: Characters, Up: stringproc-pkg   [Contents][Index]

71.4 String Processing

Position indices in strings are 1-indexed like in Maxima lists. See example in charat.

Function: charat (string, n)

Returns the n-th character of string. The first character in string is returned with n = 1.

(%i1) charat("Lisp",1);
(%o1)                           L
(%i2) charlist("Lisp")[1];
(%o2)                           L
Function: charlist (string)

Returns the list of all characters in string.

(%i1) charlist("Lisp");
(%o1)                     [L, i, s, p]
Function: eval_string (str)

Parse the string str as a Maxima expression and evaluate it. The string str may or may not have a terminator (dollar sign $ or semicolon ;). Only the first expression is parsed and evaluated, if there is more than one.

Complain if str is not a string.

Examples:

(%i1) eval_string ("foo: 42; bar: foo^2 + baz");
(%o1)                       42
(%i2) eval_string ("(foo: 42, bar: foo^2 + baz)");
(%o2)                   baz + 1764

See also parse_string and eval_string_lisp.

Function: parse_string (str)

Parse the string str as a Maxima expression (do not evaluate it). The string str may or may not have a terminator (dollar sign $ or semicolon ;). Only the first expression is parsed, if there is more than one.

Complain if str is not a string.

Examples:

(%i1) parse_string ("foo: 42; bar: foo^2 + baz");
(%o1)                    foo : 42
(%i2) parse_string ("(foo: 42, bar: foo^2 + baz)");
                                   2
(%o2)          (foo : 42, bar : foo  + baz)

See also eval_string.

Function: scopy (string)

Returns a copy of string as a new string.

Function: sdowncase
    sdowncase (string)
    sdowncase (string, start)
    sdowncase (string, start, end)

Like supcase but uppercase characters are converted to lowercase.

Function: sequal (string_1, string_2)

Returns true if string_1 and string_2 contain the same sequence of characters.

Function: sequalignore (string_1, string_2)

Like sequal but ignores case which is only possible for non-US-ASCII characters when the underlying Lisp is able to recognize a character as an alphabetic character. See remarks on alphacharp.

Function: sexplode (string)

sexplode is an alias for function charlist.

Function: simplode
    simplode (list)
    simplode (list, delim)

simplode takes a list of expressions and concatenates them into a string. If no delimiter delim is specified, simplode uses no delimiter. delim can be any string.

See also concat, sconcat, string and printf.

Examples:

(%i1) simplode(["xx[",3,"]:",expand((x+y)^3)]);
(%o1)             xx[3]:y^3+3*x*y^2+3*x^2*y+x^3
(%i2) simplode( sexplode("stars")," * " );
(%o2)                   s * t * a * r * s
(%i3) simplode( ["One","more","coffee."]," " );
(%o3)                   One more coffee.
Function: sinsert (seq, string, pos)

Returns a string that is a concatenation of substring(string, 1, pos-1), the string seq and substring (string, pos). Note that the first character in string is in position 1.

Examples:

(%i1) s: "A submarine."$
(%i2) concat( substring(s,1,3),"yellow ",substring(s,3) );
(%o2)                  A yellow submarine.
(%i3) sinsert("hollow ",s,3);
(%o3)                  A hollow submarine.
Function: sinvertcase
    sinvertcase (string)
    sinvertcase (string, start)
    sinvertcase (string, start, end)

Returns string except that each character from position start to end is inverted. If end is not given, all characters from start to the end of string are replaced.

Examples:

(%i1) sinvertcase("sInvertCase");
(%o1)                      SiNVERTcASE
Function: slength (string)

Returns the number of characters in string.

Function: smake (num, char)

Returns a new string with a number of num characters char.

Example:

(%i1) smake(3,"w");
(%o1)                          www
Function: smismatch
    smismatch (string_1, string_2)
    smismatch (string_1, string_2, test)

Returns the position of the first character of string_1 at which string_1 and string_2 differ or false. Default test function for matching is sequal. If smismatch should ignore case, use sequalignore as test.

Example:

(%i1) smismatch("seven","seventh");
(%o1)                           6
Function: split
    split (string)
    split (string, delim)
    split (string, delim, multiple)

Returns the list of all tokens in string. Each token is an unparsed string. split uses delim as delimiter. If delim is not given, the space character is the default delimiter. multiple is a boolean variable with true by default. Multiple delimiters are read as one. This is useful if tabs are saved as multiple space characters. If multiple is set to false, each delimiter is noted.

Examples:

(%i1) split("1.2   2.3   3.4   4.5");
(%o1)                 [1.2, 2.3, 3.4, 4.5]
(%i2) split("first;;third;fourth",";",false);
(%o2)               [first, , third, fourth]
Function: sposition (char, string)

Returns the position of the first character in string which matches char. The first character in string is in position 1. For matching characters ignoring case see ssearch.

Function: sremove
    sremove (seq, string)
    sremove (seq, string, test)
    sremove (seq, string, test, start)
    sremove (seq, string, test, start, end)

Returns a string like string but without all substrings matching seq. Default test function for matching is sequal. If sremove should ignore case while searching for seq, use sequalignore as test. Use start and end to limit searching. Note that the first character in string is in position 1.

Examples:

(%i1) sremove("n't","I don't like coffee.");
(%o1)                   I do like coffee.
(%i2) sremove ("DO ",%,'sequalignore);
(%o2)                    I like coffee.
Function: sremovefirst
    sremovefirst (seq, string)
    sremovefirst (seq, string, test)
    sremovefirst (seq, string, test, start)
    sremovefirst (seq, string, test, start, end)

Like sremove except that only the first substring that matches seq is removed.

Function: sreverse (string)

Returns a string with all the characters of string in reverse order.

See also reverse.

Function: ssearch
    ssearch (seq, string)
    ssearch (seq, string, test)
    ssearch (seq, string, test, start)
    ssearch (seq, string, test, start, end)

Returns the position of the first substring of string that matches the string seq. Default test function for matching is sequal. If ssearch should ignore case, use sequalignore as test. Use start and end to limit searching. Note that the first character in string is in position 1.

Example:

(%i1) ssearch("~s","~{~S ~}~%",'sequalignore);
(%o1)                                  4
Function: ssort
    ssort (string)
    ssort (string, test)

Returns a string that contains all characters from string in an order such there are no two successive characters c and d such that test (c, d) is false and test (d, c) is true. Default test function for sorting is clessp. The set of test functions is {clessp, clesspignore, cgreaterp, cgreaterpignore, cequal, cequalignore}.

Examples:

(%i1) ssort("I don't like Mondays.");
(%o1)                    '.IMaddeiklnnoosty
(%i2) ssort("I don't like Mondays.",'cgreaterpignore);
(%o2)                 ytsoonnMlkIiedda.'   
Function: ssubst
    ssubst (new, old, string)
    ssubst (new, old, string, test)
    ssubst (new, old, string, test, start)
    ssubst (new, old, string, test, start, end)

Returns a string like string except that all substrings matching old are replaced by new. old and new need not to be of the same length. Default test function for matching is sequal. If ssubst should ignore case while searching for old, use sequalignore as test. Use start and end to limit searching. Note that the first character in string is in position 1.

Examples:

(%i1) ssubst("like","hate","I hate Thai food. I hate green tea.");
(%o1)          I like Thai food. I like green tea.
(%i2) ssubst("Indian","thai",%,'sequalignore,8,12);
(%o2)         I like Indian food. I like green tea.
Function: ssubstfirst
    ssubstfirst (new, old, string)
    ssubstfirst (new, old, string, test)
    ssubstfirst (new, old, string, test, start)
    ssubstfirst (new, old, string, test, start, end)

Like subst except that only the first substring that matches old is replaced.

Function: strim (seq,string)

Returns a string like string, but with all characters that appear in seq removed from both ends.

Examples:

(%i1) "/* comment */"$
(%i2) strim(" /*",%);
(%o2)                        comment
(%i3) slength(%);
(%o3)                           7
Function: striml (seq, string)

Like strim except that only the left end of string is trimmed.

Function: strimr (seq, string)

Like strim except that only the right end of string is trimmed.

Function: stringp (obj)

Returns true if obj is a string. See introduction for example.

Function: substring
    substring (string, start)
    substring (string, start, end)

Returns the substring of string beginning at position start and ending at position end. The character at position end is not included. If end is not given, the substring contains the rest of the string. Note that the first character in string is in position 1.

Examples:

(%i1) substring("substring",4);
(%o1)                        string
(%i2) substring(%,4,6);
(%o2)                          in
Function: supcase
    supcase (string)
    supcase (string, start)
    supcase (string, start, end)

Returns string except that lowercase characters from position start to end are replaced by the corresponding uppercase ones. If end is not given, all lowercase characters from start to the end of string are replaced.

Example:

(%i1) supcase("english",1,2);
(%o1)                        English
Function: tokens
    tokens (string)
    tokens (string, test)

Returns a list of tokens, which have been extracted from string. The tokens are substrings whose characters satisfy a certain test function. If test is not given, constituent is used as the default test. {constituent, alphacharp, digitcharp, lowercasep, uppercasep, charp, characterp, alphanumericp} is the set of test functions. (The Lisp-version of tokens is written by Paul Graham. ANSI Common Lisp, 1996, page 67.)

Examples:

(%i1) tokens("24 October 2005");
(%o1)                  [24, October, 2005]
(%i2) tokens("05-10-24",'digitcharp);
(%o2)                     [05, 10, 24]
(%i3) map(parse_string,%);
(%o3)                      [5, 10, 24]

Previous: String Processing, Up: stringproc-pkg   [Contents][Index]

71.5 Octets and Utilities for Cryptography

Function: base64 (arg)

Returns the base64-representation of arg as a string. The argument arg may be a string, a non-negative integer or a list of octets.

Examples:

(%i1) base64: base64("foo bar baz");
(%o1)                          Zm9vIGJhciBiYXo=
(%i2) string: base64_decode(base64);
(%o2)                            foo bar baz
(%i3) obase: 16.$
(%i4) integer: base64_decode(base64, 'number);
(%o4)                       666f6f206261722062617a
(%i5) octets: base64_decode(base64, 'list);
(%o5)            [66, 6F, 6F, 20, 62, 61, 72, 20, 62, 61, 7A]
(%i6) ibase: 16.$
(%i7) base64(octets);
(%o7)                          Zm9vIGJhciBiYXo=

Note that if arg contains umlauts (resp. octets larger than 127) the resulting base64-string is platform dependent. However the decoded string will be equal to the original.

Function: base64_decode
    base64_decode (base64-string)
    base64_decode (base64-string, return-type)

By default base64_decode decodes the base64-string back to the original string.

The optional argument return-type allows base64_decode to alternatively return the corresponding number or list of octets. return-type may be string, number or list.

Example: See base64.

Function: crc24sum
    crc24sum (octets)
    crc24sum (octets, return-type)

By default crc24sum returns the CRC24 checksum of an octet-list as a string.

The optional argument return-type allows crc24sum to alternatively return the corresponding number or list of octets. return-type may be string, number or list.

Example:

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.22 (GNU/Linux)

iQEcBAEBAgAGBQJVdCTzAAoJEG/1Mgf2DWAqCSYH/AhVFwhu1D89C3/QFcgVvZTM
wnOYzBUURJAL/cT+IngkLEpp3hEbREcugWp+Tm6aw3R4CdJ7G3FLxExBH/5KnDHi
rBQu+I7+3ySK2hpryQ6Wx5J9uZSa4YmfsNteR8up0zGkaulJeWkS4pjiRM+auWVe
vajlKZCIK52P080DG7Q2dpshh4fgTeNwqCuCiBhQ73t8g1IaLdhDN6EzJVjGIzam
/spqT/sTo6sw8yDOJjvU+Qvn6/mSMjC/YxjhRMaQt9EMrR1AZ4ukBF5uG1S7mXOH
WdiwkSPZ3gnIBhM9SuC076gLWZUNs6NqTeE3UzMjDAFhH3jYk1T7mysCvdtIkms=
=WmeC
-----END PGP SIGNATURE-----
(%i1) ibase : obase : 16.$
(%i2) sig64 : sconcat(
 "iQEcBAEBAgAGBQJVdCTzAAoJEG/1Mgf2DWAqCSYH/AhVFwhu1D89C3/QFcgVvZTM",
 "wnOYzBUURJAL/cT+IngkLEpp3hEbREcugWp+Tm6aw3R4CdJ7G3FLxExBH/5KnDHi",
 "rBQu+I7+3ySK2hpryQ6Wx5J9uZSa4YmfsNteR8up0zGkaulJeWkS4pjiRM+auWVe",
 "vajlKZCIK52P080DG7Q2dpshh4fgTeNwqCuCiBhQ73t8g1IaLdhDN6EzJVjGIzam",
 "/spqT/sTo6sw8yDOJjvU+Qvn6/mSMjC/YxjhRMaQt9EMrR1AZ4ukBF5uG1S7mXOH",
 "WdiwkSPZ3gnIBhM9SuC076gLWZUNs6NqTeE3UzMjDAFhH3jYk1T7mysCvdtIkms=" )$
(%i3) octets: base64_decode(sig64, 'list)$
(%i4) crc24: crc24sum(octets, 'list);
(%o4)                          [5A, 67, 82]
(%i5) base64(crc24);
(%o5)                              WmeC
Function: md5sum
    md5sum (arg)
    md5sum (arg, return-type)

Returns the MD5 checksum of a string, non-negative integer, list of octets, or binary (not character) input stream. A file for which an input stream is opened may be an ordinary text file; it is the stream which needs to be binary, not the file itself.

When the argument is an input stream, md5sum reads the entire content of the stream, but does not close the stream.

The default return value is a string containing 32 hex characters. The optional argument return-type allows md5sum to alternatively return the corresponding number or list of octets. return-type may be string, number or list.

Note that in case arg contains German umlauts or other non-ASCII characters (resp. octets larger than 127) the MD5 checksum is platform dependent.

Examples:

(%i1) ibase: obase: 16.$
(%i2) msg: "foo bar baz"$
(%i3) string: md5sum(msg);
(%o3)                  ab07acbb1e496801937adfa772424bf7
(%i4) integer: md5sum(msg, 'number);
(%o4)                 0ab07acbb1e496801937adfa772424bf7
(%i5) octets: md5sum(msg, 'list);
(%o5)        [0AB,7,0AC,0BB,1E,49,68,1,93,7A,0DF,0A7,72,42,4B,0F7]
(%i6) sdowncase( printf(false, "~{~2,'0x~^:~}", octets) );
(%o6)           ab:07:ac:bb:1e:49:68:01:93:7a:df:a7:72:42:4b:f7

The argument may be a binary input stream.

(%i1) S: openr_binary (file_search ("md5.lisp"));
(%o1) #<INPUT BUFFERED FILE-STREAM (UNSIGNED-BYTE 8)
  /home/robert/maxima/maxima-code/share/stringproc/md5.lisp>
(%i2) md5sum (S);
(%o2)           31a512ed53daf5b99495c9d05559355f
(%i3) close (S);
(%o3)                         true
Function: mgf1_sha1
    mgf1_sha1 (seed, len)
    mgf1_sha1 (seed, len, return-type)

Returns a pseudo random number of variable length. By default the returned value is a number with a length of len octets.

The optional argument return-type allows mgf1_sha1 to alternatively return the corresponding list of len octets. return-type may be number or list.

The computation of the returned value is described in RFC 3447, appendix B.2.1 MGF1. SHA1 is used as hash function, i.e. the randomness of the computed number relies on the randomness of SHA1 hashes.

Example:

(%i1) ibase: obase: 16.$
(%i2) number: mgf1_sha1(4711., 8);
(%o2)                        0e0252e5a2a42fea1
(%i3) octets: mgf1_sha1(4711., 8, 'list);
(%o3)                  [0E0,25,2E,5A,2A,42,0FE,0A1]
Function: number_to_octets (number)

Returns an octet-representation of number as a list of octets. The number must be a non-negative integer.

Example:

(%i1) ibase : obase : 16.$
(%i2) octets: [0ca,0fe,0ba,0be]$
(%i3) number: octets_to_number(octets);
(%o3)                            0cafebabe
(%i4) number_to_octets(number);
(%o4)                      [0CA, 0FE, 0BA, 0BE]
Function: octets_to_number (octets)

Returns a number by concatenating the octets in the list of octets.

Example: See number_to_octets.

Function: octets_to_oid (octets)

Computes an object identifier (OID) from the list of octets.

Example: RSA encryption OID

(%i1) ibase : obase : 16.$
(%i2) oid: octets_to_oid([2A,86,48,86,0F7,0D,1,1,1]);
(%o2)                      1.2.840.113549.1.1.1
(%i3) oid_to_octets(oid);
(%o3)               [2A, 86, 48, 86, 0F7, 0D, 1, 1, 1]
Function: octets_to_string
    octets_to_string (octets)
    octets_to_string (octets, encoding)

Decodes the list of octets into a string according to current system defaults. When decoding octets corresponding to Non-US-ASCII characters the result depends on the platform, application and underlying Lisp.

Example: Using system defaults (Maxima compiled with GCL, which uses no format definition and simply passes through the UTF-8-octets encoded by the GNU/Linux terminal).

(%i1) octets: string_to_octets("abc");
(%o1)                            [61, 62, 63]
(%i2) octets_to_string(octets);
(%o2)                                 abc
(%i3) ibase: obase: 16.$
(%i4) unicode(20AC);
(%o4)                                  €
(%i5) octets: string_to_octets(%);
(%o5)                           [0E2, 82, 0AC]
(%i6) octets_to_string(octets);
(%o6)                                  €
(%i7) utf8_to_unicode(octets);
(%o7)                                20AC

In case the external format of the Lisp reader is equal to UTF-8 the optional argument encoding allows to set the encoding for the octet to string conversion. If necessary see adjust_external_format for changing the external format.

Some names of supported encodings (see corresponding Lisp manual for more):
CCL, CLISP, SBCL: utf-8, ucs-2be, ucs-4be, iso-8859-1, cp1252, cp850
CMUCL: utf-8, utf-16-be, utf-32-be, iso8859-1, cp1252
ECL: utf-8, ucs-2be, ucs-4be, iso-8859-1, windows-cp1252, dos-cp850

Example (continued): Using the optional encoding argument (Maxima compiled with SBCL, GNU/Linux terminal).

(%i8) string_to_octets("€", "ucs-2be");
(%o8)                              [20, 0AC]
Function: oid_to_octets (oid-string)

Converts an object identifier (OID) to a list of octets.

Example: See octets_to_oid.

Function: sha1sum
    sha1sum (arg)
    sha1sum (arg, return-type)

Returns the SHA1 fingerprint of a string, a non-negative integer or a list of octets. The default return value is a string containing 40 hex characters.

The optional argument return-type allows sha1sum to alternatively return the corresponding number or list of octets. return-type may be string, number or list.

Example:

(%i1) ibase: obase: 16.$
(%i2) msg: "foo bar baz"$
(%i3) string: sha1sum(msg);
(%o3)              c7567e8b39e2428e38bf9c9226ac68de4c67dc39
(%i4) integer: sha1sum(msg, 'number);
(%o4)             0c7567e8b39e2428e38bf9c9226ac68de4c67dc39
(%i5) octets: sha1sum(msg, 'list);
(%o5)  [0C7,56,7E,8B,39,0E2,42,8E,38,0BF,9C,92,26,0AC,68,0DE,4C,67,0DC,39]
(%i6) sdowncase( printf(false, "~{~2,'0x~^:~}", octets) );
(%o6)     c7:56:7e:8b:39:e2:42:8e:38:bf:9c:92:26:ac:68:de:4c:67:dc:39

Note that in case arg contains German umlauts or other non-ASCII characters (resp. octets larger than 127) the SHA1 fingerprint is platform dependent.

Function: sha256sum
    sha256sum (arg)
    sha256sum (arg, return-type)

Returns the SHA256 fingerprint of a string, a non-negative integer or a list of octets. The default return value is a string containing 64 hex characters.

The optional argument return-type allows sha256sum to alternatively return the corresponding number or list of octets (see sha1sum).

Example:

(%i1) string: sha256sum("foo bar baz");
(%o1)  dbd318c1c462aee872f41109a4dfd3048871a03dedd0fe0e757ced57dad6f2d7

Note that in case arg contains German umlauts or other non-ASCII characters (resp. octets larger than 127) the SHA256 fingerprint is platform dependent.

Function: string_to_octets
    string_to_octets (string)
    string_to_octets (string, encoding)

Encodes a string into a list of octets according to current system defaults. When encoding strings containing Non-US-ASCII characters the result depends on the platform, application and underlying Lisp.

In case the external format of the Lisp reader is equal to UTF-8 the optional argument encoding allows to set the encoding for the string to octet conversion. If necessary see adjust_external_format for changing the external format.

See octets_to_string for examples and some more information.


Next: , Previous: stringproc-pkg, Up: Top   [Contents][Index]

72 unit


Next: , Previous: unit-pkg, Up: unit-pkg   [Contents][Index]

72.1 Introduction to Units

The unit package enables the user to convert between arbitrary units and work with dimensions in equations. The functioning of this package is radically different from the original Maxima units package - whereas the original was a basic list of definitions, this package uses rulesets to allow the user to chose, on a per dimension basis, what unit final answers should be rendered in. It will separate units instead of intermixing them in the display, allowing the user to readily identify the units associated with a particular answer. It will allow a user to simplify an expression to its fundamental Base Units, as well as providing fine control over simplifying to derived units. Dimensional analysis is possible, and a variety of tools are available to manage conversion and simplification options. In addition to customizable automatic conversion, units also provides a traditional manual conversion option.

Note - when unit conversions are inexact Maxima will make approximations resulting in fractions. This is a consequence of the techniques used to simplify units. The messages warning of this type of substitution are disabled by default in the case of units (normally they are on) since this situation occurs frequently and the warnings clutter the output. (The existing state of ratprint is restored after unit conversions, so user changes to that setting will be preserved otherwise.) If the user needs this information for units, they can set unitverbose:on to reactivate the printing of warnings from the unit conversion process.

unit is included in Maxima in the share/contrib/unit directory. It obeys normal Maxima package loading conventions:

(%i1) load("unit")$
*******************************************************************
*                       Units version 0.50                        *
*          Definitions based on the NIST Reference on             *
*              Constants, Units, and Uncertainty                  *
*       Conversion factors from various sources including         *
*                   NIST and the GNU units package                *
*******************************************************************

Redefining necessary functions...
WARNING: DEFUN/DEFMACRO: redefining function TOPLEVEL-MACSYMA-EVAL ...
WARNING: DEFUN/DEFMACRO: redefining function MSETCHK ...
WARNING: DEFUN/DEFMACRO: redefining function KILL1 ...
WARNING: DEFUN/DEFMACRO: redefining function NFORMAT ...
Initializing unit arrays...
Done.

The WARNING messages are expected and not a cause for concern - they indicate the unit package is redefining functions already defined in Maxima proper. This is necessary in order to properly handle units. The user should be aware that if other changes have been made to these functions by other packages those changes will be overwritten by this loading process.

The unit.mac file also loads a lisp file unit-functions.lisp which contains the lisp functions needed for the package.

Clifford Yapp is the primary author. He has received valuable assistance from Barton Willis of the University of Nebraska at Kearney (UNK), Robert Dodier, and other intrepid folk of the Maxima mailing list.

There are probably lots of bugs. Let me know. float and numer don’t do what is expected.

TODO : dimension functionality, handling of temperature, showabbr and friends. Show examples with addition of quantities containing units.


Previous: Introduction to Units, Up: unit-pkg   [Contents][Index]

72.2 Functions and Variables for Units

Function: setunits (list)

By default, the unit package does not use any derived dimensions, but will convert all units to the seven fundamental dimensions using MKS units.

(%i2) N;
                                     kg m
(%o2)                                ----
                                       2
                                      s
(%i3) dyn;
                                   1      kg m
(%o3)                           (------) (----)
                                 100000     2
                                           s
(%i4) g;
                                    1
(%o4)                             (----) (kg)
                                   1000
(%i5) centigram*inch/minutes^2;
                                  127        kg m
(%o5)                       (-------------) (----)
                             1800000000000     2
                                              s

In some cases this is the desired behavior. If the user wishes to use other units, this is achieved with the setunits command:

(%i6) setunits([centigram,inch,minute]);
(%o6)                                done
(%i7) N;
                            1800000000000   %in cg
(%o7)                      (-------------) (------)
                                 127            2
                                            %min
(%i8) dyn;
                               18000000   %in cg
(%o8)                         (--------) (------)
                                 127          2
                                          %min
(%i9) g;
(%o9)                             (100) (cg)
(%i10) centigram*inch/minutes^2;
                                    %in cg
(%o10)                              ------
                                        2
                                    %min

The setting of units is quite flexible. For example, if we want to get back to kilograms, meters, and seconds as defaults for those dimensions we can do:

(%i11) setunits([kg,m,s]);
(%o11)                               done
(%i12) centigram*inch/minutes^2;
                                  127        kg m
(%o12)                      (-------------) (----)
                             1800000000000     2
                                              s

Derived units are also handled by this command:

(%i17) setunits(N);
(%o17)                               done
(%i18) N;
(%o18)                                 N
(%i19) dyn;
                                    1
(%o19)                           (------) (N)
                                  100000
(%i20) kg*m/s^2;
(%o20)                                 N
(%i21) centigram*inch/minutes^2;
                                    127
(%o21)                        (-------------) (N)
                               1800000000000

Notice that the unit package recognized the non MKS combination of mass, length, and inverse time squared as a force, and converted it to Newtons. This is how Maxima works in general. If, for example, we prefer dyne to Newtons, we simply do the following:

(%i22) setunits(dyn);
(%o22)                               done
(%i23) kg*m/s^2;
(%o23)                          (100000) (dyn)
(%i24) centigram*inch/minutes^2;
                                  127
(%o24)                         (--------) (dyn)
                                18000000

To discontinue simplifying to any force, we use the uforget command:

(%i26) uforget(dyn);
(%o26)                               false
(%i27) kg*m/s^2;
                                     kg m
(%o27)                               ----
                                       2
                                      s
(%i28) centigram*inch/minutes^2;
                                  127        kg m
(%o28)                      (-------------) (----)
                             1800000000000     2
                                              s

This would have worked equally well with uforget(N) or uforget(%force).

See also uforget. To use this function write first load("unit").

Function: uforget (list)

By default, the unit package converts all units to the seven fundamental dimensions using MKS units. This behavior can be changed with the setunits command. After that, the user can restore the default behavior for a particular dimension by means of the uforget command:

(%i13) setunits([centigram,inch,minute]);
(%o13)                               done
(%i14) centigram*inch/minutes^2;
                                    %in cg
(%o14)                              ------
                                        2
                                    %min
(%i15) uforget([cg,%in,%min]);
(%o15)                      [false, false, false]
(%i16) centigram*inch/minutes^2;
                                  127        kg m
(%o16)                      (-------------) (----)
                             1800000000000     2
                                              s

uforget operates on dimensions, not units, so any unit of a particular dimension will work. The dimension itself is also a legal argument.

See also setunits. To use this function write first load("unit").

Function: convert (expr, list)

When resetting the global environment is overkill, there is the convert command, which allows one time conversions. It can accept either a single argument or a list of units to use in conversion. When a convert operation is done, the normal global evaluation system is bypassed, in order to avoid the desired result being converted again. As a consequence, for inexact calculations "rat" warnings will be visible if the global environment controlling this behavior (ratprint) is true. This is also useful for spot-checking the accuracy of a global conversion. Another feature is convert will allow a user to do Base Dimension conversions even if the global environment is set to simplify to a Derived Dimension.

(%i2) kg*m/s^2;
                                     kg m
(%o2)                                ----
                                       2
                                      s
(%i3) convert(kg*m/s^2,[g,km,s]);
                                     g km
(%o3)                                ----
                                       2
                                      s
(%i4) convert(kg*m/s^2,[g,inch,minute]);

`rat' replaced 39.37007874015748 by 5000/127 = 39.37007874015748
                              18000000000   %in g
(%o4)                        (-----------) (-----)
                                  127           2
                                            %min
(%i5) convert(kg*m/s^2,[N]);
(%o5)                                  N
(%i6) convert(kg*m^2/s^2,[N]);
(%o6)                                 m N
(%i7) setunits([N,J]);
(%o7)                                done
(%i8) convert(kg*m^2/s^2,[N]);
(%o8)                                 m N
(%i9) convert(kg*m^2/s^2,[N,inch]);

`rat' replaced 39.37007874015748 by 5000/127 = 39.37007874015748
                                 5000
(%o9)                           (----) (%in N)
                                 127
(%i10) convert(kg*m^2/s^2,[J]);
(%o10)                                 J
(%i11) kg*m^2/s^2;
(%o11)                                 J
(%i12) setunits([g,inch,s]);
(%o12)                               done
(%i13) kg*m/s^2;
(%o13)                                 N
(%i14) uforget(N);
(%o14)                               false
(%i15) kg*m/s^2;
                                5000000   %in g
(%o15)                         (-------) (-----)
                                  127       2
                                           s
(%i16) convert(kg*m/s^2,[g,inch,s]);

`rat' replaced 39.37007874015748 by 5000/127 = 39.37007874015748
                                5000000   %in g
(%o16)                         (-------) (-----)
                                  127       2
                                           s

See also setunits and uforget. To use this function write first load("unit").

Optional variable: usersetunits

Default value: none

If a user wishes to have a default unit behavior other than that described, they can make use of maxima-init.mac and the usersetunits variable. The unit package will check on startup to see if this variable has been assigned a list. If it has, it will use setunits on that list and take the units from that list to be defaults. uforget will revert to the behavior defined by usersetunits over its own defaults. For example, if we have a maxima-init.mac file containing:

usersetunits : [N,J];

we would see the following behavior:

(%i1) load("unit")$
*******************************************************************
*                       Units version 0.50                        *
*          Definitions based on the NIST Reference on             *
*              Constants, Units, and Uncertainty                  *
*       Conversion factors from various sources including         *
*                   NIST and the GNU units package                *
*******************************************************************

Redefining necessary functions...
WARNING: DEFUN/DEFMACRO: redefining function
 TOPLEVEL-MACSYMA-EVAL ...
WARNING: DEFUN/DEFMACRO: redefining function MSETCHK ...
WARNING: DEFUN/DEFMACRO: redefining function KILL1 ...
WARNING: DEFUN/DEFMACRO: redefining function NFORMAT ...
Initializing unit arrays...
Done.
User defaults found...
User defaults initialized.
(%i2) kg*m/s^2;
(%o2)                                  N
(%i3) kg*m^2/s^2;
(%o3)                                  J
(%i4) kg*m^3/s^2;
(%o4)                                 J m
(%i5) kg*m*km/s^2;
(%o5)                             (1000) (J)
(%i6) setunits([dyn,eV]);
(%o6)                                done
(%i7) kg*m/s^2;
(%o7)                           (100000) (dyn)
(%i8) kg*m^2/s^2;
(%o8)                     (6241509596477042688) (eV)
(%i9) kg*m^3/s^2;
(%o9)                    (6241509596477042688) (eV m)
(%i10) kg*m*km/s^2;
(%o10)                   (6241509596477042688000) (eV)
(%i11) uforget([dyn,eV]);
(%o11)                           [false, false]
(%i12) kg*m/s^2;
(%o12)                                 N
(%i13) kg*m^2/s^2;
(%o13)                                 J
(%i14) kg*m^3/s^2;
(%o14)                                J m
(%i15) kg*m*km/s^2;
(%o15)                            (1000) (J)

Without usersetunits, the initial inputs would have been converted to MKS, and uforget would have resulted in a return to MKS rules. Instead, the user preferences are respected in both cases. Notice these can still be overridden if desired. To completely eliminate this simplification - i.e. to have the user defaults reset to factory defaults - the dontusedimension command can be used. uforget can restore user settings again, but only if usedimension frees it for use. Alternately, kill(usersetunits) will completely remove all knowledge of the user defaults from the session. Here are some examples of how these various options work.

(%i2) kg*m/s^2;
(%o2)                                  N
(%i3) kg*m^2/s^2;
(%o3)                                  J
(%i4) setunits([dyn,eV]);
(%o4)                                done
(%i5) kg*m/s^2;
(%o5)                           (100000) (dyn)
(%i6) kg*m^2/s^2;
(%o6)                     (6241509596477042688) (eV)
(%i7) uforget([dyn,eV]);
(%o7)                          [false, false]
(%i8) kg*m/s^2;
(%o8)                                  N
(%i9) kg*m^2/s^2;
(%o9)                                  J
(%i10) dontusedimension(N);
(%o10)                             [%force]
(%i11) dontusedimension(J);
(%o11)                         [%energy, %force]
(%i12) kg*m/s^2;
                                     kg m
(%o12)                               ----
                                       2
                                      s
(%i13) kg*m^2/s^2;
                                         2
                                     kg m
(%o13)                               -----
                                       2
                                      s
(%i14) setunits([dyn,eV]);
(%o14)                               done
(%i15) kg*m/s^2;
                                     kg m
(%o15)                               ----
                                       2
                                      s
(%i16) kg*m^2/s^2;
                                         2
                                     kg m
(%o16)                               -----
                                       2
                                      s
(%i17) uforget([dyn,eV]);
(%o17)                         [false, false]
(%i18) kg*m/s^2;
                                     kg m
(%o18)                               ----
                                       2
                                      s
(%i19) kg*m^2/s^2;
                                         2
                                     kg m
(%o19)                               -----
                                       2
                                      s
(%i20) usedimension(N);
Done.  To have Maxima simplify to this dimension, use
setunits([unit]) to select a unit.
(%o20)                               true
(%i21) usedimension(J);
Done.  To have Maxima simplify to this dimension, use
setunits([unit]) to select a unit.
(%o21)                               true
(%i22) kg*m/s^2;
                                     kg m
(%o22)                               ----
                                       2
                                      s
(%i23) kg*m^2/s^2;
                                         2
                                     kg m
(%o23)                               -----
                                       2
                                      s
(%i24) setunits([dyn,eV]);
(%o24)                               done
(%i25) kg*m/s^2;
(%o25)                          (100000) (dyn)
(%i26) kg*m^2/s^2;
(%o26)                    (6241509596477042688) (eV)
(%i27) uforget([dyn,eV]);
(%o27)                           [false, false]
(%i28) kg*m/s^2;
(%o28)                                 N
(%i29) kg*m^2/s^2;
(%o29)                                 J
(%i30) kill(usersetunits);
(%o30)                               done
(%i31) uforget([dyn,eV]);
(%o31)                          [false, false]
(%i32) kg*m/s^2;
                                     kg m
(%o32)                               ----
                                       2
                                      s
(%i33) kg*m^2/s^2;
                                         2
                                     kg m
(%o33)                               -----
                                       2
                                      s

Unfortunately this wide variety of options is a little confusing at first, but once the user grows used to them they should find they have very full control over their working environment.

Function: metricexpandall (x)

Rebuilds global unit lists automatically creating all desired metric units. x is a numerical argument which is used to specify how many metric prefixes the user wishes defined. The arguments are as follows, with each higher number defining all lower numbers’ units:

           0 - none. Only base units
           1 - kilo, centi, milli
(default)  2 - giga, mega, kilo, hecto, deka, deci, centi, milli,
               micro, nano
           3 - peta, tera, giga, mega, kilo, hecto, deka, deci,
               centi, milli, micro, nano, pico, femto
           4 - all

Normally, Maxima will not define the full expansion since this results in a very large number of units, but metricexpandall can be used to rebuild the list in a more or less complete fashion. The relevant variable in the unit.mac file is %unitexpand.

Variable: %unitexpand

Default value: 2

This is the value supplied to metricexpandall during the initial loading of unit.


Next: , Previous: unit-pkg, Up: Top   [Contents][Index]

73 zeilberger


Next: , Previous: zeilberger-pkg, Up: zeilberger-pkg   [Contents][Index]

73.1 Introduction to zeilberger

zeilberger is an implementation of Zeilberger’s algorithm for definite hypergeometric summation, and also Gosper’s algorithm for indefinite hypergeometric summation.

zeilberger makes use of the "filtering" optimization method developed by Axel Riese.

zeilberger was developed by Fabrizio Caruso.

load ("zeilberger") loads this package.

73.1.1 The indefinite summation problem

zeilberger implements Gosper’s algorithm for indefinite hypergeometric summation. Given a hypergeometric term F_k in k we want to find its hypergeometric anti-difference, that is, a hypergeometric term f_k such that

$$ F_k = f_{k+1} - f_k. $$

73.1.2 The definite summation problem

zeilberger implements Zeilberger’s algorithm for definite hypergeometric summation. Given a proper hypergeometric term (in n and k) \(F_{n,k}\) and a positive integer d we want to find a d-th order linear recurrence with polynomial coefficients (in n) for \(F_{n,k}\) and a rational function R in n and k such that

$$ a_0 \, F_{n,k} + \ldots + a_d \, F_{n+d,k} = \Delta_K \left(R\left(n,k\right) F_{n,k}\right), $$

where \(\Delta_k\) is the k-forward difference operator, i.e., \(\Delta_k \left(t_k\right) \equiv t_{k+1} - t_k.\)

73.1.3 Verbosity levels

There are also verbose versions of the commands which are called by adding one of the following prefixes:

Summary

Just a summary at the end is shown

Verbose

Some information in the intermediate steps

VeryVerbose

More information

Extra

Even more information including information on the linear system in Zeilberger’s algorithm

For example:
GosperVerbose, parGosperVeryVerbose, ZeilbergerExtra, AntiDifferenceSummary.


Previous: Introduction to zeilberger, Up: zeilberger-pkg   [Contents][Index]

73.2 Functions and Variables for zeilberger

Function: AntiDifference (F_k, k)

Returns the hypergeometric anti-difference of F_k, if it exists.
Otherwise AntiDifference returns no_hyp_antidifference.

Function: Gosper (F_k, k)

Returns the rational certificate R(k) for F_k, that is, a rational function such that \(F_k = R\left(k+1\right) \, F_{k+1} - R\left(k\right) \, F_k,\) if it exists. Otherwise, Gosper returns no_hyp_sol.

Function: GosperSum (F_k, k, a, b)

Returns the summation of F_k from k = a to k = b if F_k has a hypergeometric anti-difference. Otherwise, GosperSum returns nongosper_summable.

Examples:

(%i1) load ("zeilberger")$
(%i2) GosperSum ((-1)^k*k / (4*k^2 - 1), k, 1, n);
Dependent equations eliminated:  (1)
                           3       n + 1
                      (n + -) (- 1)
                           2               1
(%o2)               - ------------------ - -
                                  2        4
                      2 (4 (n + 1)  - 1)
(%i3) GosperSum (1 / (4*k^2 - 1), k, 1, n);
                                3
                          - n - -
                                2       1
(%o3)                  -------------- + -
                                2       2
                       4 (n + 1)  - 1
(%i4) GosperSum (x^k, k, 1, n);
                          n + 1
                         x          x
(%o4)                    ------ - -----
                         x - 1    x - 1
(%i5) GosperSum ((-1)^k*a! / (k!*(a - k)!), k, 1, n);
                                n + 1
                a! (n + 1) (- 1)              a!
(%o5)       - ------------------------- - ----------
              a (- n + a - 1)! (n + 1)!   a (a - 1)!
(%i6) GosperSum (k*k!, k, 1, n);
Dependent equations eliminated:  (1)
(%o6)                     (n + 1)! - 1
(%i7) GosperSum ((k + 1)*k! / (k + 1)!, k, 1, n);
                  (n + 1) (n + 2) (n + 1)!
(%o7)             ------------------------ - 1
                          (n + 2)!
(%i8) GosperSum (1 / ((a - k)!*k!), k, 1, n);
(%o8)                  NON_GOSPER_SUMMABLE
Function: parGosper (F_(n,k), k, n, d)

Attempts to find a d-th order recurrence for F_(n,k).

The algorithm yields a sequence [s_1, s_2, ..., s_m] of solutions. Each solution has the form

[R(n, k), [a_0, a_1, ..., a_d]].

parGosper returns [] if it fails to find a recurrence.

Function: Zeilberger (F_(n,k), k, n)

Attempts to compute the indefinite hypergeometric summation of F_(n,k).

Zeilberger first invokes Gosper, and if that fails to find a solution, then invokes parGosper with order 1, 2, 3, ..., up to MAX_ORD. If Zeilberger finds a solution before reaching MAX_ORD, it stops and returns the solution.

The algorithms yields a sequence [s_1, s_2, ..., s_m] of solutions. Each solution has the form

[R(n,k), [a_0, a_1, ..., a_d]].

Zeilberger returns [] if it fails to find a solution.

Zeilberger invokes Gosper only if Gosper_in_Zeilberger is true.

73.3 General global variables

Global variable: MAX_ORD

Default value: 5

MAX_ORD is the maximum recurrence order attempted by Zeilberger.

Global variable: simplified_output

Default value: false

When simplified_output is true, functions in the zeilberger package attempt further simplification of the solution.

Global variable: linear_solver

Default value: linsolve

linear_solver names the solver which is used to solve the system of equations in Zeilberger’s algorithm.

Global variable: warnings

Default value: true

When warnings is true, functions in the zeilberger package print warning messages during execution.

Global variable: Gosper_in_Zeilberger

Default value: true

When Gosper_in_Zeilberger is true, the Zeilberger function calls Gosper before calling parGosper. Otherwise, Zeilberger goes immediately to parGosper.

Global variable: trivial_solutions

Default value: true

When trivial_solutions is true, Zeilberger returns solutions which have certificate equal to zero, or all coefficients equal to zero.

73.4 Variables related to the modular test

Global variable: mod_test

Default value: false

When mod_test is true, parGosper executes a modular test for discarding systems with no solutions.

Global variable: modular_linear_solver

Default value: linsolve

modular_linear_solver names the linear solver used by the modular test in parGosper.

Global variable: ev_point

Default value: big_primes[10]

ev_point is the value at which the variable n is evaluated when executing the modular test in parGosper.

Global variable: mod_big_prime

Default value: big_primes[1]

mod_big_prime is the modulus used by the modular test in parGosper.

Global variable: mod_threshold

Default value: 4

mod_threshold is the greatest order for which the modular test in parGosper is attempted.


Previous: zeilberger-pkg, Up: Top   [Contents][Index]

74 Указатель функций и переменных

Appendix A Указатель функций и переменных

Jump to:   !   #   %   '   *   +   -   .   /   :   <   =   >   ?   ^   _   |   ~  
A   B   C   D   E   F   G   H   I   J   K   L   M   N   O   P   Q   R   S   T   U   V   W   X   Y   Z  
Index Entry  Section

!
!: Общие операторы
!!: Общие операторы

#
#: Общие операторы

%
%: Функции и переменные для ввода и вывода
%%: Функции и переменные для ввода и вывода
%c: Функции и переменные пакета contrib_ode
%e: Математические константы
%edispflag: Функции и переменные для ввода и вывода
%emode: Функции и переменные для выражений
%enumer: Функции и переменные для выражений
%f: Hypergeometric Functions
%gamma: Функции и переменные для теории чисел
%i: Математические константы
%iargs: Функции и переменные для тригонометрии
%k1: Функции и переменные пакета contrib_ode
%k2: Функции и переменные пакета contrib_ode
%m: Hypergeometric Functions
%phi: Математические константы
%pi: Математические константы
%piargs: Функции и переменные для тригонометрии
%rnum: Functions and Variables for Equations
%rnum_list: Functions and Variables for Equations
%s: Bessel Functions
%th: Функции и переменные для ввода и вывода
%unitexpand: Functions and Variables for Units
%w: Hypergeometric Functions

'
': Введение в командную строку
'': Введение в командную строку

*
*: Арифметические операторы
**: Арифметические операторы

+
+: Арифметические операторы

-
-: Арифметические операторы

.
.: Общие операторы

/
/: Арифметические операторы

:
:: Общие операторы
::: Общие операторы
::=: Общие операторы
:=: Общие операторы

<
<: Операторы отношения
<=: Операторы отношения

=
=: Общие операторы

>
>: Операторы отношения
>=: Операторы отношения

?
?: Функции и переменные для ввода и вывода
??: Функции и переменные для ввода и вывода

^
^: Арифметические операторы
^^: Общие операторы

_
_: Функции и переменные для ввода и вывода
__: Функции и переменные для ввода и вывода

|
|: Функции и переменные пакета itensor

~
~: Функции и переменные пакета itensor

A
abasep: Функции и переменные пакета atensor
abs: Общие операторы
absboxchar: Функции и переменные для ввода и вывода
absint: Functions and Variables for Fourier series
absolute_real_time: Функции и переменные времени выполнения
acos: Функции и переменные для тригонометрии
acosh: Функции и переменные для тригонометрии
acot: Функции и переменные для тригонометрии
acoth: Функции и переменные для тригонометрии
acsc: Функции и переменные для тригонометрии
acsch: Функции и переменные для тригонометрии
activate: Функции для работы с контекстами
activecontexts: Функции для работы с контекстами
adapt_depth: Plotting Options
adapt_depth: Функции и переменные пакета draw
addcol: Functions and Variables for Matrices and Linear Algebra
additive: Общие операторы
additive: Functions and Variables for Simplification
addmatrices: Functions and Variables for linearalgebra
addrow: Functions and Variables for Matrices and Linear Algebra
add_edge: Функции и переменные пакета graphs
add_edges: Функции и переменные пакета graphs
add_vertex: Функции и переменные пакета graphs
add_vertices: Функции и переменные пакета graphs
adim: Функции и переменные пакета atensor
adjacency_matrix: Функции и переменные пакета graphs
adjoin: Функции и переменные для работы с множествами
adjoint: Functions and Variables for Matrices and Linear Algebra
adjust_external_format: Characters
af: Функции и переменные пакета atensor
aform: Функции и переменные пакета atensor
agd: Package functs
airy_ai: Airy Functions
airy_bi: Airy Functions
airy_dai: Airy Functions
airy_dbi: Airy Functions
algebraic: Functions and Variables for Polynomials
algepsilon: Functions and Variables for Equations
algexact: Functions and Variables for Equations
algfac: Functions and Variables for algebraic extensions
algnorm: Functions and Variables for algebraic extensions
algsys: Functions and Variables for Equations
algtrace: Functions and Variables for algebraic extensions
alg_type: Функции и переменные пакета atensor
alias: Функции и переменные для работы в командной строке
aliases: Вспомогательные функции и переменные
allbut: Общие операторы
allroots: Functions and Variables for Equations
allsym: Функции и переменные пакета itensor
all_dotsimp_denoms: Функции и переменные пакета affine
alphabetic: Вспомогательные функции и переменные
alphacharp: Characters
alphanumericp: Characters
and: Общие операторы
antid: Functions and Variables for Differentiation
antidiff: Functions and Variables for Differentiation
AntiDifference: Functions and Variables for zeilberger
antisymmetric: Общие операторы
antisymmetric: Functions and Variables for Simplification
append: Функции и переменные для работы со списками
appendfile: Функции и переменные для ввода и вывода
apply: Функции и переменные для определения функций
apply1: Функции и переменные для правил преобразования и шаблонов
apply2: Функции и переменные для правил преобразования и шаблонов
applyb1: Функции и переменные для правил преобразования и шаблонов
apropos: Вспомогательные функции и переменные
args: Вспомогательные функции и переменные
arithmetic: Package functs
arithsum: Package functs
array: Функции и переменные для работы с массивами
array: Функции и переменные для работы с массивами
array: Функции и переменные для работы с массивами
arrayapply: Функции и переменные для работы с массивами
arrayinfo: Функции и переменные для работы с массивами
arraymake: Функции и переменные для работы с массивами
arrays: Функции и переменные для работы с массивами
ascii: Characters
asec: Функции и переменные для тригонометрии
asech: Функции и переменные для тригонометрии
asin: Функции и переменные для тригонометрии
asinh: Функции и переменные для тригонометрии
assoc: Функции и переменные для работы со списками
assoc: Функции и переменные для работы со списками
assoc_legendre_p: Functions and Variables for orthogonal polynomials
assoc_legendre_q: Functions and Variables for orthogonal polynomials
assume: Функции для работы с контекстами
assumescalar: Функции для работы с контекстами
assume_external_byte_order: Functions and Variables for binary input and output
assume_pos: Функции для работы с контекстами
assume_pos_pred: Функции для работы с контекстами
asymbol: Функции и переменные пакета atensor
at: Функции и переменные для выражений
at: Функции и переменные для выражений
at: Functions and Variables for Differentiation
atan: Функции и переменные для тригонометрии
atan2: Функции и переменные для тригонометрии
atanh: Функции и переменные для тригонометрии
atensimp: Функции и переменные пакета atensor
atom: Функции и переменные для работы со списками
atomgrad: Functions and Variables for Differentiation
atrig1: Функции и переменные для тригонометрии
atvalue: Functions and Variables for Differentiation
augcoefmatrix: Functions and Variables for Matrices and Linear Algebra
augmented_lagrangian_method: Функции и переменные пакета augmented_lagrangian
augmented_lagrangian_method: Функции и переменные пакета augmented_lagrangian
av: Функции и переменные пакета atensor
average_degree: Функции и переменные пакета graphs
axes: Plotting Options
axis_3d: Функции и переменные пакета draw
axis_bottom: Функции и переменные пакета draw
axis_left: Функции и переменные пакета draw
axis_right: Функции и переменные пакета draw
axis_top: Функции и переменные пакета draw
azimuth: Plotting Options

B
backsubst: Functions and Variables for Equations
backtrace: Функции и переменные для программирования на Maxima
backtrace: Функции и переменные для программирования на Maxima
bars: Функции и переменные пакета draw
barsplot: Функции и переменные для статистических графиков
barsplot: Функции и переменные для статистических графиков
barsplot: Функции и переменные для статистических графиков
barsplot: Функции и переменные для статистических графиков
barsplot: Функции и переменные для статистических графиков
barsplot: Функции и переменные для статистических графиков
base64: Octets and Utilities for Cryptography
base64_decode: Octets and Utilities for Cryptography
bashindices: Функции и переменные для работы с массивами
bashindices: Functions and Variables for Sums and Products
batch: Функции и переменные для ввода и вывода
batchload: Функции и переменные для ввода и вывода
bc2: Функции и переменные для дифференциальных уравнений
bdiscr: Functions and Variables for algebraic extensions
bdvac: Функции и переменные пакета ctensor
belln: Функции и переменные для работы с множествами
berlefact: Functions and Variables for Polynomials
bern: Функции и переменные для теории чисел
bernpoly: Функции и переменные для теории чисел
besselexpand: Bessel Functions
bessel_i: Bessel Functions
bessel_j: Bessel Functions
bessel_k: Bessel Functions
bessel_y: Bessel Functions
beta: Gamma and Factorial Functions
beta_args_sum_to_integer: Gamma and Factorial Functions
beta_expand: Gamma and Factorial Functions
beta_incomplete: Gamma and Factorial Functions
beta_incomplete_generalized: Gamma and Factorial Functions
beta_incomplete_regularized: Gamma and Factorial Functions
bezout: Functions and Variables for Polynomials
bfallroots: Functions and Variables for Equations
bffac: Gamma and Factorial Functions
bfhzeta: Функции и переменные для теории чисел
bfpsi: Gamma and Factorial Functions
bfpsi0: Gamma and Factorial Functions
bfzeta: Функции и переменные для теории чисел
bf_fft: Functions and Variables for fast Fourier transform
bf_find_root: Functions for numerical solution of equations
bf_find_root: Functions for numerical solution of equations
bf_inverse_fft: Functions and Variables for fast Fourier transform
bf_inverse_real_fft: Functions and Variables for fast Fourier transform
bf_real_fft: Functions and Variables for fast Fourier transform
biconected_components: Функции и переменные пакета graphs
bimetric: Функции и переменные пакета ctensor
binomial: Функции и переменные для теории чисел
bipartition: Функции и переменные пакета graphs
block: Функции и переменные для определения функций
block: Функции и переменные для определения функций
blockmatrixp: Functions and Variables for linearalgebra
bode_gain: Функции и переменные пакета bode
bode_phase: Функции и переменные пакета bode
border: Функции и переменные пакета draw
bothcoef: Functions and Variables for Polynomials
boundaries_array: Функции и переменные пакета draw
box: Plotting Options
box: Функции и переменные для выражений
box: Функции и переменные для выражений
boxchar: Функции и переменные для выражений
boxplot: Функции и переменные для статистических графиков
boxplot: Функции и переменные для статистических графиков
break: Функции и переменные для определения функций
breakup: Functions and Variables for Equations
bug_report: Функции и переменные для работы с ошибками
buildq: Макросы
build_info: Функции и переменные для работы с ошибками
burn: Функции и переменные для теории чисел

C
cabs: Общие операторы
canform: Функции и переменные пакета itensor
canform: Функции и переменные пакета itensor
canten: Функции и переменные пакета itensor
cardinality: Функции и переменные для работы с множествами
carg: Функции и переменные для выражений
cartan: Functions and Variables for Differentiation
cartesian_product: Функции и переменные для работы с множествами
catch: Функции и переменные для определения функций
cauchysum: Functions and Variables for Series
cauchy_matrix: Functions and Variables for Matrices and Linear Algebra
cbffac: Gamma and Factorial Functions
cdf_bernoulli: Функции и переменные для дискретных распределений
cdf_beta: Функции и переменные для непрерывных распределений
cdf_binomial: Функции и переменные для дискретных распределений
cdf_cauchy: Функции и переменные для непрерывных распределений
cdf_chi2: Функции и переменные для непрерывных распределений
cdf_continuous_uniform: Функции и переменные для непрерывных распределений
cdf_discrete_uniform: Функции и переменные для дискретных распределений
cdf_exp: Функции и переменные для непрерывных распределений
cdf_f: Функции и переменные для непрерывных распределений
cdf_gamma: Функции и переменные для непрерывных распределений
cdf_geometric: Функции и переменные для дискретных распределений
cdf_gumbel: Функции и переменные для непрерывных распределений
cdf_hypergeometric: Функции и переменные для дискретных распределений
cdf_laplace: Функции и переменные для непрерывных распределений
cdf_logistic: Функции и переменные для непрерывных распределений
cdf_lognormal: Функции и переменные для непрерывных распределений
cdf_negative_binomial: Функции и переменные для дискретных распределений
cdf_normal: Функции и переменные для непрерывных распределений
cdf_pareto: Функции и переменные для непрерывных распределений
cdf_poisson: Функции и переменные для дискретных распределений
cdf_rank_sum: Functions and Variables for special distributions
cdf_rayleigh: Функции и переменные для непрерывных распределений
cdf_signed_rank: Functions and Variables for special distributions
cdf_student_t: Функции и переменные для непрерывных распределений
cdf_weibull: Функции и переменные для непрерывных распределений
cdisplay: Функции и переменные пакета ctensor
ceiling: Общие операторы
central_moment: Функции и переменные для описательной статистики
central_moment: Функции и переменные для описательной статистики
cequal: Characters
cequalignore: Characters
cf: Функции и переменные для теории чисел
cfdisrep: Функции и переменные для теории чисел
cfexpand: Функции и переменные для теории чисел
cflength: Функции и переменные для теории чисел
cframe_flag: Функции и переменные пакета ctensor
cgeodesic: Функции и переменные пакета ctensor
cgreaterp: Characters
cgreaterpignore: Characters
changename: Функции и переменные пакета itensor
changevar: Functions and Variables for Integration
chaosgame: Функции и переменные пакета dynamics
charat: String Processing
charfun: Общие операторы
charfun2: Функции и переменные пакета interpol
charlist: String Processing
charp: Characters
charpoly: Functions and Variables for Matrices and Linear Algebra
chebyshev_t: Functions and Variables for orthogonal polynomials
chebyshev_u: Functions and Variables for orthogonal polynomials
checkdiv: Функции и переменные пакета ctensor
check_overlaps: Функции и переменные пакета affine
cholesky: Functions and Variables for linearalgebra
christof: Функции и переменные пакета ctensor
chromatic_index: Функции и переменные пакета graphs
chromatic_number: Функции и переменные пакета graphs
cint: Characters
circulant_graph: Функции и переменные пакета graphs
clear_edge_weight: Функции и переменные пакета graphs
clear_rules: Функции и переменные для правил преобразования и шаблонов
clear_vertex_label: Функции и переменные пакета graphs
clebsch_graph: Функции и переменные пакета graphs
clessp: Characters
clesspignore: Characters
close: String Input and Output
closefile: Функции и переменные для ввода и вывода
cmetric: Функции и переменные пакета ctensor
cmetric: Функции и переменные пакета ctensor
cnonmet_flag: Функции и переменные пакета ctensor
coeff: Functions and Variables for Polynomials
coefmatrix: Functions and Variables for Matrices and Linear Algebra
cograd: Функции и переменные пакета ctensor
col: Functions and Variables for Matrices and Linear Algebra
collapse: Функции и переменные для ввода и вывода
collectterms: Package facexp
color: Plotting Options
color: Функции и переменные пакета draw
colorbox: Функции и переменные пакета draw
color_bar: Plotting Options
color_bar_tics: Plotting Options
columnop: Functions and Variables for linearalgebra
columns: Функции и переменные пакета draw
columnspace: Functions and Variables for linearalgebra
columnswap: Functions and Variables for linearalgebra
columnvector: Functions and Variables for Matrices and Linear Algebra
combination: Package functs
combine: Functions and Variables for Simplification
commutative: Общие операторы
commutative: Functions and Variables for Simplification
comp2pui: Functions and Variables for Symmetries
compare: Общие операторы
compfile: Функции и переменные для определения функций
compfile: Функции и переменные для определения функций
compfile: Функции и переменные для определения функций
compile: Функции и переменные для определения функций
compile: Функции и переменные для определения функций
compile: Функции и переменные для определения функций
compile_file: Функции и переменные для определения функций
compile_file: Функции и переменные для определения функций
compile_file: Функции и переменные для определения функций
complement_graph: Функции и переменные пакета graphs
complete_bipartite_graph: Функции и переменные пакета graphs
complete_graph: Функции и переменные пакета graphs
components: Функции и переменные пакета itensor
concan: Функции и переменные пакета itensor
concat: Функции и переменные для ввода и вывода
conmetderiv: Функции и переменные пакета itensor
connected_components: Функции и переменные пакета graphs
connect_vertices: Функции и переменные пакета graphs
cons: Функции и переменные для работы со списками
constant: Функции и переменные для выражений
constantp: Функции и переменные для выражений
constituent: Characters
cont2part: Functions and Variables for Symmetries
content: Functions and Variables for Polynomials
context: Функции для работы с контекстами
contexts: Функции для работы с контекстами
continuous_freq: Функции и переменные для манипулирования данными
continuous_freq: Функции и переменные для манипулирования данными
contortion: Функции и переменные пакета ctensor
contour: Функции и переменные пакета draw
contour_levels: Функции и переменные пакета draw
contract: Функции и переменные пакета itensor
contract: Functions and Variables for Symmetries
contract_edge: Функции и переменные пакета graphs
contragrad: Функции и переменные пакета ctensor
contrib_ode: Функции и переменные пакета contrib_ode
convert: Functions and Variables for Units
coord: Функции и переменные пакета itensor
copylist: Функции и переменные для работы со списками
copymatrix: Functions and Variables for Matrices and Linear Algebra
copy_graph: Функции и переменные пакета graphs
cor: Функции и переменные для многомерной описательной статистики
cor: Функции и переменные для многомерной описательной статистики
cos: Функции и переменные для тригонометрии
cosh: Функции и переменные для тригонометрии
cosnpiflag: Functions and Variables for Fourier series
cot: Функции и переменные для тригонометрии
coth: Функции и переменные для тригонометрии
cov: Функции и переменные для многомерной описательной статистики
cov1: Функции и переменные для многомерной описательной статистики
covdiff: Функции и переменные пакета itensor
covect: Functions and Variables for Matrices and Linear Algebra
covers: Package functs
crc24sum: Octets and Utilities for Cryptography
create_graph: Функции и переменные пакета graphs
create_graph: Функции и переменные пакета graphs
create_graph: Функции и переменные пакета graphs
create_list: Функции и переменные для работы со списками
csc: Функции и переменные для тригонометрии
csch: Функции и переменные для тригонометрии
csetup: Функции и переменные пакета ctensor
cspline: Функции и переменные пакета interpol
cspline: Функции и переменные пакета interpol
ctaylor: Функции и переменные пакета ctensor
ctaypov: Функции и переменные пакета ctensor
ctaypt: Функции и переменные пакета ctensor
ctayswitch: Функции и переменные пакета ctensor
ctayvar: Функции и переменные пакета ctensor
ctorsion_flag: Функции и переменные пакета ctensor
ctransform: Функции и переменные пакета ctensor
ctranspose: Functions and Variables for linearalgebra
ctrgsimp: Функции и переменные пакета ctensor
ct_coords: Функции и переменные пакета ctensor
ct_coordsys: Функции и переменные пакета ctensor
ct_coordsys: Функции и переменные пакета ctensor
cube_graph: Функции и переменные пакета graphs
current_let_rule_package: Функции и переменные для правил преобразования и шаблонов
cv: Функции и переменные для описательной статистики
cv: Функции и переменные для описательной статистики
cycle_digraph: Функции и переменные пакета graphs
cycle_graph: Функции и переменные пакета graphs
cylindrical: Функции и переменные пакета draw

D
dblint: Functions and Variables for Integration
deactivate: Функции для работы с контекстами
debugmode: Функции и переменные для работы в командной строке
declare: Функции и переменные для выражений
declare_translated: Функции и переменные для определения функций
declare_weights: Функции и переменные пакета affine
decsym: Функции и переменные пакета itensor
default_let_rule_package: Функции и переменные для правил преобразования и шаблонов
defcon: Функции и переменные пакета itensor
defcon: Функции и переменные пакета itensor
define: Функции и переменные для определения функций
define: Функции и переменные для определения функций
define: Функции и переменные для определения функций
define: Функции и переменные для определения функций
define: Функции и переменные для определения функций
define_opproperty: Functions and Variables for Simplification
define_variable: Функции и переменные для определения функций
defint: Functions and Variables for Integration
defmatch: Функции и переменные для правил преобразования и шаблонов
defmatch: Функции и переменные для правил преобразования и шаблонов
defrule: Функции и переменные для правил преобразования и шаблонов
deftaylor: Functions and Variables for Series
degree_sequence: Функции и переменные пакета graphs
del: Functions and Variables for Differentiation
delay: Функции и переменные пакета draw
delete: Функции и переменные для работы со списками
delete: Функции и переменные для работы со списками
deleten: Функции и переменные пакета ctensor
delta: Functions and Variables for Differentiation
demo: Справочная система
demoivre: Functions and Variables for Simplification
demoivre: Functions and Variables for Simplification
denom: Functions and Variables for Polynomials
dependencies: Functions and Variables for Differentiation
dependencies: Functions and Variables for Differentiation
depends: Functions and Variables for Differentiation
derivabbrev: Functions and Variables for Differentiation
derivdegree: Functions and Variables for Differentiation
derivlist: Functions and Variables for Differentiation
derivsubst: Functions and Variables for Differentiation
describe: Справочная система
describe: Справочная система
describe: Справочная система
desolve: Функции и переменные для дифференциальных уравнений
desolve: Функции и переменные для дифференциальных уравнений
determinant: Functions and Variables for Matrices and Linear Algebra
detout: Functions and Variables for Matrices and Linear Algebra
dgauss_a: Функции и переменные пакета contrib_ode
dgauss_b: Функции и переменные пакета contrib_ode
dgeev: Functions and Variables for lapack
dgemm: Functions and Variables for lapack
dgeqrf: Functions and Variables for lapack
dgesv: Functions and Variables for lapack
dgesvd: Functions and Variables for lapack
diag: Функции и переменные пакета diag
diagmatrix: Functions and Variables for Matrices and Linear Algebra
diagmatrixp: Функции и переменные пакета ctensor
diagmetric: Функции и переменные пакета ctensor
diag_matrix: Functions and Variables for linearalgebra
diameter: Функции и переменные пакета graphs
diff: Functions and Variables for Differentiation
diff: Functions and Variables for Differentiation
diff: Функции и переменные пакета itensor
digitcharp: Characters
dim: Функции и переменные пакета ctensor
dimacs_export: Функции и переменные пакета graphs
dimacs_export: Функции и переменные пакета graphs
dimacs_import: Функции и переменные пакета graphs
dimension: Functions and Variables for Equations
direct: Functions and Variables for Symmetries
discrete_freq: Функции и переменные для манипулирования данными
disjoin: Функции и переменные для работы с множествами
disjointp: Функции и переменные для работы с множествами
disolate: Функции и переменные для выражений
disp: Функции и переменные для ввода и вывода
dispcon: Функции и переменные для ввода и вывода
dispcon: Функции и переменные для ввода и вывода
dispflag: Functions and Variables for Equations
dispform: Функции и переменные для выражений
dispfun: Функции и переменные для определения функций
dispfun: Функции и переменные для определения функций
dispJordan: Функции и переменные пакета diag
display: Функции и переменные для ввода и вывода
display2d: Функции и переменные для ввода и вывода
display_format_internal: Функции и переменные для ввода и вывода
disprule: Функции и переменные для правил преобразования и шаблонов
disprule: Функции и переменные для правил преобразования и шаблонов
dispterms: Функции и переменные для ввода и вывода
distrib: Функции и переменные для выражений
distrib: Functions and Variables for Simplification
distribute_over: Functions and Variables for Simplification
divide: Functions and Variables for Polynomials
divisors: Функции и переменные для работы с множествами
divsum: Функции и переменные для теории чисел
divsum: Функции и переменные для теории чисел
dkummer_m: Функции и переменные пакета contrib_ode
dkummer_u: Функции и переменные пакета contrib_ode
dlange: Functions and Variables for lapack
do: Функции и переменные для программирования на Maxima
doallmxops: Functions and Variables for Matrices and Linear Algebra
dodecahedron_graph: Функции и переменные пакета graphs
domain: Functions and Variables for Simplification
domxexpt: Functions and Variables for Matrices and Linear Algebra
domxmxops: Functions and Variables for Matrices and Linear Algebra
domxnctimes: Functions and Variables for Matrices and Linear Algebra
dontfactor: Functions and Variables for Matrices and Linear Algebra
doscmxops: Functions and Variables for Matrices and Linear Algebra
doscmxplus: Functions and Variables for Matrices and Linear Algebra
dot0nscsimp: Functions and Variables for Matrices and Linear Algebra
dot0simp: Functions and Variables for Matrices and Linear Algebra
dot1simp: Functions and Variables for Matrices and Linear Algebra
dotassoc: Functions and Variables for Matrices and Linear Algebra
dotconstrules: Functions and Variables for Matrices and Linear Algebra
dotdistrib: Functions and Variables for Matrices and Linear Algebra
dotexptsimp: Functions and Variables for Matrices and Linear Algebra
dotident: Functions and Variables for Matrices and Linear Algebra
dotproduct: Functions and Variables for linearalgebra
dotscrules: Functions and Variables for Matrices and Linear Algebra
dotsimp: Функции и переменные пакета affine
dpart: Функции и переменные для выражений
draw: Функции и переменные пакета draw
draw2d: Функции и переменные пакета draw
draw3d: Функции и переменные пакета draw
draw_graph: Функции и переменные пакета graphs
draw_graph: Функции и переменные пакета graphs
draw_graph_program: Функции и переменные пакета graphs
dscalar: Функции и переменные пакета ctensor

E
echelon: Functions and Variables for Matrices and Linear Algebra
edges: Функции и переменные пакета graphs
edge_coloring: Функции и переменные пакета graphs
eigens_by_jacobi: Functions and Variables for linearalgebra
eigenvalues: Functions and Variables for Matrices and Linear Algebra
eigenvectors: Functions and Variables for Matrices and Linear Algebra
eighth: Функции и переменные для работы со списками
einstein: Функции и переменные пакета ctensor
eivals: Functions and Variables for Matrices and Linear Algebra
eivects: Functions and Variables for Matrices and Linear Algebra
elapsed_real_time: Функции и переменные времени выполнения
elapsed_run_time: Функции и переменные времени выполнения
ele2comp: Functions and Variables for Symmetries
ele2polynome: Functions and Variables for Symmetries
ele2pui: Functions and Variables for Symmetries
elem: Functions and Variables for Symmetries
elementp: Функции и переменные для работы с множествами
elevation: Plotting Options
eliminate: Functions and Variables for Polynomials
ellipse: Функции и переменные пакета draw
elliptic_e: Функции и переменные для эллиптических интегралов
elliptic_ec: Функции и переменные для эллиптических интегралов
elliptic_eu: Функции и переменные для эллиптических интегралов
elliptic_f: Функции и переменные для эллиптических интегралов
elliptic_kc: Функции и переменные для эллиптических интегралов
elliptic_pi: Функции и переменные для эллиптических интегралов
ematrix: Functions and Variables for Matrices and Linear Algebra
emptyp: Функции и переменные для работы с множествами
empty_graph: Функции и переменные пакета graphs
endcons: Функции и переменные для работы со списками
enhanced3d: Функции и переменные пакета draw
entermatrix: Functions and Variables for Matrices and Linear Algebra
entertensor: Функции и переменные пакета itensor
entier: Общие операторы
epsilon_lp: Functions and Variables for simplex
eps_height: Функции и переменные пакета draw
eps_width: Функции и переменные пакета draw
equal: Общие операторы
equalp: Functions and Variables for Fourier series
equiv_classes: Функции и переменные для работы с множествами
erf: Error Function
erfc: Error Function
erfflag: Functions and Variables for Integration
erfi: Error Function
erf_generalized: Error Function
erf_representation: Error Function
errcatch: Функции и переменные для программирования на Maxima
error: Функции и переменные для программирования на Maxima
error: Функции и переменные для программирования на Maxima
errormsg: Функции и переменные для программирования на Maxima
error_size: Функции и переменные для ввода и вывода
error_syms: Функции и переменные для ввода и вывода
euler: Функции и переменные для теории чисел
ev: Функции и переменные для работы в командной строке
eval: Общие операторы
eval_string: String Processing
eval_string_lisp: Функции и переменные для работы в командной строке
evenfun: Functions and Variables for Simplification
evenp: Общие операторы
every: Функции и переменные для работы с множествами
every: Функции и переменные для работы с множествами
evflag: Функции и переменные для работы в командной строке
evfun: Функции и переменные для работы в командной строке
evolution: Функции и переменные пакета dynamics
evolution2d: Функции и переменные пакета dynamics
evundiff: Функции и переменные пакета itensor
ev_point: Functions and Variables for zeilberger
example: Справочная система
example: Справочная система
exp: Функции и переменные для выражений
expand: Functions and Variables for Simplification
expandwrt: Functions and Variables for Simplification
expandwrt_denom: Functions and Variables for Simplification
expandwrt_factored: Functions and Variables for Simplification
expintegral_chi: Exponential Integrals
expintegral_ci: Exponential Integrals
expintegral_e: Exponential Integrals
expintegral_e1: Exponential Integrals
expintegral_ei: Exponential Integrals
expintegral_li: Exponential Integrals
expintegral_shi: Exponential Integrals
expintegral_si: Exponential Integrals
expintexpand: Exponential Integrals
expintrep: Exponential Integrals
explicit: Функции и переменные пакета draw
explicit: Функции и переменные пакета draw
explose: Functions and Variables for Symmetries
expon: Functions and Variables for Simplification
exponentialize: Functions and Variables for Simplification
exponentialize: Functions and Variables for Simplification
expop: Functions and Variables for Simplification
express: Functions and Variables for Differentiation
expt: Функции и переменные для ввода и вывода
exptdispflag: Функции и переменные для ввода и вывода
exptisolate: Функции и переменные для выражений
exptsubst: Функции и переменные для выражений
exsec: Package functs
extdiff: Функции и переменные пакета itensor
extract_linear_equations: Функции и переменные пакета affine
extremal_subset: Функции и переменные для работы с множествами
extremal_subset: Функции и переменные для работы с множествами
ezgcd: Functions and Variables for Polynomials

F
f90: Функции и переменные пакета f90
facexpand: Functions and Variables for Polynomials
facsum: Package facexp
facsum_combine: Package facexp
factor: Functions and Variables for Polynomials
factorfacsum: Package facexp
factorflag: Functions and Variables for Polynomials
factorial: Функции и переменные для теории чисел
factorout: Functions and Variables for Polynomials
factorsum: Functions and Variables for Polynomials
factor_max_degree: Functions and Variables for Polynomials
factor_max_degree_print_warning: Functions and Variables for Polynomials
facts: Функции для работы с контекстами
facts: Функции для работы с контекстами
false: Математические константы
fasttimes: Functions and Variables for Polynomials
fast_central_elements: Функции и переменные пакета affine
fast_linsolve: Функции и переменные пакета affine
fb: Функции и переменные пакета ctensor
feature: Функции и переменные времени выполнения
featurep: Функции и переменные времени выполнения
features: Функции для работы с контекстами
fft: Functions and Variables for fast Fourier transform
fftpack5_fft: Functions and Variables for FFTPACK5
fftpack5_inverse_fft: Functions and Variables for FFTPACK5
fftpack5_inverse_real_fft: Functions and Variables for FFTPACK5
fftpack5_real_fft: Functions and Variables for FFTPACK5
fib: Функции и переменные для теории чисел
fibtophi: Функции и переменные для теории чисел
fifth: Функции и переменные для работы со списками
filename_merge: Функции и переменные для ввода и вывода
file_name: Функции и переменные пакета draw
file_output_append: Функции и переменные для ввода и вывода
file_search: Функции и переменные для ввода и вывода
file_search: Функции и переменные для ввода и вывода
file_search_demo: Функции и переменные для ввода и вывода
file_search_lisp: Функции и переменные для ввода и вывода
file_search_maxima: Функции и переменные для ввода и вывода
file_type: Функции и переменные для ввода и вывода
fillarray: Функции и переменные для работы с массивами
filled_func: Функции и переменные пакета draw
fill_color: Функции и переменные пакета draw
fill_density: Функции и переменные пакета draw
findde: Функции и переменные пакета ctensor
find_root: Functions for numerical solution of equations
find_root: Functions for numerical solution of equations
find_root_abs: Functions for numerical solution of equations
find_root_error: Functions for numerical solution of equations
find_root_rel: Functions for numerical solution of equations
first: Функции и переменные для работы со списками
fix: Общие операторы
flatten: Функции и переменные для работы с множествами
flength: String Input and Output
flipflag: Функции и переменные пакета itensor
floor: Общие операторы
flower_snark: Функции и переменные пакета graphs
flush: Функции и переменные пакета itensor
flush1deriv: Функции и переменные пакета itensor
flushd: Функции и переменные пакета itensor
flushnd: Функции и переменные пакета itensor
flush_output: String Input and Output
for: Функции и переменные для программирования на Maxima
forget: Функции для работы с контекстами
forget: Функции для работы с контекстами
fourcos: Functions and Variables for Fourier series
fourexpand: Functions and Variables for Fourier series
fourier: Functions and Variables for Fourier series
fourint: Functions and Variables for Fourier series
fourintcos: Functions and Variables for Fourier series
fourintsin: Functions and Variables for Fourier series
foursimp: Functions and Variables for Fourier series
foursin: Functions and Variables for Fourier series
fourth: Функции и переменные для работы со списками
fposition: String Input and Output
frame_bracket: Функции и переменные пакета ctensor
freeof: Функции и переменные для выражений
freshline: String Input and Output
fresnel_c: Error Function
fresnel_s: Error Function
from_adjacency_matrix: Функции и переменные пакета graphs
frucht_graph: Функции и переменные пакета graphs
fullmap: Общие операторы
fullmapl: Общие операторы
fullratsimp: Functions and Variables for Polynomials
fullratsubst: Functions and Variables for Polynomials
fullratsubstflag: Functions and Variables for Polynomials
fullsetify: Функции и переменные для работы с множествами
full_listify: Функции и переменные для работы с множествами
funcsolve: Functions and Variables for Equations
functions: Функции и переменные для определения функций
fundef: Функции и переменные для определения функций
funmake: Функции и переменные для определения функций
funp: Functions and Variables for Fourier series

G
gamma: Gamma and Factorial Functions
gammalim: Gamma and Factorial Functions
gamma_expand: Gamma and Factorial Functions
gamma_incomplete: Gamma and Factorial Functions
gamma_incomplete_generalized: Gamma and Factorial Functions
gamma_incomplete_lower: Gamma and Factorial Functions
gamma_incomplete_regularized: Gamma and Factorial Functions
gaussprob: Package functs
gauss_a: Функции и переменные пакета contrib_ode
gauss_b: Функции и переменные пакета contrib_ode
gcd: Functions and Variables for Polynomials
gcdex: Functions and Variables for Polynomials
gcdivide: Package functs
gcfac: Package scifac
gcfactor: Functions and Variables for Polynomials
gd: Package functs
gdet: Функции и переменные пакета ctensor
generalized_lambert_w: Functions and Variables for Special Functions
genfact: Функции и переменные для выражений
genindex: Вспомогательные функции и переменные
genmatrix: Functions and Variables for Matrices and Linear Algebra
gensumnum: Вспомогательные функции и переменные
gen_laguerre: Functions and Variables for orthogonal polynomials
geomap: Функции и переменные пакета draw
geomap: Функции и переменные пакета draw
geometric: Package functs
geometric_mean: Функции и переменные для описательной статистики
geometric_mean: Функции и переменные для описательной статистики
geomview_command: Functions and Variables for Plotting
geosum: Package functs
get: Функции и переменные для работы со списками
get_edge_weight: Функции и переменные пакета graphs
get_edge_weight: Функции и переменные пакета graphs
get_lu_factors: Functions and Variables for linearalgebra
get_output_stream_string: String Input and Output
get_pixel: Функции и переменные для картин
get_plot_option: Functions and Variables for Plotting
get_vertex_label: Функции и переменные пакета graphs
gfactor: Functions and Variables for Polynomials
gfactorsum: Functions and Variables for Polynomials
ggf: Functions and Variables for ggf
GGFCFMAX: Functions and Variables for ggf
GGFINFINITY: Functions and Variables for ggf
girth: Функции и переменные пакета graphs
globalsolve: Functions and Variables for Equations
global_variances: Функции и переменные для многомерной описательной статистики
global_variances: Функции и переменные для многомерной описательной статистики
gnuplot_close: Gnuplot_pipes Format Functions
gnuplot_command: Functions and Variables for Plotting
gnuplot_curve_styles: Gnuplot Options
gnuplot_curve_titles: Gnuplot Options
gnuplot_default_term_command: Gnuplot Options
gnuplot_dumb_term_command: Gnuplot Options
gnuplot_file_args: Functions and Variables for Plotting
gnuplot_out_file: Gnuplot Options
gnuplot_pdf_term_command: Gnuplot Options
gnuplot_pm3d: Gnuplot Options
gnuplot_png_term_command: Gnuplot Options
gnuplot_postamble: Gnuplot Options
gnuplot_preamble: Gnuplot Options
gnuplot_ps_term_command: Gnuplot Options
gnuplot_replot: Gnuplot_pipes Format Functions
gnuplot_reset: Gnuplot_pipes Format Functions
gnuplot_restart: Gnuplot_pipes Format Functions
gnuplot_script_file: Gnuplot Options
gnuplot_send: Gnuplot_pipes Format Functions
gnuplot_start: Gnuplot_pipes Format Functions
gnuplot_strings: Gnuplot Options
gnuplot_svg_background: Gnuplot Options
gnuplot_svg_term_command: Gnuplot Options
gnuplot_term: Gnuplot Options
gnuplot_view_args: Functions and Variables for Plotting
go: Функции и переменные для программирования на Maxima
Gosper: Functions and Variables for zeilberger
GosperSum: Functions and Variables for zeilberger
Gosper_in_Zeilberger: Functions and Variables for zeilberger
gr2d: Функции и переменные пакета draw
gr3d: Функции и переменные пакета draw
gradef: Functions and Variables for Differentiation
gradefs: Functions and Variables for Differentiation
gramschmidt: Functions and Variables for Matrices and Linear Algebra
graph6_decode: Функции и переменные пакета graphs
graph6_encode: Функции и переменные пакета graphs
graph6_export: Функции и переменные пакета graphs
graph6_import: Функции и переменные пакета graphs
graph_center: Функции и переменные пакета graphs
graph_charpoly: Функции и переменные пакета graphs
graph_eigenvalues: Функции и переменные пакета graphs
graph_order: Функции и переменные пакета graphs
graph_periphery: Функции и переменные пакета graphs
graph_product: Функции и переменные пакета graphs
graph_size: Функции и переменные пакета graphs
graph_union: Функции и переменные пакета graphs
grid: Plotting Options
grid: Функции и переменные пакета draw
grid2d: Plotting Options
grid_graph: Функции и переменные пакета graphs
grind: Функции и переменные для ввода и вывода
grind: Функции и переменные для ввода и вывода
grobner_basis: Функции и переменные пакета affine
grotzch_graph: Функции и переменные пакета graphs

H
halfangles: Функции и переменные для тригонометрии
hamilton_cycle: Функции и переменные пакета graphs
hamilton_path: Функции и переменные пакета graphs
hankel: Functions and Variables for linearalgebra
hankel_1: Bessel Functions
hankel_2: Bessel Functions
harmonic: Package functs
harmonic_mean: Функции и переменные для описательной статистики
harmonic_mean: Функции и переменные для описательной статистики
harmonic_number: Functions and Variables for solve_rec
harmonic_to_psi: Functions and Variables for solve_rec
hav: Package functs
head_angle: Функции и переменные пакета draw
head_both: Функции и переменные пакета draw
head_length: Функции и переменные пакета draw
head_type: Функции и переменные пакета draw
heawood_graph: Функции и переменные пакета graphs
hermite: Functions and Variables for orthogonal polynomials
hessian: Functions and Variables for linearalgebra
hgfred: Hypergeometric Functions
hilbert_matrix: Functions and Variables for linearalgebra
hipow: Functions and Variables for Polynomials
histogram: Функции и переменные для статистических графиков
histogram: Функции и переменные для статистических графиков
histogram: Функции и переменные для статистических графиков
histogram: Функции и переменные для статистических графиков
histogram: Функции и переменные для статистических графиков
histogram: Функции и переменные для статистических графиков
hodge: Функции и переменные пакета itensor
horner: Functions for numerical solution of equations
hypergeometric: Hypergeometric Functions
hypergeometric_representation: Error Function
hypergeometric_simp: Hypergeometric Functions

I
ibase: Функции и переменные для ввода и вывода
ic1: Функции и переменные для дифференциальных уравнений
ic2: Функции и переменные для дифференциальных уравнений
icc1: Функции и переменные пакета itensor
icc2: Функции и переменные пакета itensor
ichr1: Функции и переменные пакета itensor
ichr2: Функции и переменные пакета itensor
icosahedron_graph: Функции и переменные пакета graphs
icounter: Функции и переменные пакета itensor
icurvature: Функции и переменные пакета itensor
ic_convert: Функции и переменные пакета itensor
ident: Functions and Variables for Matrices and Linear Algebra
identfor: Functions and Variables for linearalgebra
identity: Функции и переменные для работы с множествами
idiff: Функции и переменные пакета itensor
idummy: Функции и переменные пакета itensor
idummyx: Функции и переменные пакета itensor
ieqn: Functions and Variables for Equations
ieqnprint: Functions and Variables for Equations
if: Функции и переменные для программирования на Maxima
ifactors: Функции и переменные для теории чисел
ifb: Функции и переменные пакета itensor
ifc1: Функции и переменные пакета itensor
ifc2: Функции и переменные пакета itensor
ifg: Функции и переменные пакета itensor
ifgi: Функции и переменные пакета itensor
ifr: Функции и переменные пакета itensor
iframes: Функции и переменные пакета itensor
iframe_bracket_form: Функции и переменные пакета itensor
ifri: Функции и переменные пакета itensor
ifs: Функции и переменные пакета dynamics
igeodesic_coords: Функции и переменные пакета itensor
igeowedge_flag: Функции и переменные пакета itensor
ikt1: Функции и переменные пакета itensor
ikt2: Функции и переменные пакета itensor
ilt: Functions and Variables for Integration
image: Функции и переменные пакета draw
imagpart: Функции и переменные для выражений
imetric: Функции и переменные пакета itensor
imetric: Функции и переменные пакета itensor
implicit: Функции и переменные пакета draw
implicit: Функции и переменные пакета draw
implicit_derivative: Функции и переменные пакета impdiff
implicit_plot: Функции и переменные пакета implicit_plot
implicit_plot: Функции и переменные пакета implicit_plot
inchar: Функции и переменные для ввода и вывода
ind: Математические константы
indexed_tensor: Функции и переменные пакета itensor
indices: Функции и переменные пакета itensor
induced_subgraph: Функции и переменные пакета graphs
inf: Математические константы
inferencep: Functions and Variables for inference_result
inference_result: Functions and Variables for inference_result
infeval: Функции и переменные для работы в командной строке
infinity: Математические константы
infix: Функции и переменные для выражений
infix: Функции и переменные для выражений
infix: Функции и переменные для выражений
inflag: Функции и переменные для выражений
infolists: Вспомогательные функции и переменные
init_atensor: Функции и переменные пакета atensor
init_atensor: Функции и переменные пакета atensor
init_cartan: Functions and Variables for Differentiation
init_ctensor: Функции и переменные пакета ctensor
inm: Функции и переменные пакета itensor
inmc1: Функции и переменные пакета itensor
inmc2: Функции и переменные пакета itensor
innerproduct: Functions and Variables for Matrices and Linear Algebra
inpart: Функции и переменные для выражений
inprod: Functions and Variables for Matrices and Linear Algebra
inrt: Функции и переменные для теории чисел
intanalysis: Functions and Variables for Integration
integerp: Вспомогательные функции и переменные
integer_partitions: Функции и переменные для работы с множествами
integer_partitions: Функции и переменные для работы с множествами
integrate: Functions and Variables for Integration
integrate_use_rootsof: Functions and Variables for Integration
integration_constant: Functions and Variables for Integration
integration_constant_counter: Functions and Variables for Integration
intersect: Функции и переменные для работы с множествами
intersection: Функции и переменные для работы с множествами
intervalp: Functions and Variables for orthogonal polynomials
intfaclim: Functions and Variables for Polynomials
intopois: Functions and Variables for Poisson series
intosum: Functions and Variables for Sums and Products
invariant1: Функции и переменные пакета ctensor
invariant2: Функции и переменные пакета ctensor
inverse_fft: Functions and Variables for fast Fourier transform
inverse_jacobi_cd: Функции и переменные для эллиптических функций
inverse_jacobi_cn: Функции и переменные для эллиптических функций
inverse_jacobi_cs: Функции и переменные для эллиптических функций
inverse_jacobi_dc: Функции и переменные для эллиптических функций
inverse_jacobi_dn: Функции и переменные для эллиптических функций
inverse_jacobi_ds: Функции и переменные для эллиптических функций
inverse_jacobi_nc: Функции и переменные для эллиптических функций
inverse_jacobi_nd: Функции и переменные для эллиптических функций
inverse_jacobi_ns: Функции и переменные для эллиптических функций
inverse_jacobi_sc: Функции и переменные для эллиптических функций
inverse_jacobi_sd: Функции и переменные для эллиптических функций
inverse_jacobi_sn: Функции и переменные для эллиптических функций
inverse_real_fft: Functions and Variables for fast Fourier transform
invert: Functions and Variables for Matrices and Linear Algebra
invert_by_adjoint: Functions and Variables for Matrices and Linear Algebra
invert_by_lu: Functions and Variables for linearalgebra
inv_mod: Функции и переменные для теории чисел
in_neighbors: Функции и переменные пакета graphs
ip_grid: Функции и переменные пакета draw
ip_grid_in: Функции и переменные пакета draw
is: Общие операторы
ishow: Функции и переменные пакета itensor
isolate: Функции и переменные для выражений
isolate_wrt_times: Функции и переменные для выражений
isomorphism: Функции и переменные пакета graphs
isqrt: Общие операторы
is_biconnected: Функции и переменные пакета graphs
is_bipartite: Функции и переменные пакета graphs
is_connected: Функции и переменные пакета graphs
is_digraph: Функции и переменные пакета graphs
is_edge_in_graph: Функции и переменные пакета graphs
is_graph: Функции и переменные пакета graphs
is_graph_or_digraph: Функции и переменные пакета graphs
is_isomorphic: Функции и переменные пакета graphs
is_planar: Функции и переменные пакета graphs
is_sconnected: Функции и переменные пакета graphs
is_tree: Функции и переменные пакета graphs
is_vertex_in_graph: Функции и переменные пакета graphs
items_inference: Functions and Variables for inference_result
iterations: Plotting Options
itr: Функции и переменные пакета itensor

J
jacobi: Функции и переменные для теории чисел
jacobian: Functions and Variables for linearalgebra
jacobi_cd: Функции и переменные для эллиптических функций
jacobi_cn: Функции и переменные для эллиптических функций
jacobi_cs: Функции и переменные для эллиптических функций
jacobi_dc: Функции и переменные для эллиптических функций
jacobi_dn: Функции и переменные для эллиптических функций
jacobi_ds: Функции и переменные для эллиптических функций
jacobi_nc: Функции и переменные для эллиптических функций
jacobi_nd: Функции и переменные для эллиптических функций
jacobi_ns: Функции и переменные для эллиптических функций
jacobi_p: Functions and Variables for orthogonal polynomials
jacobi_sc: Функции и переменные для эллиптических функций
jacobi_sd: Функции и переменные для эллиптических функций
jacobi_sn: Функции и переменные для эллиптических функций
JF: Функции и переменные пакета diag
join: Функции и переменные для работы со списками
jordan: Функции и переменные пакета diag
julia: Functions and Variables for Plotting
julia: Функции и переменные пакета dynamics

K
kbateman: Functions and Variables for Special Functions
kdels: Функции и переменные пакета itensor
kdelta: Функции и переменные пакета itensor
keepfloat: Functions and Variables for Polynomials
key: Функции и переменные пакета draw
kill: Функции и переменные для работы в командной строке
kill: Функции и переменные для работы в командной строке
kill: Функции и переменные для работы в командной строке
kill: Функции и переменные для работы в командной строке
kill: Функции и переменные для работы в командной строке
kill: Функции и переменные для работы в командной строке
kill: Функции и переменные для работы в командной строке
kill: Функции и переменные для работы в командной строке
killcontext: Функции для работы с контекстами
kinvariant: Функции и переменные пакета ctensor
kostka: Functions and Variables for Symmetries
kronecker_product: Functions and Variables for linearalgebra
kron_delta: Функции и переменные для работы с множествами
kt: Функции и переменные пакета ctensor
kummer_m: Функции и переменные пакета contrib_ode
kummer_u: Функции и переменные пакета contrib_ode
kurtosis: Функции и переменные для описательной статистики
kurtosis: Функции и переменные для описательной статистики
kurtosis_bernoulli: Функции и переменные для дискретных распределений
kurtosis_beta: Функции и переменные для непрерывных распределений
kurtosis_binomial: Функции и переменные для дискретных распределений
kurtosis_chi2: Функции и переменные для непрерывных распределений
kurtosis_continuous_uniform: Функции и переменные для непрерывных распределений
kurtosis_discrete_uniform: Функции и переменные для дискретных распределений
kurtosis_exp: Функции и переменные для непрерывных распределений
kurtosis_f: Функции и переменные для непрерывных распределений
kurtosis_gamma: Функции и переменные для непрерывных распределений
kurtosis_geometric: Функции и переменные для дискретных распределений
kurtosis_gumbel: Функции и переменные для непрерывных распределений
kurtosis_hypergeometric: Функции и переменные для дискретных распределений
kurtosis_laplace: Функции и переменные для непрерывных распределений
kurtosis_logistic: Функции и переменные для непрерывных распределений
kurtosis_lognormal: Функции и переменные для непрерывных распределений
kurtosis_negative_binomial: Функции и переменные для дискретных распределений
kurtosis_normal: Функции и переменные для непрерывных распределений
kurtosis_pareto: Функции и переменные для непрерывных распределений
kurtosis_poisson: Функции и переменные для дискретных распределений
kurtosis_rayleigh: Функции и переменные для непрерывных распределений
kurtosis_student_t: Функции и переменные для непрерывных распределений
kurtosis_weibull: Функции и переменные для непрерывных распределений

L
label: Plotting Options
label: Функции и переменные пакета draw
label: Функции и переменные пакета draw
labels: Функции и переменные для работы в командной строке
labels: Функции и переменные для работы в командной строке
label_alignment: Функции и переменные пакета draw
label_orientation: Функции и переменные пакета draw
lagrange: Функции и переменные пакета interpol
lagrange: Функции и переменные пакета interpol
laguerre: Functions and Variables for orthogonal polynomials
lambda: Функции и переменные для определения функций
lambda: Функции и переменные для определения функций
lambda: Функции и переменные для определения функций
lambert_w: Functions and Variables for Special Functions
laplace: Functions and Variables for Integration
laplacian_matrix: Функции и переменные пакета graphs
lassociative: Functions and Variables for Simplification
last: Функции и переменные для работы со списками
lbfgs: Functions and Variables for lbfgs
lbfgs_ncorrections: Functions and Variables for lbfgs
lbfgs_nfeval_max: Functions and Variables for lbfgs
lc2kdt: Функции и переменные пакета itensor
lcm: Функции и переменные для теории чисел
lc_l: Функции и переменные пакета itensor
lc_u: Функции и переменные пакета itensor
ldefint: Functions and Variables for Integration
ldisp: Функции и переменные для ввода и вывода
ldisplay: Функции и переменные для ввода и вывода
legend: Plotting Options
legendre_p: Functions and Variables for orthogonal polynomials
legendre_q: Functions and Variables for orthogonal polynomials
leinstein: Функции и переменные пакета ctensor
length: Функции и переменные для работы со списками
let: Функции и переменные для правил преобразования и шаблонов
let: Функции и переменные для правил преобразования и шаблонов
letrat: Функции и переменные для правил преобразования и шаблонов
letrules: Функции и переменные для правил преобразования и шаблонов
letrules: Функции и переменные для правил преобразования и шаблонов
letsimp: Функции и переменные для правил преобразования и шаблонов
letsimp: Функции и переменные для правил преобразования и шаблонов
letsimp: Функции и переменные для правил преобразования и шаблонов
let_rule_packages: Функции и переменные для правил преобразования и шаблонов
levels: Plotting Options
levi_civita: Функции и переменные пакета itensor
lfg: Функции и переменные пакета ctensor
lfreeof: Функции и переменные для выражений
lg: Функции и переменные пакета ctensor
lgtreillis: Functions and Variables for Symmetries
lhospitallim: Функции для работы с пределами
lhs: Functions and Variables for Equations
liediff: Функции и переменные пакета itensor
limit: Функции для работы с пределами
limit: Функции для работы с пределами
limit: Функции для работы с пределами
limsubst: Функции для работы с пределами
linalg_rank: Functions and Variables for linearalgebra
Lindstedt: Functions and Variables for lindstedt
linear: Functions and Variables for Simplification
linear: Package functs
linearinterpol: Функции и переменные пакета interpol
linearinterpol: Функции и переменные пакета interpol
linear_program: Functions and Variables for simplex
linear_regression: Functions and Variables for stats
linear_solver: Functions and Variables for zeilberger
linechar: Функции и переменные для ввода и вывода
linel: Функции и переменные для ввода и вывода
linenum: Функции и переменные для работы в командной строке
line_graph: Функции и переменные пакета graphs
line_type: Функции и переменные пакета draw
line_width: Функции и переменные пакета draw
linsolve: Functions and Variables for Equations
linsolvewarn: Functions and Variables for Equations
linsolve_params: Functions and Variables for Equations
lispdisp: Функции и переменные для ввода и вывода
listarith: Функции и переменные для работы со списками
listarray: Функции и переменные для работы с массивами
listconstvars: Функции и переменные для выражений
listdummyvars: Функции и переменные для выражений
listify: Функции и переменные для работы с множествами
listoftens: Функции и переменные пакета itensor
listofvars: Функции и переменные для выражений
listp: Функции и переменные для работы со списками
listp: Functions and Variables for linearalgebra
list_correlations: Функции и переменные для многомерной описательной статистики
list_correlations: Функции и переменные для многомерной описательной статистики
list_matrix_entries: Functions and Variables for Matrices and Linear Algebra
list_nc_monomials: Функции и переменные пакета affine
list_nc_monomials: Функции и переменные пакета affine
lmax: Общие операторы
lmin: Общие операторы
lmxchar: Functions and Variables for Matrices and Linear Algebra
load: Функции и переменные для ввода и вывода
loadfile: Функции и переменные для ввода и вывода
loadprint: Функции и переменные для ввода и вывода
local: Функции и переменные для определения функций
locate_matrix_entry: Functions and Variables for linearalgebra
logx: Plotting Options
logx: Функции и переменные пакета draw
logy: Plotting Options
logy: Функции и переменные пакета draw
logz: Функции и переменные пакета draw
log_gamma: Gamma and Factorial Functions
lopow: Функции и переменные для выражений
lopow: Functions and Variables for Polynomials
lorentz_gauge: Функции и переменные пакета itensor
lowercasep: Characters
lpart: Функции и переменные для выражений
lratsubst: Functions and Variables for Polynomials
lrats_max_iter: Functions and Variables for Polynomials
lreduce: Функции и переменные для работы с множествами
lreduce: Функции и переменные для работы с множествами
lriem: Функции и переменные пакета ctensor
lriemann: Функции и переменные пакета ctensor
lsquares_estimates: Functions and Variables for lsquares
lsquares_estimates_approximate: Functions and Variables for lsquares
lsquares_estimates_exact: Functions and Variables for lsquares
lsquares_mse: Functions and Variables for lsquares
lsquares_residuals: Functions and Variables for lsquares
lsquares_residual_mse: Functions and Variables for lsquares
lsum: Функции и переменные для выражений
lsum: Functions and Variables for Sums and Products
ltreillis: Functions and Variables for Symmetries
lu_backsub: Functions and Variables for linearalgebra
lu_factor: Functions and Variables for linearalgebra

M
m1pbranch: Вспомогательные функции и переменные
macroexpand: Макросы
macroexpand1: Макросы
macroexpansion: Функции и переменные для определения функций
macros: Макросы
makebox: Функции и переменные пакета itensor
makefact: Gamma and Factorial Functions
makegamma: Gamma and Factorial Functions
makelist: Функции и переменные для работы со списками
makelist: Функции и переменные для работы со списками
makeOrders: Functions and Variables for makeOrders
makeset: Функции и переменные для работы с множествами
make_array: Функции и переменные для работы с массивами
make_graph: Функции и переменные пакета graphs
make_graph: Функции и переменные пакета graphs
make_level_picture: Функции и переменные для картин
make_level_picture: Функции и переменные для картин
make_polygon: Функции и переменные для карты мира
make_poly_continent: Функции и переменные для карты мира
make_poly_continent: Функции и переменные для карты мира
make_poly_country: Функции и переменные для карты мира
make_random_state: Общие операторы
make_random_state: Общие операторы
make_random_state: Общие операторы
make_random_state: Общие операторы
make_rgb_picture: Функции и переменные для картин
make_string_input_stream: String Input and Output
make_string_output_stream: String Input and Output
make_transform: Functions and Variables for Plotting
mandelbrot: Functions and Variables for Plotting
mandelbrot: Функции и переменные пакета dynamics
map: Функции и переменные для программирования на Maxima
mapatom: Функции и переменные для программирования на Maxima
maperror: Функции и переменные для программирования на Maxima
maplist: Функции и переменные для программирования на Maxima
mapprint: Функции и переменные для программирования на Maxima
matchdeclare: Функции и переменные для правил преобразования и шаблонов
matchfix: Функции и переменные для правил преобразования и шаблонов
matchfix: Функции и переменные для правил преобразования и шаблонов
matrix: Functions and Variables for Matrices and Linear Algebra
matrixexp: Functions and Variables for Matrices and Linear Algebra
matrixmap: Functions and Variables for Matrices and Linear Algebra
matrixp: Functions and Variables for Matrices and Linear Algebra
matrixp: Functions and Variables for linearalgebra
matrix_element_add: Functions and Variables for Matrices and Linear Algebra
matrix_element_mult: Functions and Variables for Matrices and Linear Algebra
matrix_element_transpose: Functions and Variables for Matrices and Linear Algebra
matrix_size: Functions and Variables for linearalgebra
mattrace: Functions and Variables for Matrices and Linear Algebra
mat_cond: Functions and Variables for linearalgebra
mat_fullunblocker: Functions and Variables for linearalgebra
mat_function: Функции и переменные пакета diag
mat_norm: Functions and Variables for linearalgebra
mat_trace: Functions and Variables for linearalgebra
mat_unblocker: Functions and Variables for linearalgebra
max: Общие операторы
maxi: Функции и переменные для описательной статистики
maxi: Функции и переменные для описательной статистики
maxima_tempdir: Функции и переменные времени выполнения
maxima_userdir: Функции и переменные времени выполнения
maximize_lp: Functions and Variables for simplex
maxnegex: Functions and Variables for Simplification
maxposex: Functions and Variables for Simplification
maxpsifracdenom: Gamma and Factorial Functions
maxpsifracnum: Gamma and Factorial Functions
maxpsinegint: Gamma and Factorial Functions
maxpsiposint: Gamma and Factorial Functions
maxtayorder: Functions and Variables for Series
max_clique: Функции и переменные пакета graphs
max_degree: Функции и переменные пакета graphs
max_flow: Функции и переменные пакета graphs
max_independent_set: Функции и переменные пакета graphs
max_matching: Функции и переменные пакета graphs
MAX_ORD: Functions and Variables for zeilberger
maybe: Общие операторы
md5sum: Octets and Utilities for Cryptography
mean: Функции и переменные для описательной статистики
mean: Функции и переменные для описательной статистики
mean_bernoulli: Функции и переменные для дискретных распределений
mean_beta: Функции и переменные для непрерывных распределений
mean_binomial: Функции и переменные для дискретных распределений
mean_chi2: Функции и переменные для непрерывных распределений
mean_continuous_uniform: Функции и переменные для непрерывных распределений
mean_deviation: Функции и переменные для описательной статистики
mean_deviation: Функции и переменные для описательной статистики
mean_discrete_uniform: Функции и переменные для дискретных распределений
mean_exp: Функции и переменные для непрерывных распределений
mean_f: Функции и переменные для непрерывных распределений
mean_gamma: Функции и переменные для непрерывных распределений
mean_geometric: Функции и переменные для дискретных распределений
mean_gumbel: Функции и переменные для непрерывных распределений
mean_hypergeometric: Функции и переменные для дискретных распределений
mean_laplace: Функции и переменные для непрерывных распределений
mean_logistic: Функции и переменные для непрерывных распределений
mean_lognormal: Функции и переменные для непрерывных распределений
mean_negative_binomial: Функции и переменные для дискретных распределений
mean_normal: Функции и переменные для непрерывных распределений
mean_pareto: Функции и переменные для непрерывных распределений
mean_poisson: Функции и переменные для дискретных распределений
mean_rayleigh: Функции и переменные для непрерывных распределений
mean_student_t: Функции и переменные для непрерывных распределений
mean_weibull: Функции и переменные для непрерывных распределений
median: Функции и переменные для описательной статистики
median: Функции и переменные для описательной статистики
median_deviation: Функции и переменные для описательной статистики
median_deviation: Функции и переменные для описательной статистики
member: Функции и переменные для работы со списками
mesh_lines_color: Plotting Options
method: Функции и переменные пакета contrib_ode
metricexpandall: Functions and Variables for Units
mgf1_sha1: Octets and Utilities for Cryptography
min: Общие операторы
minf: Математические константы
minfactorial: Функции и переменные для теории чисел
mini: Функции и переменные для описательной статистики
mini: Функции и переменные для описательной статистики
minimalPoly: Функции и переменные пакета diag
minimize_lp: Functions and Variables for simplex
minimum_spanning_tree: Функции и переменные пакета graphs
minor: Functions and Variables for Matrices and Linear Algebra
min_degree: Функции и переменные пакета graphs
min_vertex_cover: Функции и переменные пакета graphs
mnewton: Functions and Variables for mnewton
mod: Общие операторы
ModeMatrix: Функции и переменные пакета diag
mode_checkp: Функции и переменные для определения функций
mode_check_errorp: Функции и переменные для определения функций
mode_check_warnp: Функции и переменные для определения функций
mode_declare: Функции и переменные для определения функций
mode_identity: Функции и переменные для определения функций
modular_linear_solver: Functions and Variables for zeilberger
modulus: Functions and Variables for Polynomials
mod_big_prime: Functions and Variables for zeilberger
mod_test: Functions and Variables for zeilberger
mod_threshold: Functions and Variables for zeilberger
moebius: Функции и переменные для работы с множествами
mon2schur: Functions and Variables for Symmetries
mono: Функции и переменные пакета affine
monomial_dimensions: Функции и переменные пакета affine
multinomial: Functions and Variables for Symmetries
multinomial_coeff: Функции и переменные для работы с множествами
multinomial_coeff: Функции и переменные для работы с множествами
multiplicative: Functions and Variables for Simplification
multiplicities: Functions and Variables for Equations
multi_elem: Functions and Variables for Symmetries
multi_orbit: Functions and Variables for Symmetries
multi_pui: Functions and Variables for Symmetries
multsym: Functions and Variables for Symmetries
multthru: Функции и переменные для выражений
multthru: Функции и переменные для выражений
multthru: Functions and Variables for Simplification
mycielski_graph: Функции и переменные пакета graphs
myoptions: Функции и переменные для работы в командной строке

N
nary: Functions and Variables for Simplification
ncharpoly: Functions and Variables for Matrices and Linear Algebra
nc_degree: Функции и переменные пакета affine
negative_picture: Функции и переменные для картин
negdistrib: Functions and Variables for Simplification
neighbors: Функции и переменные пакета graphs
newcontext: Функции для работы с контекстами
newdet: Functions and Variables for Matrices and Linear Algebra
newline: Characters
newline: String Input and Output
newton: Functions for numerical solution of equations
newtondebug: Functions and Variables for mnewton
newtonepsilon: Functions and Variables for mnewton
newtonmaxiter: Functions and Variables for mnewton
new_graph: Функции и переменные пакета graphs
nextlayerfactor: Package facexp
next_prime: Функции и переменные для теории чисел
niceindices: Functions and Variables for Series
niceindicespref: Functions and Variables for Series
ninth: Функции и переменные для работы со списками
nm: Функции и переменные пакета ctensor
nmc: Функции и переменные пакета ctensor
nolabels: Функции и переменные для работы в командной строке
noncentral_moment: Функции и переменные для описательной статистики
noncentral_moment: Функции и переменные для описательной статистики
nonegative_lp: Functions and Variables for simplex
nonmetricity: Функции и переменные пакета ctensor
nonnegative_lp: Functions and Variables for simplex
nonzeroandfreeof: Package functs
not: Общие операторы
notequal: Общие операторы
nounify: Функции и переменные для выражений
np: Функции и переменные пакета ctensor
npi: Функции и переменные пакета ctensor
nptetrad: Функции и переменные пакета ctensor
nroots: Functions and Variables for Equations
nterms: Функции и переменные для выражений
ntermst: Функции и переменные пакета ctensor
nthroot: Functions and Variables for Equations
nticks: Plotting Options
nticks: Функции и переменные пакета draw
ntrig: Функции и переменные для тригонометрии
nullity: Functions and Variables for linearalgebra
nullspace: Functions and Variables for linearalgebra
num: Functions and Variables for Polynomials
numbered_boundaries: Функции и переменные для карты мира
numberp: Вспомогательные функции и переменные
number_to_octets: Octets and Utilities for Cryptography
numfactor: Gamma and Factorial Functions
num_distinct_partitions: Функции и переменные для работы с множествами
num_distinct_partitions: Функции и переменные для работы с множествами
num_partitions: Функции и переменные для работы с множествами
num_partitions: Функции и переменные для работы с множествами
nusum: Functions and Variables for Series
nzeta: Functions and Variables for Special Functions
nzetai: Functions and Variables for Special Functions
nzetar: Functions and Variables for Special Functions

O
obase: Функции и переменные для ввода и вывода
octets_to_number: Octets and Utilities for Cryptography
octets_to_oid: Octets and Utilities for Cryptography
octets_to_string: Octets and Utilities for Cryptography
oddfun: Functions and Variables for Simplification
oddp: Общие операторы
odd_girth: Функции и переменные пакета graphs
ode2: Функции и переменные для дифференциальных уравнений
odelin: Функции и переменные пакета contrib_ode
ode_check: Функции и переменные пакета contrib_ode
oid_to_octets: Octets and Utilities for Cryptography
op: Функции и переменные для выражений
opena: String Input and Output
opena_binary: Functions and Variables for binary input and output
openr: String Input and Output
openr_binary: Functions and Variables for binary input and output
openw: String Input and Output
openw_binary: Functions and Variables for binary input and output
operatorp: Функции и переменные для выражений
operatorp: Функции и переменные для выражений
opproperties: Functions and Variables for Simplification
opsubst: Functions and Variables for opsubst
optimize: Функции и переменные для выражений
optimprefix: Функции и переменные для выражений
optionset: Функции и переменные для работы в командной строке
or: Общие операторы
orbit: Functions and Variables for Symmetries
orbits: Функции и переменные пакета dynamics
ordergreat: Функции и переменные для выражений
ordergreatp: Функции и переменные для выражений
orderless: Функции и переменные для выражений
orderlessp: Функции и переменные для выражений
orthogonal_complement: Functions and Variables for linearalgebra
orthopoly_recur: Functions and Variables for orthogonal polynomials
orthopoly_returns_intervals: Functions and Variables for orthogonal polynomials
orthopoly_weight: Functions and Variables for orthogonal polynomials
outative: Functions and Variables for Simplification
outchar: Функции и переменные для ввода и вывода
outermap: Функции и переменные для программирования на Maxima
outofpois: Functions and Variables for Poisson series
out_neighbors: Функции и переменные пакета graphs

P
packagefile: Функции и переменные для ввода и вывода
pade: Functions and Variables for Series
palette: Plotting Options
palette: Функции и переменные пакета draw
parabolic_cylinder_d: Parabolic Cylinder Functions
parametric: Функции и переменные пакета draw
parametric: Функции и переменные пакета draw
parametric_surface: Функции и переменные пакета draw
parGosper: Functions and Variables for zeilberger
parse_string: String Processing
part: Функции и переменные для выражений
part2cont: Functions and Variables for Symmetries
partfrac: Функции и переменные для теории чисел
partition: Функции и переменные для выражений
partition_set: Функции и переменные для работы с множествами
partpol: Functions and Variables for Symmetries
partswitch: Функции и переменные для выражений
path_digraph: Функции и переменные пакета graphs
path_graph: Функции и переменные пакета graphs
pdf_bernoulli: Функции и переменные для дискретных распределений
pdf_beta: Функции и переменные для непрерывных распределений
pdf_binomial: Функции и переменные для дискретных распределений
pdf_cauchy: Функции и переменные для непрерывных распределений
pdf_chi2: Функции и переменные для непрерывных распределений
pdf_continuous_uniform: Функции и переменные для непрерывных распределений
pdf_discrete_uniform: Функции и переменные для дискретных распределений
pdf_exp: Функции и переменные для непрерывных распределений
pdf_f: Функции и переменные для непрерывных распределений
pdf_file: Plotting Options
pdf_gamma: Функции и переменные для непрерывных распределений
pdf_geometric: Функции и переменные для дискретных распределений
pdf_gumbel: Функции и переменные для непрерывных распределений
pdf_hypergeometric: Функции и переменные для дискретных распределений
pdf_laplace: Функции и переменные для непрерывных распределений
pdf_logistic: Функции и переменные для непрерывных распределений
pdf_lognormal: Функции и переменные для непрерывных распределений
pdf_negative_binomial: Функции и переменные для дискретных распределений
pdf_normal: Функции и переменные для непрерывных распределений
pdf_pareto: Функции и переменные для непрерывных распределений
pdf_poisson: Функции и переменные для дискретных распределений
pdf_rank_sum: Functions and Variables for special distributions
pdf_rayleigh: Функции и переменные для непрерывных распределений
pdf_signed_rank: Functions and Variables for special distributions
pdf_student_t: Функции и переменные для непрерывных распределений
pdf_weibull: Функции и переменные для непрерывных распределений
pearson_skewness: Функции и переменные для описательной статистики
pearson_skewness: Функции и переменные для описательной статистики
permanent: Functions and Variables for Matrices and Linear Algebra
permut: Functions and Variables for Symmetries
permutation: Package functs
permutations: Функции и переменные для работы с множествами
petersen_graph: Функции и переменные пакета graphs
petersen_graph: Функции и переменные пакета graphs
petrov: Функции и переменные пакета ctensor
pfeformat: Функции и переменные для ввода и вывода
pickapart: Функции и переменные для выражений
picturep: Функции и переменные для картин
picture_equalp: Функции и переменные для картин
pic_height: Функции и переменные пакета draw
pic_width: Функции и переменные пакета draw
piece: Функции и переменные для выражений
piechart: Функции и переменные для статистических графиков
piechart: Функции и переменные для статистических графиков
piechart: Функции и переменные для статистических графиков
piechart: Функции и переменные для статистических графиков
piechart: Функции и переменные для статистических графиков
piechart: Функции и переменные для статистических графиков
pivot_count_sx: Functions and Variables for simplex
pivot_max_sx: Functions and Variables for simplex
planar_embedding: Функции и переменные пакета graphs
playback: Функции и переменные для работы в командной строке
playback: Функции и переменные для работы в командной строке
playback: Функции и переменные для работы в командной строке
playback: Функции и переменные для работы в командной строке
playback: Функции и переменные для работы в командной строке
playback: Функции и переменные для работы в командной строке
playback: Функции и переменные для работы в командной строке
playback: Функции и переменные для работы в командной строке
plot2d: Functions and Variables for Plotting
plot3d: Functions and Variables for Plotting
plotdf: Functions for numerical solution of differential equations
plotepsilon: Plotting Options
ploteq: Functions for numerical solution of differential equations
plot_format: Plotting Options
plot_options: Functions and Variables for Plotting
plot_realpart: Plotting Options
plsquares: Functions and Variables for lsquares
png_file: Plotting Options
pochhammer: Functions and Variables for orthogonal polynomials
pochhammer_max_index: Functions and Variables for orthogonal polynomials
points: Функции и переменные пакета draw
points: Функции и переменные пакета draw
points: Функции и переменные пакета draw
points: Функции и переменные пакета draw
points: Функции и переменные пакета draw
points: Функции и переменные пакета draw
points_joined: Функции и переменные пакета draw
point_size: Функции и переменные пакета draw
point_type: Plotting Options
point_type: Функции и переменные пакета draw
poisdiff: Functions and Variables for Poisson series
poisexpt: Functions and Variables for Poisson series
poisint: Functions and Variables for Poisson series
poislim: Functions and Variables for Poisson series
poismap: Functions and Variables for Poisson series
poisplus: Functions and Variables for Poisson series
poissimp: Functions and Variables for Poisson series
poisson: Functions and Variables for Poisson series
poissubst: Functions and Variables for Poisson series
poistimes: Functions and Variables for Poisson series
poistrim: Functions and Variables for Poisson series
polar: Функции и переменные пакета draw
polarform: Функции и переменные для выражений
polartorect: Functions and Variables for fast Fourier transform
polar_to_xy: Functions and Variables for Plotting
polydecomp: Functions and Variables for Polynomials
polyfactor: Functions and Variables for Equations
polygon: Функции и переменные пакета draw
polygon: Функции и переменные пакета draw
polymod: Общие операторы
polymod: Общие операторы
polymod: Functions and Variables for Polynomials
polynome2ele: Functions and Variables for Symmetries
polynomialp: Functions and Variables for Polynomials
polytocompanion: Functions and Variables for linearalgebra
poly_add: Функции и переменные пакета grobner
poly_buchberger: Функции и переменные пакета grobner
poly_buchberger_criterion: Функции и переменные пакета grobner
poly_coefficient_ring: Функции и переменные пакета grobner
poly_colon_ideal: Функции и переменные пакета grobner
poly_content: Функции и переменные пакета grobner
poly_depends_p: Функции и переменные пакета grobner
poly_elimination_ideal: Функции и переменные пакета grobner
poly_elimination_order: Функции и переменные пакета grobner
poly_exact_divide: Функции и переменные пакета grobner
poly_expand: Функции и переменные пакета grobner
poly_expt: Функции и переменные пакета grobner
poly_gcd: Функции и переменные пакета grobner
poly_grobner: Функции и переменные пакета grobner
poly_grobner_algorithm: Функции и переменные пакета grobner
poly_grobner_debug: Функции и переменные пакета grobner
poly_grobner_equal: Функции и переменные пакета grobner
poly_grobner_member: Функции и переменные пакета grobner
poly_grobner_subsetp: Функции и переменные пакета grobner
poly_ideal_intersection: Функции и переменные пакета grobner
poly_ideal_polysaturation: Функции и переменные пакета grobner
poly_ideal_polysaturation1: Функции и переменные пакета grobner
poly_ideal_saturation: Функции и переменные пакета grobner
poly_ideal_saturation1: Функции и переменные пакета grobner
poly_lcm: Функции и переменные пакета grobner
poly_minimization: Функции и переменные пакета grobner
poly_monomial_order: Функции и переменные пакета grobner
poly_multiply: Функции и переменные пакета grobner
poly_normalize: Функции и переменные пакета grobner
poly_normalize_list: Функции и переменные пакета grobner
poly_normal_form: Функции и переменные пакета grobner
poly_polysaturation_extension: Функции и переменные пакета grobner
poly_primary_elimination_order: Функции и переменные пакета grobner
poly_primitive_part: Функции и переменные пакета grobner
poly_pseudo_divide: Функции и переменные пакета grobner
poly_reduced_grobner: Функции и переменные пакета grobner
poly_reduction: Функции и переменные пакета grobner
poly_return_term_list: Функции и переменные пакета grobner
poly_saturation_extension: Функции и переменные пакета grobner
poly_secondary_elimination_order: Функции и переменные пакета grobner
poly_subtract: Функции и переменные пакета grobner
poly_s_polynomial: Функции и переменные пакета grobner
poly_top_reduction_only: Функции и переменные пакета grobner
potential: Functions and Variables for Integration
powers: Функции и переменные для выражений
powerseries: Functions and Variables for Series
powerset: Функции и переменные для работы с множествами
powerset: Функции и переменные для работы с множествами
power_mod: Функции и переменные для теории чисел
pred: Общие операторы
prederror: Функции и переменные для программирования на Maxima
prefer_d: Functions and Variables for Integration
prev_prime: Функции и переменные для теории чисел
primelmt: Functions and Variables for algebraic extensions
primep: Функции и переменные для теории чисел
primep_number_of_tests: Функции и переменные для теории чисел
print: Функции и переменные для ввода и вывода
printf: String Input and Output
printfile: Функции и переменные для ввода и вывода
printpois: Functions and Variables for Poisson series
printprops: Функции и переменные для работы в командной строке
printprops: Функции и переменные для работы в командной строке
printprops: Функции и переменные для работы в командной строке
print_graph: Функции и переменные пакета graphs
prodrac: Functions and Variables for Symmetries
product: Функции и переменные для выражений
product: Functions and Variables for Sums and Products
product_use_gamma: Functions and Variables for solve_rec
programmode: Functions and Variables for Equations
prompt: Функции и переменные для работы в командной строке
properties: Вспомогательные функции и переменные
props: Вспомогательные функции и переменные
propvars: Вспомогательные функции и переменные
psexpand: Functions and Variables for Series
psi: Gamma and Factorial Functions
psi: Функции и переменные пакета ctensor
ps_file: Plotting Options
ptriangularize: Functions and Variables for linearalgebra
pui: Functions and Variables for Symmetries
pui2comp: Functions and Variables for Symmetries
pui2ele: Functions and Variables for Symmetries
pui2polynome: Functions and Variables for Symmetries
puireduc: Functions and Variables for Symmetries
pui_direct: Functions and Variables for Symmetries
put: Вспомогательные функции и переменные
pwilt: Functions and Variables for Integration

Q
qput: Вспомогательные функции и переменные
qrange: Функции и переменные для описательной статистики
qrange: Функции и переменные для описательной статистики
quad_control: Functions and Variables for QUADPACK
quad_qag: Functions and Variables for QUADPACK
quad_qagi: Functions and Variables for QUADPACK
quad_qagp: Functions and Variables for QUADPACK
quad_qags: Functions and Variables for QUADPACK
quad_qawc: Functions and Variables for QUADPACK
quad_qawf: Functions and Variables for QUADPACK
quad_qawo: Functions and Variables for QUADPACK
quad_qaws: Functions and Variables for QUADPACK
quantile: Функции и переменные для описательной статистики
quantile: Функции и переменные для описательной статистики
quantile_bernoulli: Функции и переменные для дискретных распределений
quantile_beta: Функции и переменные для непрерывных распределений
quantile_binomial: Функции и переменные для дискретных распределений
quantile_cauchy: Функции и переменные для непрерывных распределений
quantile_chi2: Функции и переменные для непрерывных распределений
quantile_continuous_uniform: Функции и переменные для непрерывных распределений
quantile_discrete_uniform: Функции и переменные для дискретных распределений
quantile_exp: Функции и переменные для непрерывных распределений
quantile_f: Функции и переменные для непрерывных распределений
quantile_gamma: Функции и переменные для непрерывных распределений
quantile_geometric: Функции и переменные для дискретных распределений
quantile_gumbel: Функции и переменные для непрерывных распределений
quantile_hypergeometric: Функции и переменные для дискретных распределений
quantile_laplace: Функции и переменные для непрерывных распределений
quantile_logistic: Функции и переменные для непрерывных распределений
quantile_lognormal: Функции и переменные для непрерывных распределений
quantile_negative_binomial: Функции и переменные для дискретных распределений
quantile_normal: Функции и переменные для непрерывных распределений
quantile_pareto: Функции и переменные для непрерывных распределений
quantile_poisson: Функции и переменные для дискретных распределений
quantile_rayleigh: Функции и переменные для непрерывных распределений
quantile_student_t: Функции и переменные для непрерывных распределений
quantile_weibull: Функции и переменные для непрерывных распределений
quartile_skewness: Функции и переменные для описательной статистики
quartile_skewness: Функции и переменные для описательной статистики
quit: Функции и переменные для работы в командной строке
qunit: Функции и переменные для теории чисел
quotient: Functions and Variables for Polynomials

R
radcan: Functions and Variables for Simplification
radexpand: Functions and Variables for Simplification
radius: Функции и переменные пакета graphs
radsubstflag: Functions and Variables for Polynomials
random: Общие операторы
random_bernoulli: Функции и переменные для дискретных распределений
random_bernoulli: Функции и переменные для дискретных распределений
random_beta: Функции и переменные для непрерывных распределений
random_beta: Функции и переменные для непрерывных распределений
random_beta_algorithm: Функции и переменные для непрерывных распределений
random_binomial: Функции и переменные для дискретных распределений
random_binomial: Функции и переменные для дискретных распределений
random_binomial_algorithm: Функции и переменные для дискретных распределений
random_bipartite_graph: Функции и переменные пакета graphs
random_cauchy: Функции и переменные для непрерывных распределений
random_cauchy: Функции и переменные для непрерывных распределений
random_chi2: Функции и переменные для непрерывных распределений
random_chi2: Функции и переменные для непрерывных распределений
random_chi2_algorithm: Функции и переменные для непрерывных распределений
random_continuous_uniform: Функции и переменные для непрерывных распределений
random_continuous_uniform: Функции и переменные для непрерывных распределений
random_digraph: Функции и переменные пакета graphs
random_discrete_uniform: Функции и переменные для дискретных распределений
random_discrete_uniform: Функции и переменные для дискретных распределений
random_exp: Функции и переменные для непрерывных распределений
random_exp: Функции и переменные для непрерывных распределений
random_exp_algorithm: Функции и переменные для непрерывных распределений
random_f: Функции и переменные для непрерывных распределений
random_f: Функции и переменные для непрерывных распределений
random_f_algorithm: Функции и переменные для непрерывных распределений
random_gamma: Функции и переменные для непрерывных распределений
random_gamma: Функции и переменные для непрерывных распределений
random_gamma_algorithm: Функции и переменные для непрерывных распределений
random_geometric: Функции и переменные для дискретных распределений
random_geometric: Функции и переменные для дискретных распределений
random_geometric_algorithm: Функции и переменные для дискретных распределений
random_graph: Функции и переменные пакета graphs
random_graph1: Функции и переменные пакета graphs
random_gumbel: Функции и переменные для непрерывных распределений
random_gumbel: Функции и переменные для непрерывных распределений
random_hypergeometric: Функции и переменные для дискретных распределений
random_hypergeometric: Функции и переменные для дискретных распределений
random_hypergeometric_algorithm: Функции и переменные для дискретных распределений
random_laplace: Функции и переменные для непрерывных распределений
random_laplace: Функции и переменные для непрерывных распределений
random_logistic: Функции и переменные для непрерывных распределений
random_logistic: Функции и переменные для непрерывных распределений
random_lognormal: Функции и переменные для непрерывных распределений
random_lognormal: Функции и переменные для непрерывных распределений
random_negative_binomial: Функции и переменные для дискретных распределений
random_negative_binomial: Функции и переменные для дискретных распределений
random_negative_binomial_algorithm: Функции и переменные для дискретных распределений
random_network: Функции и переменные пакета graphs
random_normal: Функции и переменные для непрерывных распределений
random_normal: Функции и переменные для непрерывных распределений
random_normal_algorithm: Функции и переменные для непрерывных распределений
random_pareto: Функции и переменные для непрерывных распределений
random_pareto: Функции и переменные для непрерывных распределений
random_permutation: Функции и переменные для работы с множествами
random_poisson: Функции и переменные для дискретных распределений
random_poisson: Функции и переменные для дискретных распределений
random_poisson_algorithm: Функции и переменные для дискретных распределений
random_rayleigh: Функции и переменные для непрерывных распределений
random_rayleigh: Функции и переменные для непрерывных распределений
random_regular_graph: Функции и переменные пакета graphs
random_regular_graph: Функции и переменные пакета graphs
random_student_t: Функции и переменные для непрерывных распределений
random_student_t: Функции и переменные для непрерывных распределений
random_student_t_algorithm: Функции и переменные для непрерывных распределений
random_tournament: Функции и переменные пакета graphs
random_tree: Функции и переменные пакета graphs
random_weibull: Функции и переменные для непрерывных распределений
random_weibull: Функции и переменные для непрерывных распределений
range: Функции и переменные для описательной статистики
range: Функции и переменные для описательной статистики
rank: Functions and Variables for Matrices and Linear Algebra
rassociative: Functions and Variables for Simplification
rat: Functions and Variables for Polynomials
ratalgdenom: Functions and Variables for Polynomials
ratchristof: Функции и переменные пакета ctensor
ratcoef: Functions and Variables for Polynomials
ratdenom: Functions and Variables for Polynomials
ratdenomdivide: Functions and Variables for Polynomials
ratdiff: Functions and Variables for Polynomials
ratdisrep: Functions and Variables for Polynomials
rateinstein: Функции и переменные пакета ctensor
ratexpand: Functions and Variables for Polynomials
ratexpand: Functions and Variables for Polynomials
ratfac: Functions and Variables for Polynomials
rational: Package functs
rationalize: Общие операторы
ratmx: Functions and Variables for Matrices and Linear Algebra
ratnumer: Functions and Variables for Polynomials
ratp: Functions and Variables for Polynomials
ratprint: Functions and Variables for Polynomials
ratriemann: Функции и переменные пакета ctensor
ratsimp: Functions and Variables for Polynomials
ratsimp: Functions and Variables for Polynomials
ratsimpexpons: Functions and Variables for Polynomials
ratsubst: Functions and Variables for Polynomials
ratvars: Functions and Variables for Polynomials
ratvars: Functions and Variables for Polynomials
ratvars: Functions and Variables for Polynomials
ratvarswitch: Functions and Variables for Polynomials
ratweight: Functions and Variables for Polynomials
ratweights: Functions and Variables for Polynomials
ratweyl: Функции и переменные пакета ctensor
ratwtlvl: Functions and Variables for Polynomials
read: Функции и переменные для ввода и вывода
readbyte: String Input and Output
readchar: String Input and Output
readline: String Input and Output
readonly: Функции и переменные для ввода и вывода
read_array: Functions and Variables for plain-text input and output
read_binary_array: Functions and Variables for binary input and output
read_binary_list: Functions and Variables for binary input and output
read_binary_matrix: Functions and Variables for binary input and output
read_hashed_array: Functions and Variables for plain-text input and output
read_list: Functions and Variables for plain-text input and output
read_matrix: Functions and Variables for plain-text input and output
read_nested_list: Functions and Variables for plain-text input and output
read_xpm: Функции и переменные для картин
realonly: Functions and Variables for Equations
realpart: Функции и переменные для выражений
realroots: Functions and Variables for Equations
real_fft: Functions and Variables for fast Fourier transform
rearray: Функции и переменные для работы с массивами
rectangle: Функции и переменные пакета draw
rectform: Функции и переменные для выражений
recttopolar: Functions and Variables for fast Fourier transform
rediff: Функции и переменные пакета itensor
reduce_consts: Package rducon
reduce_order: Functions and Variables for solve_rec
refcheck: Функции и переменные для отладки
region_boundaries: Функции и переменные для карты мира
rem: Вспомогательные функции и переменные
remainder: Functions and Variables for Polynomials
remarray: Функции и переменные для работы с массивами
remarray: Функции и переменные для работы с массивами
rembox: Функции и переменные для выражений
rembox: Функции и переменные для выражений
rembox: Функции и переменные для выражений
remcomps: Функции и переменные пакета itensor
remcon: Функции и переменные пакета itensor
remcoord: Функции и переменные пакета itensor
remfun: Functions and Variables for Fourier series
remfunction: Функции и переменные для работы в командной строке
remfunction: Функции и переменные для работы в командной строке
remlet: Функции и переменные для правил преобразования и шаблонов
remlet: Функции и переменные для правил преобразования и шаблонов
remlet: Функции и переменные для правил преобразования и шаблонов
remlet: Функции и переменные для правил преобразования и шаблонов
remove: Вспомогательные функции и переменные
remove: Вспомогательные функции и переменные
remove: Вспомогательные функции и переменные
remove: Вспомогательные функции и переменные
remove: Вспомогательные функции и переменные
remove_edge: Функции и переменные пакета graphs
remove_plot_option: Functions and Variables for Plotting
remove_vertex: Функции и переменные пакета graphs
rempart: Package functs
remrule: Функции и переменные для правил преобразования и шаблонов
remrule: Функции и переменные для правил преобразования и шаблонов
remsym: Функции и переменные пакета itensor
remvalue: Вспомогательные функции и переменные
remvalue: Вспомогательные функции и переменные
rename: Функции и переменные пакета itensor
rename: Функции и переменные пакета itensor
reset: Функции и переменные для работы в командной строке
residue: Functions and Variables for Integration
resolvante: Functions and Variables for Symmetries
resolvante_alternee1: Functions and Variables for Symmetries
resolvante_bipartite: Functions and Variables for Symmetries
resolvante_diedrale: Functions and Variables for Symmetries
resolvante_klein: Functions and Variables for Symmetries
resolvante_klein3: Functions and Variables for Symmetries
resolvante_produit_sym: Functions and Variables for Symmetries
resolvante_unitaire: Functions and Variables for Symmetries
resolvante_vierer: Functions and Variables for Symmetries
rest: Функции и переменные для работы со списками
rest: Функции и переменные для работы со списками
resultant: Functions and Variables for Polynomials
resultant: Functions and Variables for Polynomials
return: Функции и переменные для программирования на Maxima
reveal: Функции и переменные для ввода и вывода
reverse: Функции и переменные для работы со списками
revert: Functions and Variables for Series
revert2: Functions and Variables for Series
rgb2level: Функции и переменные для картин
rhs: Functions and Variables for Equations
ric: Функции и переменные пакета ctensor
ricci: Функции и переменные пакета ctensor
riem: Функции и переменные пакета ctensor
riemann: Функции и переменные пакета ctensor
rinvariant: Функции и переменные пакета ctensor
risch: Functions and Variables for Integration
rk: Functions for numerical solution of differential equations
rk: Функции и переменные пакета dynamics
rk: Функции и переменные пакета dynamics
rmxchar: Функции и переменные для ввода и вывода
rmxchar: Functions and Variables for Matrices and Linear Algebra
rncombine: Вспомогательные функции и переменные
romberg: Functions and Variables for romberg
rombergabs: Functions and Variables for romberg
rombergit: Functions and Variables for romberg
rombergmin: Functions and Variables for romberg
rombergtol: Functions and Variables for romberg
room: Функции и переменные времени выполнения
room: Функции и переменные времени выполнения
room: Функции и переменные времени выполнения
rootsconmode: Functions and Variables for Equations
rootscontract: Functions and Variables for Equations
rootsepsilon: Functions and Variables for Equations
rot_horizontal: Функции и переменные пакета draw
rot_vertical: Функции и переменные пакета draw
round: Общие операторы
row: Functions and Variables for Matrices and Linear Algebra
rowop: Functions and Variables for linearalgebra
rowswap: Functions and Variables for linearalgebra
rreduce: Функции и переменные для работы с множествами
rreduce: Функции и переменные для работы с множествами
run_testsuite: Функции и переменные для работы с ошибками
run_testsuite: Функции и переменные для работы с ошибками
run_testsuite: Функции и переменные для работы с ошибками
run_testsuite: Функции и переменные для работы с ошибками
run_viewer: Plotting Options

S
same_xy: Plotting Options
same_xyz: Plotting Options
sample: Plotting Options
save: Функции и переменные для ввода и вывода
save: Функции и переменные для ввода и вывода
save: Функции и переменные для ввода и вывода
save: Функции и переменные для ввода и вывода
save: Функции и переменные для ввода и вывода
save: Функции и переменные для ввода и вывода
savedef: Функции и переменные для ввода и вывода
savefactors: Functions and Variables for Polynomials
scalarmatrixp: Functions and Variables for Matrices and Linear Algebra
scalarp: Вспомогательные функции и переменные
scaled_bessel_i: Bessel Functions
scaled_bessel_i0: Bessel Functions
scaled_bessel_i1: Bessel Functions
scalefactors: Functions and Variables for Matrices and Linear Algebra
scale_lp: Functions and Variables for simplex
scanmap: Функции и переменные для программирования на Maxima
scanmap: Функции и переменные для программирования на Maxima
scatterplot: Функции и переменные для статистических графиков
scatterplot: Функции и переменные для статистических графиков
scatterplot: Функции и переменные для статистических графиков
scatterplot: Функции и переменные для статистических графиков
schur2comp: Functions and Variables for Symmetries
sconcat: Функции и переменные для ввода и вывода
scopy: String Processing
scsimp: Functions and Variables for Simplification
scurvature: Функции и переменные пакета ctensor
sdowncase: String Processing
sec: Функции и переменные для тригонометрии
sech: Функции и переменные для тригонометрии
second: Функции и переменные для работы со списками
sequal: String Processing
sequalignore: String Processing
setcheck: Функции и переменные для отладки
setcheckbreak: Функции и переменные для отладки
setdifference: Функции и переменные для работы с множествами
setelmx: Functions and Variables for Matrices and Linear Algebra
setequalp: Функции и переменные для работы с множествами
setify: Функции и переменные для работы с множествами
setp: Функции и переменные для работы с множествами
setunits: Functions and Variables for Units
setup_autoload: Вспомогательные функции и переменные
setval: Функции и переменные для отладки
set_edge_weight: Функции и переменные пакета graphs
set_partitions: Функции и переменные для работы с множествами
set_partitions: Функции и переменные для работы с множествами
set_plot_option: Functions and Variables for Plotting
set_random_state: Общие операторы
set_up_dot_simplifications: Функции и переменные пакета affine
set_up_dot_simplifications: Функции и переменные пакета affine
set_vertex_label: Функции и переменные пакета graphs
seventh: Функции и переменные для работы со списками
sexplode: String Processing
sf: Функции и переменные пакета atensor
sha1sum: Octets and Utilities for Cryptography
sha256sum: Octets and Utilities for Cryptography
shortest_path: Функции и переменные пакета graphs
show: Функции и переменные для ввода и вывода
showcomps: Функции и переменные пакета itensor
showratvars: Функции и переменные для ввода и вывода
showratvars: Functions and Variables for Polynomials
showtime: Функции и переменные для работы в командной строке
sign: Общие операторы
signum: Общие операторы
similaritytransform: Functions and Variables for Matrices and Linear Algebra
simp: Functions and Variables for Simplification
simplified_output: Functions and Variables for zeilberger
simplify_products: Functions and Variables for solve_rec
simplify_sum: Functions and Variables for solve_rec
simplode: String Processing
simpmetderiv: Функции и переменные пакета itensor
simpmetderiv: Функции и переменные пакета itensor
simpproduct: Functions and Variables for Sums and Products
simpsum: Functions and Variables for Sums and Products
simtran: Functions and Variables for Matrices and Linear Algebra
sin: Функции и переменные для тригонометрии
sinh: Функции и переменные для тригонометрии
sinnpiflag: Functions and Variables for Fourier series
sinsert: String Processing
sinvertcase: String Processing
sixth: Функции и переменные для работы со списками
skewness: Функции и переменные для описательной статистики
skewness: Функции и переменные для описательной статистики
skewness_bernoulli: Функции и переменные для дискретных распределений
skewness_beta: Функции и переменные для непрерывных распределений
skewness_binomial: Функции и переменные для дискретных распределений
skewness_chi2: Функции и переменные для непрерывных распределений
skewness_continuous_uniform: Функции и переменные для непрерывных распределений
skewness_discrete_uniform: Функции и переменные для дискретных распределений
skewness_exp: Функции и переменные для непрерывных распределений
skewness_f: Функции и переменные для непрерывных распределений
skewness_gamma: Функции и переменные для непрерывных распределений
skewness_geometric: Функции и переменные для дискретных распределений
skewness_gumbel: Функции и переменные для непрерывных распределений
skewness_hypergeometric: Функции и переменные для дискретных распределений
skewness_laplace: Функции и переменные для непрерывных распределений
skewness_logistic: Функции и переменные для непрерывных распределений
skewness_lognormal: Функции и переменные для непрерывных распределений
skewness_negative_binomial: Функции и переменные для дискретных распределений
skewness_normal: Функции и переменные для непрерывных распределений
skewness_pareto: Функции и переменные для непрерывных распределений
skewness_poisson: Функции и переменные для дискретных распределений
skewness_rayleigh: Функции и переменные для непрерывных распределений
skewness_student_t: Функции и переменные для непрерывных распределений
skewness_weibull: Функции и переменные для непрерывных распределений
slength: String Processing
slommel: Bessel Functions
smake: String Processing
smismatch: String Processing
solve: Functions and Variables for Equations
solvedecomposes: Functions and Variables for Equations
solveexplicit: Functions and Variables for Equations
solvefactors: Functions and Variables for Equations
solvenullwarn: Functions and Variables for Equations
solveradcan: Functions and Variables for Equations
solvetrigwarn: Functions and Variables for Equations
solve_rec: Functions and Variables for solve_rec
solve_rec_rat: Functions and Variables for solve_rec
some: Функции и переменные для работы с множествами
some: Функции и переменные для работы с множествами
somrac: Functions and Variables for Symmetries
sort: Общие операторы
sort: Общие операторы
space: Characters
sparse: Functions and Variables for Matrices and Linear Algebra
sparse6_decode: Функции и переменные пакета graphs
sparse6_encode: Функции и переменные пакета graphs
sparse6_export: Функции и переменные пакета graphs
sparse6_import: Функции и переменные пакета graphs
specint: Functions and Variables for Integration
spherical: Функции и переменные пакета draw
spherical_bessel_j: Functions and Variables for orthogonal polynomials
spherical_bessel_y: Functions and Variables for orthogonal polynomials
spherical_hankel1: Functions and Variables for orthogonal polynomials
spherical_hankel2: Functions and Variables for orthogonal polynomials
spherical_harmonic: Functions and Variables for orthogonal polynomials
spherical_to_xyz: Functions and Variables for Plotting
splice: Макросы
split: String Processing
splitfield: Functions and Variables for algebraic extensions
sposition: String Processing
sprint: String Input and Output
sqfr: Functions and Variables for Polynomials
sqrt: Общие операторы
sqrtdispflag: Общие операторы
sremove: String Processing
sremovefirst: String Processing
sreverse: String Processing
ssearch: String Processing
ssort: String Processing
sstatus: Функции и переменные для работы в командной строке
ssubst: String Processing
ssubstfirst: String Processing
staircase: Функции и переменные пакета dynamics
stardisp: Функции и переменные для ввода и вывода
stats_numer: Functions and Variables for stats
status: Функции и переменные времени выполнения
status: Функции и переменные времени выполнения
status: Функции и переменные времени выполнения
std: Функции и переменные для описательной статистики
std: Функции и переменные для описательной статистики
std1: Функции и переменные для описательной статистики
std1: Функции и переменные для описательной статистики
std_bernoulli: Функции и переменные для дискретных распределений
std_beta: Функции и переменные для непрерывных распределений
std_binomial: Функции и переменные для дискретных распределений
std_chi2: Функции и переменные для непрерывных распределений
std_continuous_uniform: Функции и переменные для непрерывных распределений
std_discrete_uniform: Функции и переменные для дискретных распределений
std_exp: Функции и переменные для непрерывных распределений
std_f: Функции и переменные для непрерывных распределений
std_gamma: Функции и переменные для непрерывных распределений
std_geometric: Функции и переменные для дискретных распределений
std_gumbel: Функции и переменные для непрерывных распределений
std_hypergeometric: Функции и переменные для дискретных распределений
std_laplace: Функции и переменные для непрерывных распределений
std_logistic: Функции и переменные для непрерывных распределений
std_lognormal: Функции и переменные для непрерывных распределений
std_negative_binomial: Функции и переменные для дискретных распределений
std_normal: Функции и переменные для непрерывных распределений
std_pareto: Функции и переменные для непрерывных распределений
std_poisson: Функции и переменные для дискретных распределений
std_rayleigh: Функции и переменные для непрерывных распределений
std_student_t: Функции и переменные для непрерывных распределений
std_weibull: Функции и переменные для непрерывных распределений
stirling: Формула Стирлинга
stirling1: Функции и переменные для работы с множествами
stirling2: Функции и переменные для работы с множествами
strim: String Processing
striml: String Processing
strimr: String Processing
string: Функции и переменные для ввода и вывода
stringdisp: Функции и переменные для ввода и вывода
stringout: Функции и переменные для ввода и вывода
stringout: Функции и переменные для ввода и вывода
stringout: Функции и переменные для ввода и вывода
stringout: Функции и переменные для ввода и вывода
stringout: Функции и переменные для ввода и вывода
stringp: String Processing
string_to_octets: Octets and Utilities for Cryptography
strong_components: Функции и переменные пакета graphs
struve_h: Struve Functions
struve_l: Struve Functions
style: Plotting Options
sublis: Общие операторы
sublist: Общие операторы
sublist_indices: Функции и переменные для работы со списками
sublis_apply_lambda: Общие операторы
submatrix: Functions and Variables for Matrices and Linear Algebra
subsample: Функции и переменные для манипулирования данными
subsample: Функции и переменные для манипулирования данными
subset: Функции и переменные для работы с множествами
subsetp: Функции и переменные для работы с множествами
subst: Общие операторы
substinpart: Общие операторы
substpart: Общие операторы
substring: String Processing
subvar: Функции и переменные для работы с массивами
subvarp: Общие операторы
sum: Функции и переменные для выражений
sum: Functions and Variables for Sums and Products
sumcontract: Functions and Variables for Sums and Products
sumexpand: Functions and Variables for Sums and Products
summand_to_rec: Functions and Variables for solve_rec
supcase: String Processing
supcontext: Функции для работы с контекстами
supcontext: Функции для работы с контекстами
surface_hide: Функции и переменные пакета draw
svg_file: Plotting Options
symbolp: Общие операторы
symmdifference: Функции и переменные для работы с множествами
symmetric: Functions and Variables for Simplification
symmetricp: Функции и переменные пакета ctensor
system: Функции и переменные для ввода и вывода

T
t: Plotting Options
tab: Characters
take_channel: Функции и переменные для картин
take_inference: Functions and Variables for inference_result
tan: Функции и переменные для тригонометрии
tanh: Функции и переменные для тригонометрии
taylor: Functions and Variables for Series
taylordepth: Functions and Variables for Series
taylorinfo: Functions and Variables for Series
taylorp: Functions and Variables for Series
taylor_logexpand: Functions and Variables for Series
taylor_order_coefficients: Functions and Variables for Series
taylor_simplifier: Functions and Variables for Series
taylor_truncate_polynomials: Functions and Variables for Series
taytorat: Functions and Variables for Series
tcl_output: Функции и переменные для ввода и вывода
tcl_output: Функции и переменные для ввода и вывода
tcl_output: Функции и переменные для ввода и вывода
tcontract: Functions and Variables for Symmetries
tellrat: Functions and Variables for Polynomials
tellsimp: Функции и переменные для правил преобразования и шаблонов
tellsimpafter: Функции и переменные для правил преобразования и шаблонов
tensorkill: Функции и переменные пакета ctensor
tentex: Функции и переменные пакета itensor
tenth: Функции и переменные для работы со списками
terminal: Функции и переменные пакета draw
testsuite_files: Функции и переменные для работы с ошибками
test_mean: Functions and Variables for stats
test_means_difference: Functions and Variables for stats
test_normality: Functions and Variables for stats
test_proportion: Functions and Variables for stats
test_proportions_difference: Functions and Variables for stats
test_rank_sum: Functions and Variables for stats
test_sign: Functions and Variables for stats
test_signed_rank: Functions and Variables for stats
test_variance: Functions and Variables for stats
test_variance_ratio: Functions and Variables for stats
tex: Функции и переменные для ввода и вывода
tex: Функции и переменные для ввода и вывода
tex: Функции и переменные для ввода и вывода
tex: Функции и переменные для ввода и вывода
tex: Функции и переменные для ввода и вывода
tex: Функции и переменные для ввода и вывода
texput: Функции и переменные для ввода и вывода
texput: Функции и переменные для ввода и вывода
texput: Функции и переменные для ввода и вывода
texput: Функции и переменные для ввода и вывода
third: Функции и переменные для работы со списками
throw: Функции и переменные для программирования на Maxima
time: Функции и переменные времени выполнения
timedate: Функции и переменные времени выполнения
timer: Функции и переменные для отладки
timer: Функции и переменные для отладки
timer: Функции и переменные для отладки
timer_devalue: Функции и переменные для отладки
timer_info: Функции и переменные для отладки
timer_info: Функции и переменные для отладки
title: Plotting Options
title: Функции и переменные пакета draw
tldefint: Functions and Variables for Integration
tlimit: Функции для работы с пределами
tlimit: Функции для работы с пределами
tlimit: Функции для работы с пределами
tlimswitch: Функции для работы с пределами
todd_coxeter: Functions and Variables for Groups
toeplitz: Functions and Variables for linearalgebra
tokens: String Processing
topological_sort: Функции и переменные пакета graphs
totaldisrep: Functions and Variables for Polynomials
totalfourier: Functions and Variables for Fourier series
totient: Функции и переменные для теории чисел
to_lisp: Функции и переменные для работы в командной строке
tpartpol: Functions and Variables for Symmetries
tr: Функции и переменные пакета ctensor
trace: Функции и переменные для отладки
trace: Функции и переменные для отладки
trace: Функции и переменные для отладки
tracematrix: Package functs
trace_options: Функции и переменные для отладки
trace_options: Функции и переменные для отладки
transcompile: Функции и переменные для определения функций
transform_xy: Plotting Options
translate: Функции и переменные для определения функций
translate: Функции и переменные для определения функций
translate: Функции и переменные для определения функций
translate_file: Функции и переменные для определения функций
translate_file: Функции и переменные для определения функций
transparent: Функции и переменные пакета draw
transpose: Functions and Variables for Matrices and Linear Algebra
transrun: Функции и переменные для определения функций
tree_reduce: Функции и переменные для работы с множествами
tree_reduce: Функции и переменные для работы с множествами
treillis: Functions and Variables for Symmetries
treinat: Functions and Variables for Symmetries
triangularize: Functions and Variables for Matrices and Linear Algebra
trigexpand: Функции и переменные для тригонометрии
trigexpandplus: Функции и переменные для тригонометрии
trigexpandtimes: Функции и переменные для тригонометрии
triginverses: Функции и переменные для тригонометрии
trigrat: Функции и переменные для тригонометрии
trigreduce: Функции и переменные для тригонометрии
trigreduce: Функции и переменные для тригонометрии
trigsign: Функции и переменные для тригонометрии
trigsimp: Функции и переменные для тригонометрии
trivial_solutions: Functions and Variables for zeilberger
true: Математические константы
trunc: Functions and Variables for Series
tr_array_as_ref: Функции и переменные для определения функций
tr_bound_function_applyp: Функции и переменные для определения функций
tr_file_tty_messagesp: Функции и переменные для определения функций
tr_float_can_branch_complex: Функции и переменные для определения функций
tr_function_call_default: Функции и переменные для определения функций
tr_numer: Функции и переменные для определения функций
tr_optimize_max_loop: Функции и переменные для определения функций
tr_semicompile: Функции и переменные для определения функций
tr_state_vars: Функции и переменные для определения функций
tr_warnings_get: Функции и переменные для определения функций
tr_warn_bad_function_calls: Функции и переменные для определения функций
tr_warn_fexpr: Функции и переменные для определения функций
tr_warn_meval: Функции и переменные для определения функций
tr_warn_mode: Функции и переменные для определения функций
tr_warn_undeclared: Функции и переменные для определения функций
tr_warn_undefined_variable: Функции и переменные для определения функций
tr_windy: Функции и переменные для определения функций
ttyoff: Функции и переменные для ввода и вывода
tutte_graph: Функции и переменные пакета graphs

U
ueivects: Functions and Variables for Matrices and Linear Algebra
ufg: Функции и переменные пакета ctensor
uforget: Functions and Variables for Units
ug: Функции и переменные пакета ctensor
ultraspherical: Functions and Variables for orthogonal polynomials
und: Математические константы
underlying_graph: Функции и переменные пакета graphs
undiff: Функции и переменные пакета itensor
unicode: Characters
unicode_to_utf8: Characters
union: Функции и переменные для работы с множествами
unique: Функции и переменные для работы со списками
uniteigenvectors: Functions and Variables for Matrices and Linear Algebra
unitvector: Functions and Variables for Matrices and Linear Algebra
unit_step: Functions and Variables for orthogonal polynomials
unit_vectors: Функции и переменные пакета draw
unless: Функции и переменные для программирования на Maxima
unorder: Общие операторы
unsum: Functions and Variables for Series
untellrat: Functions and Variables for Polynomials
untimer: Функции и переменные для отладки
untimer: Функции и переменные для отладки
untrace: Функции и переменные для отладки
untrace: Функции и переменные для отладки
uppercasep: Characters
uric: Функции и переменные пакета ctensor
uricci: Функции и переменные пакета ctensor
uriem: Функции и переменные пакета ctensor
uriemann: Функции и переменные пакета ctensor
usersetunits: Functions and Variables for Units
user_preamble: Функции и переменные пакета draw
use_fast_arrays: Функции и переменные для работы с массивами
us_ascii_only: Characters
utf8_to_unicode: Characters
uvect: Functions and Variables for Matrices and Linear Algebra

V
values: Функции и переменные для работы в командной строке
vandermonde_matrix: Functions and Variables for linearalgebra
var: Функции и переменные для описательной статистики
var: Функции и переменные для описательной статистики
var1: Функции и переменные для описательной статистики
var1: Функции и переменные для описательной статистики
var_bernoulli: Функции и переменные для дискретных распределений
var_beta: Функции и переменные для непрерывных распределений
var_binomial: Функции и переменные для дискретных распределений
var_chi2: Функции и переменные для непрерывных распределений
var_continuous_uniform: Функции и переменные для непрерывных распределений
var_discrete_uniform: Функции и переменные для дискретных распределений
var_exp: Функции и переменные для непрерывных распределений
var_f: Функции и переменные для непрерывных распределений
var_gamma: Функции и переменные для непрерывных распределений
var_geometric: Функции и переменные для дискретных распределений
var_gumbel: Функции и переменные для непрерывных распределений
var_hypergeometric: Функции и переменные для дискретных распределений
var_laplace: Функции и переменные для непрерывных распределений
var_logistic: Функции и переменные для непрерывных распределений
var_lognormal: Функции и переменные для непрерывных распределений
var_negative_binomial: Функции и переменные для дискретных распределений
var_normal: Функции и переменные для непрерывных распределений
var_pareto: Функции и переменные для непрерывных распределений
var_poisson: Функции и переменные для дискретных распределений
var_rayleigh: Функции и переменные для непрерывных распределений
var_student_t: Функции и переменные для непрерывных распределений
var_weibull: Функции и переменные для непрерывных распределений
vector: Функции и переменные пакета draw
vector: Функции и переменные пакета draw
vectorpotential: Общие операторы
vectorpotential: Functions and Variables for Matrices and Linear Algebra
vectorsimp: Functions and Variables for Matrices and Linear Algebra
vect_cross: Functions and Variables for Matrices and Linear Algebra
verbify: Функции и переменные для выражений
verbose: Functions and Variables for Series
vers: Package functs
vertex_coloring: Функции и переменные пакета graphs
vertex_degree: Функции и переменные пакета graphs
vertex_distance: Функции и переменные пакета graphs
vertex_eccentricity: Функции и переменные пакета graphs
vertex_in_degree: Функции и переменные пакета graphs
vertex_out_degree: Функции и переменные пакета graphs
vertices: Функции и переменные пакета graphs
vertices_to_cycle: Функции и переменные пакета graphs
vertices_to_path: Функции и переменные пакета graphs

W
warnings: Functions and Variables for zeilberger
weyl: Функции и переменные пакета ctensor
weyl: Функции и переменные пакета ctensor
wheel_graph: Функции и переменные пакета graphs
while: Функции и переменные для программирования на Maxima
window: Plotting Options
with_stdout: Функции и переменные для ввода и вывода
with_stdout: Функции и переменные для ввода и вывода
writebyte: String Input and Output
writefile: Функции и переменные для ввода и вывода
write_binary_data: Functions and Variables for binary input and output
write_data: Functions and Variables for plain-text input and output
wronskian: Package functs

X
x: Plotting Options
xaxis: Функции и переменные пакета draw
xaxis_color: Функции и переменные пакета draw
xaxis_type: Функции и переменные пакета draw
xaxis_width: Функции и переменные пакета draw
xlabel: Plotting Options
xlabel: Функции и переменные пакета draw
xrange: Функции и переменные пакета draw
xreduce: Функции и переменные для работы с множествами
xreduce: Функции и переменные для работы с множествами
xthru: Общие операторы
xthru: Functions and Variables for Simplification
xtics: Plotting Options
xtics: Функции и переменные пакета draw
xtics_axis: Функции и переменные пакета draw
xtics_rotate: Функции и переменные пакета draw
xu_grid: Функции и переменные пакета draw
xy_file: Функции и переменные пакета draw
xy_scale: Plotting Options
x_voxel: Функции и переменные пакета draw

Y
y: Plotting Options
yaxis: Функции и переменные пакета draw
yaxis_color: Функции и переменные пакета draw
yaxis_type: Функции и переменные пакета draw
yaxis_width: Функции и переменные пакета draw
ylabel: Plotting Options
ylabel: Функции и переменные пакета draw
yrange: Функции и переменные пакета draw
ytics: Plotting Options
ytics: Функции и переменные пакета draw
ytics_axis: Функции и переменные пакета draw
ytics_rotate: Функции и переменные пакета draw
yv_grid: Функции и переменные пакета draw
yx_ratio: Plotting Options
y_voxel: Функции и переменные пакета draw

Z
z: Plotting Options
zaxis: Функции и переменные пакета draw
zaxis_color: Функции и переменные пакета draw
zaxis_type: Функции и переменные пакета draw
zaxis_width: Функции и переменные пакета draw
Zeilberger: Functions and Variables for zeilberger
zerobern: Функции и переменные для теории чисел
zeroequiv: Общие операторы
zerofor: Functions and Variables for linearalgebra
zeromatrix: Functions and Variables for Matrices and Linear Algebra
zeromatrixp: Functions and Variables for linearalgebra
zeta: Функции и переменные для теории чисел
zeta%pi: Функции и переменные для теории чисел
zgeev: Functions and Variables for lapack
zheev: Functions and Variables for lapack
zlabel: Plotting Options
zlabel: Функции и переменные пакета draw
zlange: Functions and Variables for lapack
zmin: Plotting Options
zrange: Функции и переменные пакета draw
ztics: Plotting Options
ztics: Функции и переменные пакета draw
ztics_axis: Функции и переменные пакета draw
ztics_rotate: Функции и переменные пакета draw
z_voxel: Функции и переменные пакета draw

Jump to:   !   #   %   '   *   +   -   .   /   :   <   =   >   ?   ^   _   |   ~  
A   B   C   D   E   F   G   H   I   J   K   L   M   N   O   P   Q   R   S   T   U   V   W   X   Y   Z  

Footnotes

(1)

Applied Mathematics and Programming Division, K.U. Leuven

(2)

Applied Mathematics and Programming Division, K.U. Leuven

(3)

Institut für Mathematik, T.U. Wien

(4)

National Bureau of Standards, Washington, D.C., U.S.A

(5)

https://www.netlib.org/slatec

(6)

https://www.netlib.org/quadpack

(7)

R. Piessens, E. de Doncker-Kapenga, C.W. Uberhuber, and D.K. Kahaner. QUADPACK: A Subroutine Package for Automatic Integration. Berlin: Springer-Verlag, 1983, ISBN 0387125531.