This is maxima.info, produced by makeinfo version 5.1 from maxima.texi.


File: maxima.info,  Node: Пакет grobner,  Next: Пакет impdiff,  Prev: Пакет graphs,  Up: Top

51 Пакет grobner
****************

* Menu:

* Введение в пакет grobner::
* Функции и переменные пакета grobner::


File: maxima.info,  Node: Введение в пакет grobner,  Next: Функции и переменные пакета grobner,  Prev: Top,  Up: Top

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
---------------------------------------------------------------------------------

   • ‘lex’

     чисто лексикографический, используется по умолчанию для сравнения
     порядка одночленов
   • ‘grlex’

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

   • ‘grevlex’

     общая степень, совпадения разрешаются обратным лексикографическим
     упорядочиванием

   • ‘invlex’

     обратный лексикографический порядок


File: maxima.info,  Node: Функции и переменные пакета grobner,  Prev: Введение в пакет grobner,  Up: Top

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’

     Возможные значения:
        • ‘buchberger’
        • ‘parallel_buchberger’
        • ‘gebauer_moeller’

     Определяет алгоритм, используемый для поиска базиса Гребнера.

 -- Управляющая переменная: 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>)


File: maxima.info,  Node: Пакет impdiff,  Next: Пакет implicit_plot,  Prev: Пакет grobner,  Up: Top

52 Пакет impdiff
****************

* Menu:

* Функции и переменные пакета impdiff::


File: maxima.info,  Node: Функции и переменные пакета impdiff,  Prev: Пакет impdiff,  Up: Пакет impdiff

52.1 Функции и переменные пакета impdiff
========================================

 -- Функция: implicit_derivative (<f>,<indvarlist>,<orderlist>,<depvar>)
     Эта процедура вычисляет неявную производную функции многих
     переменных.  <f> – функция-массив, с индексами, обозначающими
     порядок производных по переменным из <indvarlist>; <indvarlist> –
     список независимых переменных; <orderlist> – требуемый порядок; и
     <depvar> – зависимая переменная.

     Для того, чтобы использовать эту функцию, сначала напишите
     ‘load("impdiff")’.


File: maxima.info,  Node: Пакет implicit_plot,  Next: Пакет interpol,  Prev: Пакет impdiff,  Up: Top

53 Пакет implicit_plot
**********************

* Menu:

* Функции и переменные пакета implicit_plot::


File: maxima.info,  Node: Функции и переменные пакета implicit_plot,  Prev: Пакет implicit_plot,  Up: Пакет implicit_plot

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"]);


File: maxima.info,  Node: Пакет interpol,  Next: lapack-pkg,  Prev: Пакет implicit_plot,  Up: Top

54 Пакет interpol
*****************

* Menu:

* Введение в пакет interpol::
* Функции и переменные пакета interpol::


File: maxima.info,  Node: Введение в пакет interpol,  Next: Функции и переменные пакета interpol,  Prev: Пакет interpol,  Up: Пакет interpol

54.1 Введение в пакет interpol
==============================

Пакет ‘interpol’ определяет методы Лагранжа, линейный и и метод
кубических сплайнов для полиномиальной интерполяции.

   С комментариями, сообщениями об ошибках и предложениями, пожалуйста
обращайтесь ко мне по адресу <’mario AT edu DOT xunta DOT es’>.


File: maxima.info,  Node: Функции и переменные пакета interpol,  Prev: Введение в пакет interpol,  Up: Пакет interpol

