Maxima/Printable version


Maxima

The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at
https://en.wikibooks.org/wiki/Maxima

Permission is granted to copy, distribute, and/or modify this document under the terms of the Creative Commons Attribution-ShareAlike 3.0 License.

What is Maxima and what is it useful for

Maxima belongs to the category of computer software applications known as computer algebra systems - or CAS.

Within this category of applications, it is "general purpose" in that it is not dedicated to any specific mathematical topic of study or application. However, within that general-purpose category there is a sense in which it is a special-purpose application in that, while significant numerical computational capabilities are possible, the primary emphasis is on processing "symbolic" mathematical expressions using syntax for expression composition for input that conforms to that which Maxima can parse, interpret, and process.

So, to state it briefly, Maxima is primarily an application for processing symbolic mathematical expressions according to the purpose of the user using syntax Maxima can parse and interpret.

In general, Maxima expressions fall into three categories:

  • Mathematical expressions
  • Object expressions
  • Programming expressions

Mathematical expressions are for doing things that simply are essentially of a mathematical nature. Object expressions are used to create data structures for storage. Programming expressions provide the capability for some types of imperative or functional programming instructions.

Thus, Maxima is not strictly a programming language like Python, Julia, Java, C, and so forth. The differences between Maxima as a CAS, and other programming languages should become evident from the contents of this document and, even better, with the actual experience of using Maxima to accomplish specific mathematical tasks.

Getting started using Maxima will be much easier if the user begins with a particular frame of mind. Almost everything Maxima is an expression of some type. Expressions are what Maxima is all about - especially mathematical symbolic expressions. If numbers can be considered as represented symbolically by numeration (integers, fractions, decimal or floating point literals) then it is not an exaggeration to characterize everything Maxima can do as symbolic processing.

The following is a list of a few examples (certainly not all) of what Maxima can be used for:

  • Solve algebraic equations symbolically or numerically
  • Solve ordinary differential equations
  • Matrix creation and operations
  • Calculus - limits, differentiation, integration
  • Expansion, factoring, and simplification of expressions
  • Rational numbers as fractions, and "big" floating point numbers to specified precision
  • Complex numbers
  • Trigonometric expressions

Plotting - 2D and 3D with some animation

Maxima also includes packages that may be loaded into the current working environment that provide for some specialized tasks, including the study of specific mathematical subjects or applications.


Methods of use

Users have choices as to the kind of interface used to interact with Maxima. These choices inevitably have an influence on the installation source and process used to install Maxima on a computer with a particular operating system - notably MS Windows, Linux, or Mac OS.

The following is a concise list of the various interactive interface options:

  • Online by way of a web browser interface , without installation[1]
  • Offline after installation on a computer system
    • Using a graphical user interface (with a GUI)
    • From a terminal console (without a GUI)

The online web browser interface may be useful for beginners that want to try Maxima for the first time, or for occasions when a local installation is not available for some reason. This web browser interface includes a link to the Maxima Documentation, which is best characterized as a reference manual with some examples, and not as a user guide.

After installation of Maxima alone without a GUI, the user can interface with the Maxima CLI by way of a terminal console by entering:

$> maxima

This should start Maxima as follows:

$> maxima
Loading /home/yourusername/.maxima/maxima-init.mac
Maxima 5.49.0 https://maxima.sourceforge.io
using Lisp SBCL 2.0.1.debian
Distributed under the GNU Public License. See the file COPYING.
Dedicated to the memory of William Schelter.
The function bug_report() provides bug reporting information.

(%i1)

The (%i1) prompt is where the first Maxima expression is entered by the user. For example:

(%i1) 'integrate(%e^(2*t+a)*sin(t)*t,t);
                            ⌠
                            ⎮   2 t + a
(%o1)                       ⎮ %e        t sin(t) dt
                            ⎮
                            ⌡
(%i2)

It is likely that most users will find that interacting with Maxima from a terminal console (without a GUI) is somewhat crude, and furthermore all input expressions and output expressions are not persistent between sessions. Hence, the GUI option is generally recommended, but at the cost of having to become familiar with the GUI of choice.

There are two commonly used GUIs for Maxima:

Xmaxima is typically included with the Maxima installation. It is very similar to the terminal console GUI.

wxMaxima is unquestionably the more comprehensive, complete, and useful GUI presently available for Maxima.

Maxima is typically more useful as an interactive tool. However, it can be used to execute a file containing Maxima expressions. To execute Maxima expressions saved in a file named c.mac for example, and save output to a text file named c.txt use a command from a terminal shell session such as:

 $> maxima -b c.mac >c.txt

References

  1. ↑ "Maxima Online - WASM". maxima-on-wasm.pages.dev. Retrieved 2026-04-19.


Installation

Installation

If there can be a frustration for both new users of Maxima and current users it is installation. For typical users, this does not need to be the case. This section is devoted to providing the simplest installation path possible for computers with three operating systems (MS Windows, Mac OS, and Linux) without getting bogged down by technical details or atypical requirements.

