On Coding X: Computer Graphics II

Now that I’ve talked about what I use computer graphics for in my last installment of On Coding, I’d like to talk about the most useful graphics package I’ve come across for writing mathematics:  TikZ.

First a word about the name, TikZ.  It’s an example of a recursive acronym, like GOD used in Douglas Hofstadter’s Gödel, Escher, Bach, which stands for “GOD Over Djinn.”  (By the way, read Gödel, Escher, Bach if you haven’t already — it’s an amazing book about Gödel’s Incompleteness Theorem.)

So TikZ stands for “TikZ ist kein Zeichenprogramm,” which is German for “TikZ is not a drawing program.”  According to its creator, Till Tantau, this indicates that TikZ is not a way to draw pictures with your mouse or tablet, but is more like a computer graphics language.  It is designed for use in LaTeX, and is built with a lower-level language called PGF, which stands for “portable graphics format.”

So enough history — you can read more in the TikZ manual.  But a word of caution — it’s over 1000 pages long, so there’s a lot there!  I’ll only be able to scratch the surface today.

The two most important features of TikZ, in my opinion, are (1) you can draw very precise graphics because you’re writing in a high-level langauge, not using a WYSIWYG environment, and (2) you can use it in LaTeX, including putting any LaTeX symbols in your graphics.  This second point is extremely important, since it means when you’re labelling a diagram, the labels (usually involving mathematical symbols) look exactly the same way as the do in your text.

I use TikZ almost exclusively for two-dimensional mathematical graphics.  In a recent paper, for example, I created the following image.

tikzexamples

Note how precisely all the elements are rendered — this is because you give precise coordinates for all the individual graphics elements.

Let’s take a look at another, somewhat simpler example from this paper.

tikzexamples2

I chose this example for a few reasons.  First, it requires using a lot of the basic TikZ commands.  Second, it illustrates the practical side of drawing computer graphics.  No, I’m not going to submit this image to a Bridges art exhibition any time soon — but if I need to make an image for a paper, I want it to look good.

So I thought I’d take some time to explain various aspects of the code which creates this image.  Maybe not the most glamorous graphic — but you’re welcome to look at the 1000+ page manual for hundreds of neat examples.  Here is a diagram for a finite-state automaton from page 179, for example.

 

tikzpgfmanual2

Here’s what you’d need to type in LaTeX to get the simple graph I mentioned a moment ago.

tikz

Let’s look at several different excerpts from this example.  The first line opens your TikZ environment, and scales the image.  The default unit is 1 cm, so you need to set the scale to get your image the right size.

The next line is just a comment — I don’t use comments much for simple images.  But for more complex images, they’re important.  Just as important as commenting computer code.

The next line draws a set of axes.  What’s important here is that I defined my own “\axes” command — so you can include user-defined functions as well.  The advantages of being able to do this are huge.  You can use any command you define in LaTeX in a TikZ image.

Another great feature is the looping construct, “\foreach.”  The red segments above are one unit long, and so the only difference is the starting points.  Also important here is that you can use mathematical expressions inside TikZ, like the “{(\x^2+9)/6}” expression in the curly brackets.

Note the directives “[thick, red]” after the “draw” command.  You have control over every aspect of the drawing routines in TikZ — and there are lots of them.  For example, there is the “dashed” directive in line 10.  But not only can you draw a dashed line, but you can also specify the lengths of the dash marks and the spaces between them, too!  Further, you can create user-defined styles if you use the same set of directives over and over again.  This is helpful if you are creating several related images, and you want to tweak the color, for example.  You only have to change the color specification in the style, and every image which uses that style will be rendered using the new color.

Notice the “\filldraw” command in line 6.  I wanted open circles, so I drew the circles in red, and filled them with white.  If I wanted to, I could have also specified precisely how thick I wanted the circles to be drawn, but the default thickness looked just fine to me.

Notice the use of “node” and “\node” throughout.  In line 9, for example, the “3” is centered at coordinates (3, -0.5).  Also note the placement of nodes at the end of line segments, as shown in lines 7 and 8.  Again, it is significant that you can include any text you can create in LaTeX in your diagram.

I hope this is enough to give you the feel of using TikZ.  As I mentioned in the last installment, I also use TikZ to create slideshow presentations since there is so much you can do.  Remember, there are over 1000 pages of examples of things you can do in TikZ in the manual.

I would like to mention one caveat, however.  I do sometimes use Mathematica to create images with mathematically intensive equations and calculations.  TikZ is closer to a markup language in its usage, as I see it — so any image that requires significant coding to produce is a bit too cumbersome syntactically.  Here is an example of an image I used Mathematica to create.

Figure1.png