54.2 Функции и переменные пакета interpol
=========================================

 -- Функция: lagrange (<points>)
 -- Функция: lagrange (<points>, <option>)
     Вычисляет полиномиальную интерполяцию методом Лагранжа.  Аргумент
     <points> должен быть либо:

        • матрицей из двух колонок, ‘p:matrix([2,4],[5,6],[9,3])’,
        • списком пар, ‘p: [[2,4],[5,6],[9,3]]’,
        • списком чисел ‘p: [4,6,3]’, в этом случае абсцисса будет
          назначена автоматически равной 1, 2, 3 и т.д.

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

     Аргумент <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> должен быть либо:

        • матрицей из двух колонок, ‘p:matrix([2,4],[5,6],[9,3])’,
        • списком пар, ‘p: [[2,4],[5,6],[9,3]]’,
        • списком чисел ‘p: [4,6,3]’, в этом случае абсцисса будет
          назначена автоматически равной 1, 2, 3 и т.д.

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

     Аргумент <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> должен быть либо:

        • матрицей из двух колонок, ‘p:matrix([2,4],[5,6],[9,3])’,
        • списком пар, ‘p: [[2,4],[5,6],[9,3]]’,
        • списком чисел ‘p: [4,6,3]’, в этом случае абсцисса будет
          назначена автоматически равной 1, 2, 3 и т.д.

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

     Существует три специальные опции:
        • ‘'d1’, по умолчанию ‘'unknown’, – первая производная в точке
          x_1.  Если ‘'unknown’, то вторая производная в точке x_1
          предполагается равной 0 (натуральный кубический сплайн).  Если
          задана, то вторая производная вычисляется исходя из этого
          числа.

        • ‘'dn’, по умолчанию ‘'unknown’, – первая производная в точке
          x_n.  Если ‘'unknown’, то вторая производная в точке x_n
          предполагается равной 0 (натуральный кубический сплайн).  Если
          задана, то вторая производная вычисляется исходя из этого
          числа.

        • ‘'varname’, по умолчанию ‘'x’, – имя независимой переменной.

     Примеры:
          (%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))$


File: maxima.info,  Node: lapack-pkg,  Next: lbfgs-pkg,  Prev: Пакет interpol,  Up: Top

55 lapack
*********

* Menu:

* Introduction to lapack::
* Functions and Variables for lapack::


File: maxima.info,  Node: Introduction to lapack,  Next: Functions and Variables for lapack,  Prev: lapack-pkg,  Up: lapack-pkg

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.


File: maxima.info,  Node: Functions and Variables for lapack,  Prev: Introduction to lapack,  Up: lapack-pkg

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>.

     ‘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 ‘zheev’, 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.


File: maxima.info,  Node: lbfgs-pkg,  Next: lindstedt-pkg,  Prev: lapack-pkg,  Up: Top

56 lbfgs
********

* Menu:

* Introduction to lbfgs::
* Functions and Variables for lbfgs::


File: maxima.info,  Node: Introduction to lbfgs,  Next: Functions and Variables for lbfgs,  Prev: Top,  Up: Top

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>


File: maxima.info,  Node: Functions and Variables for lbfgs,  Prev: Introduction to lbfgs,  Up: Top

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’.


File: maxima.info,  Node: lindstedt-pkg,  Next: linearalgebra-pkg,  Prev: lbfgs-pkg,  Up: Top

57 lindstedt
************

* Menu:

* Functions and Variables for lindstedt::


File: maxima.info,  Node: Functions and Variables for lindstedt,  Prev: lindstedt-pkg,  Up: lindstedt-pkg

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")’.


File: maxima.info,  Node: linearalgebra-pkg,  Next: lsquares-pkg,  Prev: lindstedt-pkg,  Up: Top

58 linearalgebra
****************

* Menu:

* Introduction to linearalgebra::
* Functions and Variables for linearalgebra::


File: maxima.info,  Node: Introduction to linearalgebra,  Next: Functions and Variables for linearalgebra

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 ]


File: maxima.info,  Node: Functions and Variables for linearalgebra,  Prev: Introduction to linearalgebra

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>.


File: maxima.info,  Node: lsquares-pkg,  Next: makeOrders-pkg,  Prev: linearalgebra-pkg,  Up: Top

59 lsquares
***********

* Menu:

* Introduction to lsquares::
* Functions and Variables for lsquares::


File: maxima.info,  Node: Introduction to lsquares,  Next: Functions and Variables for lsquares,  Prev: lsquares-pkg,  Up: lsquares-pkg

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.


