printfmaxima

maxima : printing a nice table ala printf


maxima beginner question: how do I print a nice fixed format table, such as (R code):

> for (i in 1:5) printf("%4d\t%7.3f\t%s\t%12.5f\n", i, sqrt(i), paste0("C",i), exp(i))
   1      1.000 C1       2.71828
   2      1.414 C2       7.38906
   3      1.732 C3      20.08554
   4      2.000 C4      54.59815
   5      2.236 C5     148.41316

advice appreciated.


Solution

  • There is a printf function in Maxima, which produces formatted output, mostly by punting to the function FORMAT in the Common Lisp implementation. A web search for "Common Lisp Hyperspec FORMAT" will find the spec for that.

    FORMAT, and therefore printf, marks format specifiers with tilde instead of percent sign. The arguments for the format specifiers are similar but different than in C or other languages; see the CLHS for details.

    There are a few specifiers for Maxima which aren't in the CLHS. ~m displays a Maxima expression as in the pretty printer, and ~h displays a bigfloat, if I remember correctly.

    The format string you showed might be equivalent to this (I didn't test it):

    for i: 1 thru 5
        do printf (true, "~4d~0,8t~7,3f~0,8t~a~0,8t~12,5f~%", i, float (sqrt (i)), sconcat ("C", i), float (exp (i)));
    

    But many times I just put stuff in a matrix and then the Maxima pretty printer aligns stuff pretty well without any further effort on my part.