There are in general two installation options that will be of interest to most users of Maxima:

  • Installation of Maxima alone
  • Installation of the wxMaxima GUI including Maxima

Installation of Maxima alone for MS Windows, Mac OS, and Linux

Follow the instructions for the relevant operating system provided using the following link to the Maxima website installation instruction page:

Maxima Installation Instructions


For Linux, there is the option of installing Maxima using the software package management system for your Linux distribution. Most distributions provide binaries for Maxima in their repositories. These usually are the version which was current, when the distribution was released. So they likely are not the latest version of Maxima. Also, these binaries may not have been compiled with support for Unicode which is something that users may find useful. However, having a more current version of Maxima may not be necessary, and the same applies to Unicode support. So if following the Maxima installation instructions for Linux is too technical for you, then the simplest path is to install Maxima using the software package management system for your Linux distribution.

Installation of wxMaxima GUI including Maxima for MS Windows and Mac OS

For MS Windows and Mac OS, follow the instructions for the relevant operating system provided using the following link to the wxMaxima website installation instruction page:

wxMaxima Installation Instructions

Installation of wxMaxima GUI including Maxima for Linux (recommended)

For Linux there are several options:

  • As noted for Linux, above there is the option of installing wxMaxima including Maxima using the software package management system for your Linux distribution. Most distributions provide binaries for wxMaxima and Maxima in their repositories. These usually are the version which was current, when the distribution was released. So they likely are not the latest version of wxMaxima and Maxima. Also, the Maxima binaries may not have been compiled with support for Unicode which is something that users may find useful. However, having a more current version of wxMaxima and Maxima may not be necessary, and the same applies to Unicode support. So the simplest path is to install wxMaxima and Maxima using the software package management system for your Linux distribution.
  • The second option is to install Maxima using the Installation of Maxima alone for Linux instructions of the link above, and then install wxMaxima using the software package management system for your Linux distribution. wxMaxima will either autodetect the installed version of Maxima, or the user can provide the path to the desired Maxima executable file using the Configure settings of wxMaxima. This option provides a relatively recent version of Maxima with Unicode support.


Instructions for compiling and installing Maxima and wxMaxima from source code can be found by referring to the links above respectively. This option is technically complex requiring specialized know-how.


Getting Started Using Maxima

Getting Started Using Maxima - Some Essentials

This section is intended for those that are new to Maxima. It may or may not be of value or interest to those having prior experience.

The Maxima Way of doing Mathematics

Imagine that you want to create a computer application to perform some general mathematical tasks - not merely numerical calculations or "number crunching" as it is sometimes referred to somewhat pejoratively. It seems likely that it would be realized early on that, unlike humans that can interpret concepts and notation using context, computers and programming software generally are intolerant of any sort of ambiguity. Progress is being made in providing programming software with the ability to interpret based on context, but not here in Maxima. The Maxima expression syntax was created to be logical as well as unambiguous and precise in meaning and intention.

Another realization likely would be that mathematical expressions are the essential object on which mathematical concepts hinge, and that these concepts are conveyed using a conventional (if not entirely standard) system of notation. So, the means to compose mathematical expressions using some syntax for interpreting mathematical notation that your program could read and process as input would be essential. So Maxima is not a programming language in the conventional sense.

With the foregoing in mind, before starting to see examples of Maxima in action, keep the following in mind while learning and using Maxima:

  • Expressions of various types (especially mathematical expressions) are the input to Maxima
  • Every expression returns a value which is displayed as output unless the display is suppressed by some means
  • Expressions as input are entered using an expression syntax that Maxima can read and process

Maxima expressions are of three types:

  1. Mathematical expressions
  2. Object expressions
  3. Programming expressions

Maxima expressions are comprised of two "ingredients" so to speak:

  1. Atoms
  2. Operators

Atoms:

These are one type of the built-in basic expression ingredients of Maxima. They are:

  1. Literal numerals for numbers - integer, fraction, and floating point literals
  2. Identifiers - names used alone or to identify other expressions by name
  3. Strings - quoted strings of one or more characters

Operators:

These are the second type of the built-in expression ingredients of Maxima. Including:

  1. Mathematical operators such as + , - , * , /, ^ , ! for addition, subtraction, negation, multiplication, division, exponentiation, factorial and the like. Internally to Maxima these are short-hand symbols for operators. Maxima operators also include "functions" such as sin(x), log(x), etc.
  2. Operators that are used to accomplish something other than for mathematical purposes


Note: It is important to point out that there is a difference between operators, functions as used in the context of programming, and the mathematical concept of functions. In this book all Maxima functions in the programming sense of the word that are built-in to Maxima (that is "out-of-the-box" so to speak) will be referred to as operators, including those from loaded packages that are included with the Maxima distribution. Maxima functions in the programming sense of the word created by the user will be referred to as functions. The context should make it clear when the mathematical concept of a function is being referred to. It is unfortunately the case that the Maxima documentation refers to operators as functions. Like so much else, the word "function" has become overloaded.

Expressions - Identifiers, Atoms, and Operators