File: maxima.info,  Node: Functions and Variables for lsquares,  Prev: Introduction to lsquares,  Up: lsquares-pkg

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")’.


File: maxima.info,  Node: makeOrders-pkg,  Next: mnewton-pkg,  Prev: lsquares-pkg,  Up: Top

60 makeOrders
*************

* Menu:

* Functions and Variables for makeOrders::


File: maxima.info,  Node: Functions and Variables for makeOrders,  Prev: makeOrders-pkg,  Up: makeOrders-pkg

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")’.


File: maxima.info,  Node: mnewton-pkg,  Next: numericalio-pkg,  Prev: makeOrders-pkg,  Up: Top

61 mnewton
**********

* Menu:

* Introduction to mnewton::
* Functions and Variables for mnewton::


File: maxima.info,  Node: Introduction to mnewton,  Next: Functions and Variables for mnewton,  Prev: mnewton-pkg,  Up: mnewton-pkg

61.1 Introduction to mnewton
============================

‘mnewton’ is an implementation of Newton’s method for solving nonlinear
equations in one or more variables.


File: maxima.info,  Node: Functions and Variables for mnewton,  Prev: Introduction to mnewton,  Up: mnewton-pkg

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.  If ‘newtonepsilon’ is a bigfloat, then
     ‘mnewton’ computations are done with bigfloats.  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’.

 -- Function: mnewton (<FuncList>,<VarList>,<GuessList>)

     Multiple nonlinear functions solution using the Newton method.
     <FuncList> is the list of functions to solve, <VarList> is the list
     of variable names, and <GuessList> is the list of initial
     approximations.

     The solution is returned in the same format that ‘solve()’ returns.
     If the solution is not found, ‘[]’ is returned.

     This function is controlled by global variables ‘newtonepsilon’ and
     ‘newtonmaxiter’.

     See also ‘realroots’, ‘allroots’, ‘find_root’ and ‘newton’.

          (%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]]

     To use this function write first ‘load("mnewton")’.  See also
     ‘newtonepsilon’ and ‘newtonmaxiter’.


File: maxima.info,  Node: numericalio-pkg,  Next: opsubst-pkg,  Prev: mnewton-pkg,  Up: Top

62 numericalio
**************

* Menu:

* Introduction to numericalio::
* Functions and Variables for plain-text input and output::
* Functions and Variables for binary input and output::


File: maxima.info,  Node: Introduction to numericalio,  Next: Functions and Variables for plain-text input and output,  Prev: mnewton-pkg,  Up: numericalio-pkg

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.


File: maxima.info,  Node: Functions and Variables for plain-text input and output,  Next: Functions and Variables for binary input and output,  Prev: Introduction to numericalio,  Up: numericalio-pkg

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’.


File: maxima.info,  Node: Functions and Variables for binary input and output,  Prev: Functions and Variables for plain-text input and output,  Up: numericalio-pkg

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’.


File: maxima.info,  Node: opsubst-pkg,  Next: orthopoly-pkg,  Prev: numericalio-pkg,  Up: Top

63 opsubst
**********

* Menu:

* Functions and Variables for opsubst::


File: maxima.info,  Node: Functions and Variables for opsubst,  Prev: opsubst-pkg,  Up: opsubst-pkg

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")’.


File: maxima.info,  Node: orthopoly-pkg,  Next: romberg-pkg,  Prev: opsubst-pkg,  Up: Top

64 orthopoly
************

* Menu:

* Introduction to orthogonal polynomials::
* Functions and Variables for orthogonal polynomials::


File: maxima.info,  Node: Introduction to orthogonal polynomials,  Next: Functions and Variables for orthogonal polynomials,  Prev: orthopoly-pkg,  Up: orthopoly-pkg

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 *note 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)

   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.