But another nice TikZ feature is that you can import images into your environment — so I can draw complex images in Mathematica, include them in my TikZ picture, and then overlay LaTeX symbols on top of the image.  With this capability, the possibilities are quite literally endless.

A final comment:  TikZ and LaTeX are both open source, so if you’re interested, you can just download them and start experimenting!  The learning curve is a little steep, admittedly, but once you’ve climbed up, you’ll be able to create astonishingly beautiful graphical images for any purpose you have in mind.  Try it!

 

The One Four Conjecture

I can’t remember when I first heard of the “Four Fours” puzzle.  The goal is to use four 4’s to create as many different integers as possible using basic arithmetic operations.  For example,

42=44-\dfrac4{\sqrt 4}.

Which numbers are possible to obtain depends on the range of operations or functions allowed.  Using a decimal point and a bar for a repeating decimal, for example, allows expressions such as

103=\dfrac{44}{.\overline 4}+4.

You can read more about this puzzle on this Wikipedia page, and look at the references there for even more information.

A few years ago, I wondered about what numbers are possible using just one 4.  Of course there aren’t many if you restrict yourself to the basic arithmetic operations.  But you can write 4!= 24, for example.

So the factorial was a way to make numbers larger, but then what about bringing those factorials back down?  The square root function does that, but then you need to convert to an integer.  So perhaps use the floor function, so that the second function you use is

f(n)=\lfloor\sqrt n\rfloor.

Now this is a bit trickier — even small numbers are not so easy to obtain.  For example,

5=\left\lfloor\sqrt{\left\lfloor\sqrt{\left\lfloor\sqrt{\left\lfloor\sqrt{\left\lfloor \sqrt{(4!)!}\right\rfloor}\right\rfloor}\right\rfloor}\right\rfloor}\right\rfloor.

That’s a lot of work just to get 5….  But as I kept on exploring using Mathematica, it seemed that eventually, you could get every positive integer this way!

At first, it was really hard to believe — but the more I worked, the more plausible it became.  It soon became obvious that other numbers other than 4 were possible to begin with.  You could start with 9, for example, since then you could get 4 by

4=\left\lfloor\sqrt{\left\lfloor\sqrt{\left\lfloor \sqrt{9!}\right\rfloor}\right\rfloor}\right\rfloor,

and then proceed from there.

Further, why use a square root?  Could other roots work as well?  More experimentation seemed to suggest that any root might also work.  This led me to the following:

The One n Conjecture:  Suppose n>2 and p>1 are given.  Then using the factorial function and the function

f(n)=\lfloor n^{1/p}\rfloor,

all positive integers may be obtained by some composition of these functions.

This seemed really difficult to prove.  Suppose, for example — using the factorial and square root functions — it is impossible to obtain some particular integer no matter what input you start with.  Of course it is always possible to obtain n from n^2, and n^2 from n^4, and so on, but you’ve got to get larger first, and that requires some use of the factorial.

It turns out, however — in a particular sense (which you’ll see in a moment) — it is always possible, for any p.

The Possibility Lemma:  Suppose p>1 is given.  Then for any positive integer k>1, there exist positive integers q,m such that