With the foregoing information in mind, Maxima can be used to provide some examples of these various aspects of working with Maxima. This will be accomplished in the spirit of providing some insight and clarity for how to interact with Maxima, and how to compose expressions for input and how to interpret the values of expressions as output.

Indentifiers

Symbols

  • symbols %z7 and %z9 represent any arbitrary integer value.


Operators

"=" means syntactic equality. Check : is(equal(a,b))


Names

  "One quick way to check on name conflicts is to keep the html Maxima help manual up in a separate window, and have the Index panel available to type in a name you want to use. 
   The painful way to check on name conflicts is to wait for Maxima to give you a strange error message as to why what you are trying to do won’t work. If you get strange results, try changing the names of your variables and or functions. An important fact is that Maxima is case sensitive, so  you can avoid name conflicts by capitalizing the names of your user defined Maxima functions. Your Solve will not conflict with Maxima’s solve." Edwin L. Woollett[1]

References


Objects

  • atom
    • number
    • name
    • string
  • list of atoms


Variables


Data types

  • Numbers
  • Strings
  • Constants
  • Lists
  • Arrays
  • Structures


Features

Maxima recognizes certain mathematical properties of:

  • functions and variables
  • system. There is a list of non-mathematical, system-dependent features. See status.

which called features.

 declare (x, foo) /* gives the property foo to the function or variable x */
 declare (foo, feature) /* declares a new feature foo. */ 
 declare ([red, green, blue], feature) /* declares three new features, red, green, and blue. */

The predicate

 featurep (x, foo) 

returns true if x has the foo property, and false otherwise.

The infolist features is a list of known features. These are

   integer        noninteger      even
   odd            rational        irrational
   real           imaginary       complex
   analytic       increasing      decreasing
   oddfun         evenfun         posfun
   constant       commutative     lassociative
   rassociative   symmetric       antisymmetric
   integervalued

plus any user-defined features.

features is a list of mathematical features.

Example:

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

Declare

declare recognizes the following properties:

  • additive : Tells Maxima to simplify a_i expressions by the substitution a_i(x + y + z + ...) --> a_i(x) + a_i(y) + a_i(z) + .... The substitution is carried out on the first argument only.
  • alphabetic : Tells Maxima to recognize all characters in a_i (which must be a string) as alphabetic characters.
  • antisymmetric, commutative, symmetric : Tells Maxima to recognize a_i as a symmetric or antisymmetric function. commutative is the same as symmetric.
  • bindtest : Tells Maxima to trigger an error when a_i is evaluated unbound.
  • constant : Tells Maxima to consider a_i a symbolic constant.
  • even, odd : Tells Maxima to recognize a_i as an even or odd integer variable.
  • evenfun, oddfun : Tells Maxima to recognize a_i as an odd or even function.
  • evflag : Makes a_i known to the ev function so that a_i is bound to true during the execution of ev when a_i appears as a flag argument of ev. See evflag.
  • evfun : Makes a_i known to ev so that the function named by a_i is applied when a_i appears as a flag argument of ev. See evfun.
  • feature : Tells Maxima to recognize a_i as the name of a feature. Other atoms may then be declared to have the a_i property.
  • increasing, decreasing : Tells Maxima to recognize a_i as an increasing or decreasing function.
  • integer, noninteger : Tells Maxima to recognize a_i as an integer or noninteger variable.
  • integervalued : Tells Maxima to recognize a_i as an integer-valued function.
  • lassociative, rassociative : Tells Maxima to recognize a_i as a right-associative or left-associative function.
  • linear : Equivalent to declaring a_i both outative and additive.
  • mainvar : Tells Maxima to consider a_i a "main variable". A main variable succeeds all other constants and variables in the canonical ordering of Maxima expressions, as determined by ordergreatp.
  • multiplicative : Tells Maxima to simplify a_i expressions by the substitution a_i(x * y * z * ...) --> a_i(x) * a_i(y) * a_i(z) * .... The substitution is carried out on the first argument only.
  • nary : Tells Maxima to recognize a_i as an n-ary function. The nary declaration is not the same as calling the nary function. The sole effect of declare(foo, nary) is to instruct the Maxima simplifier to flatten nested expressions, for example, to simplify foo(x, foo(y, z)) to foo(x, y, z).
  • nonarray : Tells Maxima to consider a_i not an array. This declaration prevents multiple evaluation of a subscripted variable name.
  • nonscalar : Tells Maxima to consider a_i a nonscalar variable. The usual application is to declare a variable as a symbolic vector or matrix.
  • noun : Tells Maxima to parse a_i as a noun. The effect of this is to replace instances of a_i with 'a_i or nounify(a_i), depending on the context.
  • outative : Tells Maxima to simplify a_i expressions by pulling constant factors out of the first argument. When a_i has one argument, a factor is considered constant if it is a literal or declared constant. When a_i has two or more arguments, a factor is considered constant if the second argument is a symbol and the factor is free of the second argument.
  • posfun : Tells Maxima to recognize a_i as a positive function.
  • rational, irrational : Tells Maxima to recognize a_i as a rational or irrational real variable.
  • real, imaginary, complex : Tells Maxima to recognize a_i as a real, pure imaginary, or complex variable.
  • scalar : Tells Maxima to consider a_i a scalar variable.