File: maxima.info,  Node: Functions and Variables for orthogonal polynomials,  Prev: Introduction to orthogonal polynomials,  Up: orthopoly-pkg

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>.

     Reference: Abramowitz and Stegun, equations 22.5.37, page 779,
     8.6.6 (second equation), page 334, and 8.2.5, page 333.

 -- Function: assoc_legendre_q (<n>, <m>, <x>)
     The associated Legendre function of the second kind of degree <n>
     and order <m>.

     Reference: Abramowitz and Stegun, equation 8.5.3 and 8.1.8.

 -- Function: chebyshev_t (<n>, <x>)
     The Chebyshev polynomial of the first kind of degree <n>.

     Reference: Abramowitz and Stegun, equation 22.5.47, page 779.

 -- Function: chebyshev_u (<n>, <x>)
     The Chebyshev polynomial of the second kind of degree <n>.

     Reference: Abramowitz and Stegun, equation 22.5.48, page 779.

 -- Function: gen_laguerre (<n>, <a>, <x>)
     The generalized Laguerre polynomial of degree <n>.

     Reference: Abramowitz and Stegun, equation 22.5.54, page 780.

 -- Function: hermite (<n>, <x>)
     The Hermite polynomial of degree <n>.

     Reference: Abramowitz and Stegun, equation 22.5.55, page 780.

 -- 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.

     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> <= -1’ or ‘<b> <= -1’.

     Reference: Abramowitz and Stegun, equation 22.5.42, page 779.

 -- Function: laguerre (<n>, <x>)
     The Laguerre polynomial of degree <n>.

     Reference: Abramowitz and Stegun, equations 22.5.16 and 22.5.54,
     page 780.

 -- Function: legendre_p (<n>, <x>)
     The Legendre polynomial of the first kind of degree <n>.

     Reference: Abramowitz and Stegun, equations 22.5.50 and 22.5.51,
     page 779.

 -- Function: legendre_q (<n>, <x>)
     The Legendre function of the second kind of degree <n>.

     Reference: Abramowitz and Stegun, equations 8.5.3 and 8.1.8.

 -- 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.  For nonnegative integers <n> with ‘<n> <=
     pochhammer_max_index’, the expression ‘pochhammer (<x>, <n>)’
     evaluates to the product ‘<x> (<x> + 1) (<x> + 2) ... (<x> + n -
     1)’ when ‘<n> > 0’ and to 1 when ‘<n> = 0’.  For negative <n>,
     ‘pochhammer (<x>, <n>)’ is defined as ‘(-1)^<n> / pochhammer (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 Abramowitz and Stegun, equation 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: Abramowitz and Stegun, equation 6.1.16, page 256.

 -- Function: spherical_bessel_j (<n>, <x>)
     The spherical Bessel function of the first kind.

     Reference: Abramowitz and Stegun, equations 10.1.8, page 437 and
     10.1.15, page 439.

 -- Function: spherical_bessel_y (<n>, <x>)
     The spherical Bessel function of the second kind.

     Reference: Abramowitz and Stegun, equations 10.1.9, page 437 and
     10.1.15, page 439.

 -- Function: spherical_hankel1 (<n>, <x>)
     The spherical Hankel function of the first kind.

     Reference: Abramowitz and Stegun, equation 10.1.36, page 439.

 -- Function: spherical_hankel2 (<n>, <x>)
     The spherical Hankel function of the second kind.

     Reference: Abramowitz and Stegun, equation 10.1.17, page 439.

 -- Function: spherical_harmonic (<n>, <m>, <x>, <y>)
     The spherical harmonic function.

     Reference: Merzbacher 9.64.

 -- 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 (also known as the Gegenbauer
     polynomial).

     Reference: Abramowitz and Stegun, equation 22.5.46, page 779.


File: maxima.info,  Node: romberg-pkg,  Next: simplex-pkg,  Prev: orthopoly-pkg,  Up: Top

65 romberg
**********

* Menu:

* Functions and Variables for romberg::


File: maxima.info,  Node: Functions and Variables for romberg,  Prev: Top,  Up: Top

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’.


File: maxima.info,  Node: simplex-pkg,  Next: simplification-pkg,  Prev: romberg-pkg,  Up: Top

66 simplex
**********

* Menu:

* Introduction to simplex::
* Functions and Variables for simplex::


File: maxima.info,  Node: Introduction to simplex,  Next: Functions and Variables for simplex,  Prev: simplex-pkg,  Up: simplex-pkg

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


File: maxima.info,  Node: Functions and Variables for simplex,  Prev: Introduction to simplex,  Up: simplex-pkg

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’.


File: maxima.info,  Node: simplification-pkg,  Next: solve_rec-pkg,  Prev: simplex-pkg,  Up: Top

67 simplification
*****************

* Menu:

* Introduction to simplification::
* Package absimp::
* Package facexp::
* Package functs::
* Package ineq::
* Package rducon::
* Package scifac::


File: maxima.info,  Node: Introduction to simplification,  Next: Package absimp,  Prev: simplification-pkg,  Up: simplification-pkg

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.


File: maxima.info,  Node: Package absimp,  Next: Package facexp,  Prev: Introduction to simplification,  Up: simplification-pkg

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)