k=f(f(f\cdots f(m!)),

where the function f is composed q times.

Let’s focus on the square root for now — that is, p=2.  The Possibility Lemma is only a starting point, since it turns out that most of the time, the smallest m need to generate a particular k is actually greater than k — making an induction proof based on the Lemma impossible.

For example, for k=42, the smallest m is 218 with q=8, so that

42=f(f(f(f(f(f(f(f(218!)))))))).

But for k=43, we get

43=\left\lfloor\sqrt{\left\lfloor \sqrt{10!}\right\rfloor}\right\rfloor.

It seemed that the least m needed to generate a given k exhibited rather erratic behavior.  So my next step was to plot a graph of the least m given k.

I won’t go into all the details here — but it took a little work to optimize the algorithms.  As an example, the smallest m needed to generate k=48,\!500 is m=890,\!827, and computations with such large factorials take time.  It turns out that the trick was to compute in advance the first 1,000,000 factorials as floating point numbers.  A little accuracy is lost as result, but several checks suggested that even so, the correct value of m is found each time.

So here is the plot of values for the least possible m for k from 1 to 5,000.

OneFour5000

And here’s the plot for values of k from 1 to 40,000.

OneFour40000

Now here’s something interesting!  You can’t help but think “fractal behavior” here.  And why the thin bands?  Not sure yet, but they somehow correspond to square roots of factorials.  For example, the m for 49,998 is 470,324, and the m for 49,999 is 248,312, and the square root of 470,324! is not too far off from 248,312!.

But although it looks like there are thin bands, they are not uniformly generated.  Here’s a closeup of the previous graph in the range 49,900 to 50,000.

OneFour100.png

There doesn’t seem to be a predictable pattern as to when the jumps are made.

And it does appear that the thin bands have an upward trend.  Might it be possible that every positive integer is eventually the m for some k?  Not an easy question to answer.

And this is only a beginning!  I just generated the graph up to 50,000 yesterday, so I haven’t had time to analyze it in any more detail.  Using p=3 generates the following graph, so it seems that there may be similar behavior for various p.

OneFour5000p3

I plan to keep working on this little puzzle — although I think a proof of or counterexample to the One n Conjecture is rather far off.  When I do make more progress, I’ll give you an update.  Despite the difficulty of the problem, this is a really fun puzzle to play with!  I hope you might give it a try, too….

Guest Blogger: Percival Q. Plumtwiddle, II

As promised, here is the second installment of my friend Percy’s essay on the significance of our Earthly existence being three-dimensional.  I hope these few words give food for much geometrical thought….

On Threeness (continued…)

Popping over a few dimensions in the meanwhile, the knowledgeable geometer is certainly aware that in dimension four and, indeed, in all dimensions exceeding this critical dimension, the situation is somewhat overwhelming, to say the least. So many thousands of uniform polyhedra abound that the prospect of their enumeration appears beyond the scope of even the most ambitious geometer. (I might recommend such a project, however, to an advanced practitioner of one of the Eastern religions who might, as a result of sufficient spiritual development, continue the undertaking in subsequent reincarnations.)

But in dimension three, how manageable our delight!  Seventy-odd uniform polyhedra clog the pores, multitudinous compounds and stellations frolic with the celestial spheres, etc.,  such as to render the average mortal awestruck.  Details are, of course, voluminous (though within reason), and more eminent geometers than yours truly have authored copious memoranda on said frolicking.  And there is yet much left unsaid, or perhaps, unmemorandized.  To presume that our friendly Supreme B. was unaware of such phantasmagoria would be heresy first class.  Fie!, I say, to such presumption!

As convincing as I have striven to be, I shall endeavor, with difficulty, not to be so narcissistic as to suppose that I have left no room for doubt in the reader’s mind. And so I entice with a few non-Euclidean morsels…

I shall not doubt the reader’s familiarity with the method for calculating the length of a circular arc, given the appropriate parameters. Perhaps less well-known is the method for calculating the area of a spherical triangle, with the attendant formulae relating the various parts of such a triangle only slightly more obscure. I purposefully omit their statements, secretly hoping that the reader will rediscover their simplicity and elegance afresh… In any case, the knowledgeable reader is well acquainted with the vast number of beautiful yet stable geodesic structures which may be constructed, the data for which constructions being directly calculated by way of the aforementioned simple formulae. Let not the skeptical reader be amused by such hyperbole — for one who has indeed fabricated such a structure or two with a few sheets of stiff paper and a bit of rubber cement will certainly view my descriptions as grave understatement.

In any event, as the informed reader is well aware, the formula for finding the area of the spherical triangles mentioned above may be successfully implemented by a child of ten, or perhaps a precocious child of eight, with a minimum of instruction, a pocket calculator, and, if necessary, the promise of an ice cream in the event of their successful completion. The informed reader is equally well aware that analogous calculations in four dimensions may be successfully implemented by no less that a ranking member of the cranially elite given the necessary data (and perhaps a few extraneous ones for good luck), a personal computer, and, if necessary, the promise of tenure in the event of their successful calculation. The superiority of the three-dimensional scenario, both fiscally and otherwise, is evident.

I pause, as a prelude to a conclusion, to ask the reader to reflect upon his or her stance vis a vis the proposed heightened status of Threeness. I imagine the reader to be of one of four minds. First, the reader may be insufferably bored at the current exegesis, in which case he or she will have undoubtedly ceased its perusal long ago. In this case, there is no reason for a continuation of discourse. Secondly, the reader may, to my ineffable delight, be wholly in agreement with the propositions contained herein. Should this be the case, I am not compelled to offer further justification for them. Thirdly, the reader may, to my profound disappointment, be immovably opposed to my thesis. (As an apology to those readers who fall in the second category, I must, rather that be labelled as a righteous fanatic, admit this frankly incomprehensible possibility.) I would not prolong the displeasure of such readers, those that there may be. Fourthly, the reader may be genuinely undecided, perhaps having never mused upon such matters previously, or perhaps still wrestling with deep foundational issues and at an impasse with regard to their resolution. In the former case, I urge an immediate excursion to that local library known for its excellent collection of volumes on the subject, followed by a thorough study of those treatises, and then a rereading of the current manuscript. In the latter case, I believe the matter rather more philosophical than mathematical, and I might suggest several worthwhile Buddhist sources (and caution the reader to avoid the twentieth-century European existentialists). In neither case would I find a need to argue further in this matter of Threeness.

And so, dear reader, I take my leave. It is my fondest hope that these few words have, at the very least, given cause for a leisurely intellectual frolic amidst sunny geometrical meadows, and at the very best, profoundly elevated the spirit. In either case, my work will not have been in vain.

Guest Blogger: Percival Q. Plumtwiddle, I

As I’m out of town for a few weeks, I thought I’d invite my good friend Percy Plumtwiddle to be a guest blogger.  He is an ardent enthusiast of geometry, and we have had many animated discussions on the geometry of three and higher dimensions.

But he has his stubborn side (don’t we all?).  And yes, his language is flowery and over the top, but well, we all have our eccentricities, too.  Nonetheless, he makes some interesting points — just how interesting, I’ll have to let you decide.

Also, his essay, while not too long, is a bit long for just one post — so I’ll break it into two installments.  I’ll return to my keyboard in a few weeks.  In the meantime, enjoy Percy’s unique perspective on geometry, and more broadly, life in general….

On Threeness

Were I God — and I assure you, dear reader, that such is not remotely an aspiration; and were it, even my dear friends and those who hold me in highest esteem (those that there may be) would chortle audibly at the consideration of such a prospect — and were it incumbent upon me to create a sentient being or two (admittedly, I would be somewhat embarrassed, were I God, to admit to the creation of many such beings which presently spoil an otherwise hospitable planet) — and had I the necessity of establishing a place of residence for the aforementioned sentient beings (not that it would be required, matter being at times inconvenient, especially when taking the form of a piece of chocolate cake hidden under one’s outer garments at the precise moment when a head-on collision with a rotund nephew is imminent) — I would not hesitate for a moment in making such a domicile, in dimension, three.

Lest the frivolous reader imagine such a dimensionality to be merely the whim of a somewhat eccentric, although omniscient, Supreme Being, or lest the pious reader imagine that such a dimensionality foreshadows the fairly recent (according to even the most conservative of cosmological estimates) doctrine of the Trinity popular in some Western religions, and lest the banal reader imagine that this third dimesion would be, as goes the cliche, a “charm,” and lest the reader of belles lettres be tempted to make a thoroughly trite reference to MacBeth — apply the cerebral brakes forthwith!  I intend to provide sound reason to dispel such imaginations, should the reader find it bearable to forage among slightly less green pastures.

I appeal not only to the reader’s intellect — being, unfortunately, acquainted much more intimately with self-proclaimed members of the cranially elite than I presently desire — but also to the reader’s aesthetic sensibilities, as potentially volatile as such an appeal may be.  But I have profound faith in this universal Threeness, so I proceed, fully cognizant of the perilous quagmire in which I may soon find myself immersed, should the fates allow.

Indeed, my argument is entirely geometrical, being of the school of thought that such argumentation is lacking in no essentials.  Should the reader be otherwise disposed, I urge an immediate cessation of the perusal of this document, the administration of a soothing tonic, and perhaps the leisurely reading of a light novella.

Several remarks of the Euclidean persuasion present themselves.  Oh, indeed, we are all familiar with the usual formulae for distance, angle, etc., etc.  These pose little difficulty, even in thirty-seven dimensions, once we are introduced to our good friend the Greek capital sigma.

But let us turn our eyes to the imaginitive world of polyhedra, a subject quite dear to my heart.  Another discussion entirely!  It is within this discussion that the force of my words comes to bear.  For indeed, I should be greatly surprised if when, upon strolling through the Pearly Gates and bidding good-day to St. Pete, I find that God did not have amongst his cabinet (a gaggle of geese, perhaps, but the precise nomenclature for an approbriation of Archangels momentarily eludes me) one for whom polyhedra are a consuming passion.

And what would give cause for raised eyebrows?  Follow along.  Examining your regular polyhedra of dimension two, we find squares, triangles, etc., etc., and, while these are no doubt pleasing to the eye, one might find oneself a trifle bored after pondering a polygon of forty-six sides.  For next comes the all-too-exciting forty-seven sider, and while one might appear to the casual observer nonplussed, the more astute attendant of human psychology would undoubtedly sense a consuming ennui.  Hardly worthy of God, or even a lesser member of his cabinet.  Of course, one may counter that I have neglected the likes of five-pointed stars, nineteen-pointed stars, and eighty-five-pointed stars, and one would be correct.  But these, too, soon become tiresome.

This ends the first installment of Percy Plumtwiddle’s essay, On Threeness.  Be sure to catch the second (and final) installment next week!