Declare tells:

  • evenp()
  • oddp()
  • integerp()
  • and so on

what to return.


Compare with:

  • mode_decalre


Numbers

Check

(%i1) load(to_poly);
(%o1)  home/a/maxima/share/to_poly_solve/to_poly.lisp
(%i2) r;
(%o2) r 
(%i3) isreal_p(r);
(%o3) true     /*  When I use unspecified variables, Maxima seems to assume that they are real */ 
(%i4) z:x+y*%i;
(%o4) %i y + x
(%i5) isreal_p(z);
(%o5) isreal_p(%i y) /* maxima can't check if it is real or not */
(%i6) isreal_p(x);
(%o6) true
(%i7) isreal_p(y);
(%o7) true
(%i8) complex_number_p(z); 
(%o8) false 
(%i9) declare(z, complex);
(%o9) done
(%i10) complex_number_p(z);
(%o10)   false /* still not complex */                                                                                                              true


Random numbers

  bfloat(random(10^fpprec) / 10^fpprec); /* random bfloat with fpprec decimal digits in the range 0 to 1 */

Number types

Binary numbers

(%i1) ibase;
(%o1) 10
(%i2) obase;
(%o2) 10
(%i3) ibase:2;
(%o3) 2
(%i4) x=1001110;
(%o4) x=78


Complex numbers

Argument

Principial value of argument of complex number in turns carg produces results in the range (-pi, pi] . It can be mapped to [0, 2*pi) by adding 2*pi to the negative values

carg_t(z):=
 block(
 [t],
 t:carg(z)/(2*%pi),  /* now in turns */
 if t<0 then t:t+1, /* map from (-1/2,1/2] to [0, 1) */
 return(t)
)$

On can order list of complex points according to it's argument :

l2_ordered: sort(l2, lambda([z1,z2], is(carg(z1) < carg(z2))))$


rational numbers

  • rat
  • ratp

Rationalize with limit denominator:[1]