File: maxima.info,  Node: Package facexp,  Next: Package functs,  Prev: Package absimp,  Up: simplification-pkg

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


File: maxima.info,  Node: Package functs,  Next: Package ineq,  Prev: Package facexp,  Up: simplification-pkg

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")’.


File: maxima.info,  Node: Package ineq,  Next: Package rducon,  Prev: Package functs,  Up: simplification-pkg

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.


File: maxima.info,  Node: Package rducon,  Next: Package scifac,  Prev: Package ineq,  Up: simplification-pkg

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.


File: maxima.info,  Node: Package scifac,  Prev: Package rducon,  Up: simplification-pkg

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.


File: maxima.info,  Node: solve_rec-pkg,  Next: stats-pkg,  Prev: simplification-pkg,  Up: Top

68 solve_rec
************

* Menu:

* Introduction to solve_rec::
* Functions and Variables for solve_rec::


File: maxima.info,  Node: Introduction to solve_rec,  Next: Functions and Variables for solve_rec,  Prev: solve_rec-pkg,  Up: solve_rec-pkg

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)


File: maxima.info,  Node: Functions and Variables for solve_rec,  Prev: Introduction to solve_rec,  Up: solve_rec-pkg

68.2 Functions and Variables for solve_rec
==========================================

 -- 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


File: maxima.info,  Node: stats-pkg,  Next: Пакет stirling,  Prev: solve_rec-pkg,  Up: Top

69 stats
********

* Menu:

* Introduction to stats::
* Functions and Variables for inference_result::
* Functions and Variables for stats::
* Functions and Variables for special distributions::


File: maxima.info,  Node: Introduction to stats,  Next: Functions and Variables for inference_result,  Prev: Top,  Up: Top

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’>.


File: maxima.info,  Node: Functions and Variables for inference_result,  Next: Functions and Variables for stats,  Prev: Introduction to stats,  Up: Top

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’.


File: maxima.info,  Node: Functions and Variables for stats,  Next: Functions and Variables for special distributions,  Prev: Functions and Variables for inference_result,  Up: Top

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:

        • ‘'mean’, default ‘0’, is the mean value to be checked.

        • ‘'alternative’, default ‘'twosided’, is the alternative
          hypothesis; valid values are: ‘'twosided’, ‘'greater’ and
          ‘'less’.

        • ‘'dev’, default ‘'unknown’, this is the value of the standard
          deviation when it is known; valid values are: ‘'unknown’ or a
          positive expression.

        • ‘'conflevel’, default ‘95/100’, confidence level for the
          confidence interval; it must be an expression which takes a
          value in (0,1).

        • ‘'asymptotic’, default ‘false’, indicates whether it performs
          an exact <t>-test or an asymptotic one based on the Central
          Limit Theorem; valid values are ‘true’ and ‘false’.

     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:

        • 
        • ‘'alternative’, default ‘'twosided’, is the alternative
          hypothesis; valid values are: ‘'twosided’, ‘'greater’ and
          ‘'less’.

        • ‘'dev1’, default ‘'unknown’, this is the value of the standard
          deviation of the <x1> sample when it is known; valid values
          are: ‘'unknown’ or a positive expression.

        • ‘'dev2’, default ‘'unknown’, this is the value of the standard
          deviation of the <x2> sample when it is known; valid values
          are: ‘'unknown’ or a positive expression.

        • ‘'varequal’, default ‘false’, whether variances should be
          considered to be equal or not; this option takes effect only
          when ‘'dev1’ and/or ‘'dev2’ are ‘'unknown’.

        • ‘'conflevel’, default ‘95/100’, confidence level for the
          confidence interval; it must be an expression which takes a
          value in (0,1).

        • ‘'asymptotic’, default ‘false’, indicates whether it performs
          an exact <t>-test or an asymptotic one based on the Central
          Limit Theorem; valid values are ‘true’ and ‘false’.

     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:

        • ‘'mean’, default ‘'unknown’, is the population’s mean, when it
          is known.

        • ‘'alternative’, default ‘'twosided’, is the alternative
          hypothesis; valid values are: ‘'twosided’, ‘'greater’ and
          ‘'less’.

        • ‘'variance’, default ‘1’, this is the variance value
          (positive) to be checked.

        • ‘'conflevel’, default ‘95/100’, confidence level for the
          confidence interval; it must be an expression which takes a
          value in (0,1).

     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:

        • ‘'alternative’, default ‘'twosided’, is the alternative
          hypothesis; valid values are: ‘'twosided’, ‘'greater’ and
          ‘'less’.

        • ‘'mean1’, default ‘'unknown’, when it is known, this is the
          mean of the population from which <x1> was taken.

        • ‘'mean2’, default ‘'unknown’, when it is known, this is the
          mean of the population from which <x2> was taken.

        • ‘'conflevel’, default ‘95/100’, confidence level for the
          confidence interval of the ratio; it must be an expression
          which takes a value in (0,1).

     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:

        • ‘'proportion’, default ‘1/2’, is the value of the proportion
          to be checked.

        • ‘'alternative’, default ‘'twosided’, is the alternative
          hypothesis; valid values are: ‘'twosided’, ‘'greater’ and
          ‘'less’.

        • ‘'conflevel’, default ‘95/100’, confidence level for the
          confidence interval; it must be an expression which takes a
          value in (0,1).

        • ‘'asymptotic’, default ‘false’, indicates whether it performs
          an exact test based on the binomial distribution, or an
          asymptotic one based on the Central Limit Theorem; valid
          values are ‘true’ and ‘false’.

        • ‘'correct’, default ‘true’, indicates whether Yates correction
          is applied or not.

     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:

        • ‘'alternative’, default ‘'twosided’, is the alternative
          hypothesis; valid values are: ‘'twosided’ (‘p1 # p2’),
          ‘'greater’ (‘p1 > p2’) and ‘'less’ (‘p1 < p2’).

        • ‘'conflevel’, default ‘95/100’, confidence level for the
          confidence interval; it must be an expression which takes a
          value in (0,1).

        • ‘'correct’, default ‘true’, indicates whether Yates correction
          is applied or not.

     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:

        • ‘'alternative’, default ‘'twosided’, is the alternative
          hypothesis; valid values are: ‘'twosided’, ‘'greater’ and
          ‘'less’.

        • ‘'median’, default ‘0’, is the median value to be checked.

     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:

        • ‘'median’, default ‘0’, is the median value to be checked.

        • ‘'alternative’, default ‘'twosided’, is the alternative
          hypothesis; valid values are: ‘'twosided’, ‘'greater’ and
          ‘'less’.

     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:

        • ‘'alternative’, default ‘'twosided’, is the alternative
          hypothesis; valid values are: ‘'twosided’, ‘'greater’ and
          ‘'less’.

     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:

        • ‘'conflevel’, default ‘95/100’, confidence level for the
          confidence intervals; it must be an expression which takes a
          value in (0,1).

     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)) )$