limit_denominator(x, max_denominator):=
block([p0, q0, p1, q1, n, d, a, q2, k, bound1, bound2, ratprint: false],
 [p0, q0, p1, q1]: [0, 1, 1, 0],
 [n, d]: ratexpand([ratnum(x), ratdenom(x)], 0),
 if d <= max_denominator then x else
 (catch(
   do block(
     a: quotient(n, d),
     q2: q0+a*q1,
     if q2 > max_denominator then throw('done),
     [p0, q0, p1, q1]: [p1, q1, p0+a*p1, q2],
     [n, d]: [d, n-a*d])),
 k: quotient(max_denominator-q0, q1),
 bound1: (p0+k*p1)/(q0+k*q1),
 bound2: p1/q1,
 if abs(bound2 - x) <= abs(bound1 - x) then bound2 else bound1))$

Predicate functions

(%i1) is(0=0.0);
(%o1) false

Compare :

(%i1) a:0.0$
(%i2)is(equal(a,0));
(%o2) true


List of predicate functions ( see p at the end ) :

  • abasep
  • alphacharp
  • alphanumericp
  • atom
  • bfloatp
  • blockmatrixp
  • cequal
  • cequalignore
  • cgreaterp
  • cgreaterpignore
  • charp
  • clessp
  • clesspignore
  • complex_number_p from to_poly package
  • constantp
  • constituent
  • diagmatrixp
  • digitcharp
  • disjointp
  • elementp
  • emptyp
  • evenp
  • featurep
  • floatnump ( compare : isreal_p)
  • if
  • integerp
  • intervalp
  • is
  • isreal_p from to_poly package
  • lcharp
  • listp
  • listp
  • lowercasep
  • mapatom
  • matrixp
  • matrixp
  • maybe
  • member
  • nonnegintegerp
  • nonscalarp
  • numberp
  • oddp
  • operatorp
  • ordergreatp
  • orderlessp
  • picture_equalp
  • picturep
  • poly_depends_p
  • poly_grobner_subsetp
  • polynomialp
  • prederror
  • primep
  • ratnump
  • ratp
  • scalarp
  • sequal
  • sequalignore
  • setequalp
  • setp
  • stringp
  • subsetp
  • subvarp
  • symbolp
  • symmetricp
  • taylorp
  • unknown
  • uppercasep
  • zeroequiv
  • zeromatrixp
  • zn_primroot_p


See also :

  • declare[2]
    • property:
      • rational, irrational, real, imaginary, complex,
      • even, odd,
      • decreasing, increasing
      • evenfun, oddfun

Number Theory

There are functions and operators useful with integer numbers

Elementary number theory

In Maxima there are some elementary functions like the factorial n! and the double factorial n!! defined as where is the greatest integer less than or equal to

Divisibility

Some of the most important functions for integer numbers have to do with divisibility:

gcd, ifactor, mod, divisors... 

all of them well documented in help. you can view it with the '?' command.

Function ifactors takes positive integer and returns a list of pairs : prime factor and its exponent. For example :

a:ifactors(8);
[[2,3]]

It means that :

Other Functions

Continuus fractions :

(%i6) cfdisrep([1,1,1,1]);
(%o6) 1+1/(1+1/(1+1/1))
(%i7) float(%), numer;
(%o7) 1.666666666666667


Functions

Definition

For mathematical functions use always

define() 

instead of

:= 

There is only one small difference between them:

"The function definition operator. f(x_1, ..., x_n) := expr defines a function named f with arguments x_1, …, x_n and function body expr. := never evaluates the function body (unless explicitly evaluated by quote-quote '')."

"Defines a function named f with arguments x_1, …, x_n and function body expr. define always evaluates its second argument (unless explicitly quoted). "[3]

return

"return doesn't mean the same thing in Maxima as it does in other programming languages. It means only to return a value from a block; that's not enough for what you need here." Robert Dodier[4]

If you wish to make a return from some expression inside the function then you must use block and return.

   block ([], expr1, ..., if (a > 10) then return(a), ..., exprn)


is itself an expression, and so could take the place of the right hand side of a function definition. Here it may happen that the return happens earlier than the last expression.

Local variables

  block ([x], expr1, ..., exprn)

The first [] in the block, may contain a list of variables and variable assignments, such as [a: 3, b, c: []], which would cause the three variables a,b,and c to not refer to their global values, but rather have these special values for as long as the code executes inside the block, or inside functions called from inside the block. This is called dynamic binding, since the variables last from the start of the block to the time it exits. Once you return from the block, or throw out of it, the old values (if any) of the variables will be restored. It is certainly a good idea to protect your variables in this way. Note that the assignments in the block variables, are done in parallel. This means, that if you had used c: a in the above, the value of c would have been the value of a at the time you just entered the block, but before a was bound. Thus doing something like:

   block ([a: a], expr1, ... a: a+3, ..., exprn)

will protect the external value of a from being altered, but would let you access what that value was. Thus the right hand side of the assignments, is evaluated in the entering context, before any binding occurs. Using just block ([x], ...) would cause the x to have itself as value, just as if it would have if you entered a fresh Maxima session.

See also description by Darren Irvine[5]

compile

  • "The modedeclare statement is important for compiled code
  • Compiling can greatly speed numerical code; for mostly symbolic code, the speed up is not great.
  • There are some differences between compiled and uncompiled code -- be careful." Barton Willis[6]


mode_declare

"mode_declare tells the compiler that the compiled code needs not to be generic enough to be able to deal with all kind of objects. If your function only takes floats, but no symbolic arguments the compiled code might run much faster." Gunter Königsmann

diff

explicit

implicit


Debugging

Directories

Start Maxima and type the command:[7]

   maxima_userdir;

this will tell you the directory that is being used as your user directory.

infolists

  • is a system variable
  • Default value: []
  • is a list of the names of all of the information lists in Maxima. These are
    • labels : All bound %i, %o, and %t labels.
    • values : All bound atoms which are user variables, not Maxima options or switches, created by : or :: or functional binding.
    • functions : All user-defined functions, created by := or define.
    • arrays : All declared and undeclared arrays, created by :, ::, or :=.
    • macros : All user-defined macro functions, created by ::=.
    • myoptions : All options ever reset by the user (whether or not they are later reset to their default values).
    • rules : All user-defined pattern matching and simplification rules, created by tellsimp, tellsimpafter, defmatch, or defrule.
    • aliases : All atoms which have a user-defined alias, created by the alias, ordergreat, orderless functions or by declaring the atom as a noun with declare.
    • dependencies : All atoms which have functional dependencies, created by the depends, dependencies, or gradef functions.
    • gradefs : All functions which have user-defined derivatives, created by the gradef function.
    • props : All atoms which have any property other than those mentioned above, such as properties established by atvalue or matchdeclare, etc., as well as properties established in the declare function.
    • let_rule_packages : All user-defined let rule packages plus the special package default_let_rule_package. (default_let_rule_package is the name of the rule package used when one is not explicitly set by the user.)

reset

reset : resets many (global) system variables

Use:

 reset()

example output :

 (%o1) [_, __, load_pathname, labels, %, linenum, ratprint, tr-unique, 
                                                     lispdisp, multiplicities]

trace

In Maxima :

:lisp (setf *debugger-hook* nil)


manual debugging

print partial results using :

  • print
  • playback

values

values:

  • is a system variable
  • is a list ... which contains the names of currently assigned scalar values which have been set by:
    • the user interactively
    • by packages which have been loaded"[8]
  • initial value is []

dependencies

dependencies :

  • is a system variable
  • is the list of atoms which have functional dependencies, assigned by:
    • depends
    • the function dependencies
    • gradef

status

 status (feature);

example output:

(%o34) [sb-bsd-sockets-addrinfo, cl, mk-defsystem, cltl2, 64-bit, 
64-bit-registers, alien-callbacks, ansi-cl, ash-right-vops, 
c-stack-is-control-stack, common-lisp, compare-and-swap-vops, 
complex-float-vops, cycle-counter, elf, float-eql-vops, 
fp-and-pc-standard-save, gencgc, ieee-floating-point, inline-constants, 
integer-eql-vop, interleaved-raw-slots, largefile, linkage-table, linux, 
little-endian, memory-barrier-vops, multiply-high-vops, os-provides-blksize-t, 
os-provides-dladdr, os-provides-dlopen, os-provides-getprotoby-r, 
os-provides-poll, os-provides-putwc, os-provides-suseconds-t, 
package-local-nicknames, precise-arg-count-error, raw-instance-init-vops, 
sb-after-xc-core, sb-core-compression, sb-doc, sb-eval, sb-futex, sb-ldb, 
sb-package-locks, sb-simd-pack, sb-source-locations, sb-test, sb-thread, 
sb-unicode, sb-xref-for-internals, sbcl, stack-allocatable-closures, 
stack-allocatable-fixed-objects, stack-allocatable-lists, 
stack-allocatable-vectors, stack-grows-downward-not-upward, symbol-info-vops, 
unix, unwind-to-frame-and-call-vop, x86-64]


Data structures

"Maxima's current array/matrix semantics are a mess, I must say, with at least four different kinds of object (hasharrays, explicit lists, explicit matrices, Lisp arrays) supporting subscripting with varying semantics. " [9]

"Maxima's concept of arrays, lists, and matrices is pretty confused, since various ideas have accreted in the many years of the project... Yes, this is a mess. Sorry about that. These are all interesting ideas, but there is no unifying framework. " [10]

Array

Maxima has two array types :[11]

  • Undeclared arrays ( implemented as Lisp hash tables )
  • Declared arrays ( implemented as Lisp arrays )
    • created by the array function
    • created by the make_array function.


Category: Arrays :

  • array
  • arrayapply
  • arrayinfo
  • arraymake
  • arrays - global variable
  • fillarray
  • listarray
  • make_array
  • rearray
  • remarray
  • subvar
  • use_fast_arrays

See also :

  • array functions defined by := and define.


Undeclared array

Assignment creates an undeclared array.

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


"If the user assigns to a subscripted variable before declaring the corresponding array, an undeclared array is created. Undeclared arrays, otherwise known as hashed arrays (because hash coding is done on the subscripts), are more general than declared arrays. The user does not declare their maximum size, and they grow dynamically by hashing as more elements are assigned values. The subscripts of undeclared arrays need not even be numbers. However, unless an array is rather sparse, it is probably more efficient to declare it when possible than to leave it undeclared. " ( from Maxima CAS doc)

"created if one does :

b[x+1]:y^2 

(and b is not already an array, a list, or a matrix - if it were one of these an error would be caused since x+1 would not be a valid subscript for an art-q array, a list or a matrix).

Its indices (also known as keys) may be any object. It only takes one key at a time (b[x+1,u]:y would ignore the u). Referencing is done by b[x+1] ==> y^2. Of course the key may be a list, e.g.

 b[[x+1,u]]:y 

would be valid. "( from Maxima CAS doc)

Declared array

  • declare array ( give a name and allocate memmory)
  • fill array
  • process array


array function

Function: array (name, type, dim_1, …, dim_n)

Creates an n-dimensional array. Here :

  • type can be fixnum for integers of limited size or flonum for floating-point numbers
  • n may be less than or equal to 5. The subscripts for the i'th dimension are the integers running from 0 to dim_i.
(%i5) array(A,2,2);
(%o5)                                  A
(%i8) arrayinfo(A);
(%o8)                      [declared, 2, [2,2]]

Because subscripts of array A elements are goes from 0 to dim so array A has :

( dim_1 + 1) * (dim_2 + 1) = 3*3 = 9 

elements.


The array function can be used to transform an undeclared array into a declared array.

arraymake function

Function: arraymake (A, [i_1, …, i_n])

The result is an unevaluated array reference.

(%i12) arraymake(A,[3,3,3]);
(%o12)                    array_make(3, 3, 3)
                                           3, 3, 3
(%i13) arrayinfo(A);
       arrayinfo: A is not an array.

Function: make_array

Function: make_array (type, dim_1, …, dim_n)

Creates and returns a Lisp array.

Type may be :

  • any
  • flonum
  • fixnum
  • hashed
  • functional.

There are n indices, and the i'th index runs from 0 to dim_i - 1.

The advantage of make_array over array is that the return value doesn't have a name, and once a pointer to it goes away, it will also go away. For example, if y: make_array (...) then y points to an object which takes up space, but after y: false, y no longer points to that object, so the object can be garbage collected.

Examples:

(%i9) A : array_make(3,3,3);
(%o9)                         array_make(3, 3, 3)
(%i10) arrayinfo(A);
(%o10)                     [declared, 3, [3, 3, 3]]

List

Assignment to an element of a list.

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


(%i1) mylist : [[a,b],[c,d]];
(%o1) [[a, b], [c, d]]

Interesting examples by Burkhard Bunk : [12]

lst: [el1, el2, ...];         contruct list explicitly
lst[2];                       reference to element by index starting from 1
cons(expr, alist);            prepend expr to alist
endcons(expr, alist);         append expr to alist
append(list1, list2, ..);     merge lists
makelist(expr, i, i1, i2);    create list with control variable i
makelist(expr, x, xlist);     create list with x from another list     
length(alist);                returns #elements
map(fct, list);               evaluate a function of one argument
map(fct, list1, list2);       evaluate a function of two arguments

Category: Lists :

  • [
  • ]
  • append
  • assoc
  • cons
  • copylist
  • create_list
  • delete
  • eighth
  • endcons
  • fifth
  • first
  • flatten
  • fourth
  • fullsetify
  • join
  • last
  • length
  • listarith
  • listp
  • lmax
  • lmin
  • lreduce
  • makelist
  • member
  • ninth
  • permut
  • permutations
  • pop
  • push
  • random_permutation
  • rest
  • reverse
  • rreduce
  • second
  • setify
  • seventh
  • sixth
  • some
  • sort
  • sublist
  • sublist_indices
  • tenth
  • third
  • tree_reduce
  • xreduce

product

/* example by Burton Willis */
(%i28) P1(s) := rectform(product(s[i],i, 1, length(s)))$

(%i29) P2(s) := xreduce(lambda([a,b], rectform(a*b)),s)$

(%i30) s : makelist(random(1.0)+%i*random(1.0),10^4)$

(%i31) P1(s);
Evaluation took 32.3080 seconds (32.3860 elapsed) using 17944.301 MB.
(%o31) 0.0

(%i32) P2(s);
Evaluation took 0.0620 seconds (0.0620 elapsed) using 8.343 MB.
(%o32) 0.0

Matrix

"In Maxima, a matrix is implemented as a nested list (namely a list of rows of the matrix)". E.g. :[13]

(($MATRIX) ((MLIST) 1 2 3) ((MLIST) 4 5 6))

Construction of matrices from nested lists :

(%i3) M:matrix([1,2,3],[4,5,6],[0,-1,-2]);
                                [ 1   2    3  ]
                                [             ]
(%o3)                           [ 4   5    6  ]
                                [             ]
                                [ 0  - 1  - 2 ]


Interesting examples by Burkhard Bunk : [14]

A: matrix([a, b, c], [d, e, f], [g, h, i]);     /* (3x3) matrix */
u: matrix([x, y, z]);                           /* row vector */
v: transpose(matrix([r, s, t]));                /* column vector */

Reference to elements etc:

u[1,2];                 /* second element of u */
v[2,1];                 /* second element of v */
A[2,3];   or  A[2][3];  /* (2,3) element */
A[2];                         /* second row of A */
transpose(transpose(A)[2]);   /* second column of A */

Element by element operations:

A + B;     
A - B;
A * B;      
A / B;
A ^ s;      
s ^ A;

Matrix operations :

A . B;                  /* matrix multiplication */
A ^^ s;                 /* matrix exponentiation (including inverse) */
transpose(A);
determinant(A);
invert(A);




Category: Matrices :[15]

  • addcol
  • addrow
  • adjoint
  • augcoefmatrix
  • cauchy_matrix
  • charpoly
  • coefmatrix
  • col
  • columnvector
  • covect
  • copymatrix
  • determinant
  • detout
  • diag
  • diagmatrix
  • doallmxops
  • domxexpt
  • domxmxops
  • domxnctimes
  • doscmxops
  • doscmxplus
  • echelon
  • eigen
  • ematrix
  • entermatrix
  • genmatrix
  • ident
  • invert
  • list_matrix_entries
  • lmxchar
  • matrix
  • matrix_element_add
  • matrix_element_mult
  • matrix_element_transpose
  • matrixmap
  • matrixp
  • mattrace
  • minor
  • ncharpoly
  • newdet
  • nonscalar
  • nonscalarp
  • permanent
  • rank
  • ratmx
  • row
  • scalarmatrixp
  • scalarp
  • setelmx
  • sparse
  • submatrix
  • tracematrix
  • transpose
  • triangularize
  • zeromatrix

Function: matrix

Function: matrix (row_1, …, row_n)

Returns a rectangular matrix which has the rows row_1, …, row_n. Each row is a list of expressions. All rows must be the same length.

. operator

"The dot operator, for matrix (non-commutative) multiplication. When "." is used in this way, spaces should be left on both sides of it, e.g.

A . B

This distinguishes it plainly from a decimal point in a floating point number.

The operator . represents noncommutative multiplication and scalar product. When the operands are 1-column or 1-row matrices a and b, the expression a.b is equivalent to sum (a[i]*b[i], i, 1, length(a)). If a and b are not complex, this is the scalar product, also called the inner product or dot product, of a and b. The scalar product is defined as conjugate(a).b when a and b are complex; innerproduct in the eigen package provides the complex scalar product.

When the operands are more general matrices, the product is the matrix product a and b. The number of rows of b must equal the number of columns of a, and the result has number of rows equal to the number of rows of a and number of columns equal to the number of columns of b.

To distinguish . as an arithmetic operator from the decimal point in a floating point number, it may be necessary to leave spaces on either side. For example, 5.e3 is 5000.0 but 5 . e3 is 5 times e3.

There are several flags which govern the simplification of expressions involving ., namely dot0nscsimp, dot0simp, dot1simp, dotassoc, dotconstrules, dotdistrib, dotexptsimp, dotident, and dotscrules." ( from Maxima CAS doc)

Vectors

Category: Vectors :

  • Vectors
  • eigen
  • express
  • nonscalar
  • nonscalarp
  • scalarp

Category: Package vect[16]

  • vect
  • scalefactors
  • vect_cross
  • vectorpotential
  • vectorsimp


Numerical methods

 "If you are doing purely numerical computation and are concerned about speed, use a compiled numerical programming language. Maxima is intended for use if you have symbolic mathematical symbols, too,
 and while it works for numbers, most components of the system are on the lookout for non-numeric inputs, and this checking takes time. 
 It is possible to speed up certain kinds of numeric computations in Maxima by using compile() and mode_declare()  together. " RJF


Newton method

Functions

  • newton for equation with function of one variable
  • mnewton is an implementation of Newton's method for solving nonlinear equations in one or more variables.

newton

load :

load("newton");
(%o1)                                                                                                   /home/a/maxima/share/numeric/newton.mac
(%i2) load("newton1");
(%o2)                                                                                                   /home/a/maxima/share/numeric/newton1.mac

Code :

/* 
 
Maxima CAS code 
from /maxima/share/numeric/newton1.mac 
input : 
 exp  =  function of one variable, x
 var = variable 
 x0 = initial value of variable
 eps = 

The search begins with x = x_0 and proceeds until abs(expr) < eps (with expr evaluated at the current value of x). 

output : xn = an approximate solution of expr = 0 by Newton's method
*/ 


newton(exp,var,x0,eps):=
block(
  [xn,s,numer],
   numer:true,
   s:diff(exp,var),
   xn:x0,
   
   loop, 
    if abs(subst(xn,var,exp))<eps 
         then return(xn),
    xn:xn-subst(xn,var,exp)/subst(xn,var,s),
   go(loop) 
)$


mnewton

Boundaries of Components of Mandelbrot set by Newton method. Image and Maxima CAS code

One can use Newton method for solving systems of multiple nonlinear functions. It is implemented in mnewton function. See directory :

/Maxima..../share/contrib/mnewton.mac

which uses linsolve_by_lu defined in :

 /share/linearalgebra/lu.lisp

See this image for more code.

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


Algorithms

Vectors made with Maxima CAS

Stack implementation using list:


/* create stack */
stack:[1];
/* push on stack */
stack:endcons(2,stack);
stack:endcons(3,stack);
block
(
  loop,
  stack:delete(last(stack),stack), /* pop from stack */
  disp(stack), /* display */
  if is(not emptyp(stack)) then go(loop)
);
stack;


Plots

Complex Functions

  • Visualizing Complex Functions with Conformal Mapping ( themaximalist ) [17]

Topologist's sine curve

plot2d (sin(1/x), [x, 0, 1])$

Topologist's comb :

Topologist's comb
load(draw); /* by Mario Rodríguez Riotorto  http://riotorto.users.sourceforge.net/gnuplot/index.html  */

draw2d(
 title     = "Topologist\\47s comb", /* Syntax for postscript enhanced option; character 47 = '  */
 xrange        = [0.0,1.2],
 yrange        = [0,1.2],
 file_name = "comb2",
 terminal      = svg,
 points_joined = impulses, /* vertical segments are drawn from points to the x-axis  */
 color         = "blue",
 points(makelist(1/x,x,1,1000),makelist(1,y,1,1000)) )$



Outputs and warnings

  • ratprint : false; /* remove "rat :replaced " */
  • using $ instead of ; at the end of the line ( not inside function where , ends the line )
  • return from the function
  • "warning: encountered undefined variable ... in translation." This is warning from compile when function uses global variable without using in in tha arguments list. You have to include the variables in the function's list


Example programs

  • Iteration of complex numbers, stack and drawing a list of points
Julia set using IIM
  • Iteration of complex numbers, comparing complex numbers, finding period of cycle
critical orbit with 3-period cycle
  • Drawing Julia set and critical orbit. Computing period
Drawing Julia set and critical orbit. Computing period
  • drawing curves in 2D plane
Mandelbrot lemniscates-image and source
  • drawing points
Drawing 2D points. Image and source code


Weaknesses of math software

While Maxima is a very useful software, it suffers from the same issues faced by many other math programs.

  • The limit of a discontinuous function at the point of discontinuity[18]
  • Branch cuts[19]
  • Zero-recognition
  • Keeping track of domains of validity

References


Help

bash

  • info maxima

Maxima commands

  • dependencies
  • infolists
  • describe
  • ??