REXML could not parse this XML/HTML: <script type="text/javascript"> window.MathJax && MathJax.Hub.Queue(["Typeset",MathJax.Hub]); Acko.queue(function () { Acko.Fallback.warnWebGL(); }); </script>

“It is known that there are an infinite number of worlds, simply because there is an infinite amount of space for them to be in. However, not every one of them is inhabited. Therefore, there must be a finite number of inhabited worlds.

Any finite number divided by infinity is as near to nothing as makes no odds, so the average population of all the planets in the universe can be said to be zero. From this it follows that the population of the whole universe is also zero, and that any people you may meet from time to time are merely the products of a deranged imagination.”– The Restaurant at the End of the Universe, Douglas Adams

If there's one thing mathematicians have a love-hate relationship with, it has to be *infinity*. It's the ultimate tease: it beckons us to come closer, but never allows us anywhere near it. No matter how far we travel to impress it, infinity remains disinterested, equally distant from everything: infinitely far!

$$ 0 < 1 < 2 < 3 < … < \infty $$

Yet infinity is not just desirable, it is absolutely necessary. All over mathematics, we find problems for which no finite amount of steps will help resolve them. Without infinity, we wouldn't have real numbers, for starters. That's a problem: our circles aren't round anymore (no $ π $ and $ \tau $) and our exponentials stop growing right (no $ e $). We can throw out all of our triangles too: most of their sides have exploded.

A steel railroad bridge with a 1200 ton counter-weight.

Completed in 1910. Source: Library of Congress.

We like infinity because it helps avoid all that. In fact even when things are not infinite, we often prefer to pretend they are—we do geometry in infinitely big planes, because then we don't have to care about where the edges are.

Now, suppose we want to analyze a steel beam, because we're trying to figure out if our proposed bridge will stay up. If we want to model reality accurately, that means simulating each individual particle, every atom in the beam. Each has its own place and pushes and pulls on others nearby.

But even just $ 40 $ grams of pure iron contains $ 4.31 \cdot 10^{23} $ atoms. That's an inordinate amount of things to keep track of for just 1 teaspoon of iron.

Instead, we pretend the steel is solid throughout. Rather than being composed of atoms with gaps in between, it's made of some unknown, filled in material with a certain density, expressed e.g. as *grams per cubic centimetre*. Given any shape, we can determine its volume, and hence its total mass, and go from there. That's much simpler than counting and keeping track of individual atoms, right?

Unfortunately, that's not quite true.

Like all choices in mathematics, this one has consequences we cannot avoid. Our beam's density is *mass per volume*. Individual points in space have zero volume. That would mean that at any given point inside the beam, the amount of mass there is $ 0 $. How can a beam that is entirely composed of nothing be solid and have a non-zero mass?

*Bam! No more iron anywhere.*

While Douglas Adams was being deliberately obtuse, there's a kernel of truth there, which is a genuine paradox: what exactly is the mass of every atom in our situation?

To make our beam solid and continuous, we had to shrink every atom down to an infinitely small point. To compensate, we had to create infinitely many of them. Dividing the finite mass of the beam between an infinite amount of atoms should result in $ 0 $ mass per atom. Yet all these masses still have to add up to the total mass of the beam. This suggests $ 0 + 0 + 0 + … > 0 $, which seems impossible.

If the mass of every atom were not $ 0 $, and we have infinitely many points inside the beam, then the total mass is infinity times the atomic mass $ m $. Yet the total mass is finite. This suggests $ m + m + m + … < \infty $, which also doesn't seem right.

It seems whatever this number $ m $ is, it can't be $ 0 $ and can't be non-zero. It's definitely not infinite, we only had a finite mass to begin with. It's starting to sound like we'll have to invent a whole new set of numbers again to even find it.

That's effectively what Isaac Newton and Gottfried Leibniz set in motion at the end of the 17th century, when they both discovered calculus independently. It was without a doubt the most important discovery in mathematics and resulted in formal solutions to many problems that were previously unsolvable— our entire understanding of physics has relied on it since. Yet it took until the late 19th century for the works of Augustin Cauchy and Karl Weierstrass to pop up, which formalized the required theory of *convergence*. This allows us to describe exactly how differences can shrink down to nothing as you approach infinity. Even that wasn't enough: it was only in the 1960s when the idea of infinitesimals as fully functioning numbers—the hyperreal numbers—was finally proven to be consistent enough by Abraham Robinson.

But it goes back much further. Ancient mathematicians were aware of problems of infinity, and used many ingenious ways to approach it. For example, $ π $ was found by considering circles to be infinite-sided polygons. Archimedes' work is likely the earliest use of *indivisibles*, using them to imagine tiny mechanical levers and find a shape's center of mass. He's better known for running naked through the streets shouting Eureka! though.

That it took so long shows that this is not an easy problem. The proofs involved are elaborate and meticulous, all the way back. They have to be, in order to nail down something as tricky as infinity. As a result, students generally learn calculus through the simplified methods of Newton and Leibniz, rather than the most mathematically correct interpretation. We're taught to mix notations from 4 different centuries together, and everyone's just supposed to connect the dots on their own. Except the trail of important questions along the way is now overgrown with jungle.

Still, it shows that even if we don't understand the whole picture, we can get a lot done. This article is in no way a formal introduction to infinitesimals. Rather, it's a demonstration of why we might need them.

What is happening when we shrink atoms down to points? Why does it make shapes solid yet seemingly hollow? Is it ever meaningful to write $ x = \infty $? Is there only one infinity, or are there many different kinds?

To answer that, we first have to go back to even simpler times, to Ancient Greece, and start with the works of Zeno.

Zeno of Elea was one of the first mathematicians to pose these sorts of questions, effectively trolling mathematics for the next two millennia. He lived in the 5th century BC in southern Italy, although only second-hand references survive. In his series of paradoxes, he examines the nature of equality, distance, continuity, of time itself.

Because it's the ancient times, our mathematical knowledge is limited. We know about zero, but we're still struggling with the idea of nothing. We've run into negative numbers, but they're clearly absurd and imaginary, unlike the positive numbers we find in geometry. We also know about fractions and ratios, but square roots still confuse us, even though our temples stay up.

Limits are the first tool in our belt for tackling infinity. Given a sequence described by countable steps, we can attempt to extend it not just to the end of the world, but literally forever. If this works we end up with a finite value. If not, the limit is undefined. A limit can be equal to $ \infty $, but that's just shorthand for *the sequence has no upper bound*. Negative infinity means no lower bound.

Until now we've only encountered fractions, that is, *rational numbers*. Each of our sums was made of fractions. The limit, if it existed, was also a rational number. We don't know whether this was just a coincidence.

It might seem implausible that a sequence of numbers that is 100% rational and converges, can approach a limit that isn't rational at all. Yet we've already seen similar discrepancies. In our first sequence, every partial sum was *less than* $ 1 $. Meanwhile the limit of the sum was *equal to* $ 1 $. Clearly, the limit does not have to share all the properties of its originating sequence.

We also haven't solved our original problem: we've only chopped things up into infinitely many *finite pieces*. How do we get to *infinitely small pieces*? To answer that, we need to go looking for *continuity*.

Generally, continuity is defined by what it is and what its properties are: a noticeable lack of holes, and no paradoxical values. But that's putting the cart before the horse. First, we have to show which holes we're trying to plug.

REXML could not parse this XML/HTML: <div class="wide slideshow full"> <div class="iframe c"> <iframe src="/files/infinity-and-beyond/mb-5-continuity.html" class="mathbox paged autosize" height="320"></iframe> </div> <div class="steps"> <div class="step"> <p>Let's imagine the <em>rational numbers</em>.</p> </div> <div class="step"> <p>Actually, hold on. Is this really a line? The integers certainly weren't connected.</p> </div> <div class="step"> <p class="math">Rather than assume anything, we're going to attempt to visualize all the rational numbers. We'll start with the <span class="blue">numbers between $ 0 $ and $ 1 $</span>.</p> </div> <div class="step"> <div class="extra bottom"><big>$$ \class{blue}{\frac{0 + 1}{2}} $$</big></div> <p class="math">Between any two numbers, we can find a new number in between: their average. This leads to $ \frac{1}{2} $.</p> </div> <div class="step"> <div class="extra bottom"><big>$$ \frac{a + b}{2} $$</big></div> <p>By repeatedly taking averages, we keep finding new numbers, filling up the interval.</p> </div> <div class="step"> <p>If we separate out every step, we get a <em>binary tree</em>.</p> </div> <div class="step"> <p class="math">You can think of this as a map of all the fractions of $ 2^n $. Given any such fraction, say <big>$ \frac{13}{32} = \frac{13}{2^5} $</big>, there is a unique path of lefts and rights that leads directly to it. At least, as long as it lies between $ 0 $ and $ 1 $.</p> </div> <div class="step"> <p class="math"> Note that the graph resembles a fractal and that the distance to the top edge is divided in half with every step. But we only ever explore a finite amount of steps. Therefor, we are not taking a limit and we'll never actually touch the edge. </p> </div> <div class="step"> <div class="extra left" data-hold="1">$$ \frac{2 \cdot a + b}{3} $$</div> <div class="extra right" data-hold="1">$$ \frac{a + 2 \cdot b}{3} $$</div> <p class="math">But we can take thirds as well, leading to fractions with a power of $ 3^n $ in their denominator.</p> </div> <div class="step"> <p class="math">As some numbers can be reached in multiple ways, we can eliminate some lines, and end up with this graph, where every number sprouts into a three-way, <em>ternary tree</em>. Again, we have a map that gives us a unique path to any fraction of $ 3^n $ in this range, like <big>$ \frac{11}{27} = \frac{11}{3^3} $</big>.</p> </div> <div class="step"> <div class="extra"> $$ \frac{21}{60} = \frac{21}{2^2 \cdot 3 \cdot 5} $$ </div> <p class="math">Because we can do this for any denominator, we can define a way to get to any rational number in a finite amount of steps. Take for example <big>$ \frac{21}{60} $</big>. We decompose its denominator into prime numbers and begin with $ 0 $ and $ 1 $ again.</p> </div> <div class="step"> <div class="extra top edge hold3"> <small><small> $$ \frac{21}{60} = \frac{21}{2^2 \cdot 3 \cdot 5} $$ </small></small> </div> <p class="math">There is a division of $ 2^2 $, so we do two binary splits. This time, I'm repeating the previously found numbers so you can see the regular divisions more clearly. We get <span class="green">quarters</span>.</p> </div> <div class="step"> <p class="math">The next factor is $ 3 $ so we divide into thirds once. We now have <span class="gold">twelfths</span>.</p> </div> <div class="step"> <p class="math">For the last division we chop into fifths and get <span class="orangered">sixtieths</span>.</p> </div> <div class="step"> <p class="math">$ \frac{21}{60} $ is now the <span class="orangered">21st number from the left</span>.</p> </div> <div class="step"> <p class="math">But this means we've found a clear way to visualize <em>all</em> the rational numbers between $ 0 $ and $ 1 $: it's all the numbers we can reach by applying a finite number of binary (2), ternary (3), quinary (5) etc. divisions, for any denominator. So there's always a finite <em>gap</em> between any two rational numbers, even though there are infinitely many of them.</p> </div> <div class="step"> <p>The rational numbers are <em>not continuous</em>. Therefor, it is more accurate to picture them as a set of tick marks than a connected number line.</p> </div> <div class="step"> <p class="math">To find continuity then, we need to revisit one of our earlier trees. We'll pick the binary one.<br />While every fork goes two ways, we actually have a third choice at every step: we can choose to stop. That's how we get a finite path to a whole fraction of $ 2^n $.</p> </div> <div class="step"> <p>But what if we never stop? We have to apply a limit: we try to spot a pattern and try to <span class="green">fast-forward it</span>. Note that by halving each step vertically on the graph, we've actually <em>linearized</em> each approach into a straight line which ends. Now we can <em>take limits visually</em> just by intersecting lines with the top edge.</p> </div> <div class="step"> <p class="math">Right away we can spot two convergent limits: by always choosing either the <span class="orangered">left</span> or the <span class="green">right</span> branch, we end up at respectively $ 0 $ and $ 1 $.</p> </div> <div class="step"> <p class="math"><span class="orangered">These</span> <span class="green">two</span> sequences both converge to $ \frac{1}{2} $. It seems that 'at infinity steps', the graph meets up with itself in the middle.</p> </div> <div class="step"> <p class="math">But the graph is now a true fractal. So the same convergence can be found here. In fact, the graph meets up with itself anywhere there is a multiple of <big>$ \frac{1}{2^n} $</big>.</p> </div> <div class="step"> <p class="math">That's pretty neat: now we can eliminate the option of stopping altogether. Instead of ending at $ \frac{5}{16} $, we can simply take <span class="purple">one additional step in either direction, followed by infinitely many opposite steps</span>. Now we're <em>only</em> considering paths that are infinitely long.</p> </div> <div class="step"> <p class="math">But if this graph only leads to fractions of $ 2^n $, then there must be gaps between them. In the limit, the distance between any two adjacent numbers in the graph shrinks down to <em>exactly</em> $ 0 $, which suggests there are no gaps. This infinite version of the binary tree must lead to a lot more numbers than we might think.<br /> Suppose we take a path of <span class="orangered">alternating left and right steps</span>, and extend it forever. Where do we end up?</p> </div> <div class="step"> <p>We can apply the same principle of an <span class="gold">upper and lower bound</span>, but now we're approaching from both sides at once. Thanks to our linearization trick, the entire sequence fits snugly inside a triangle.</p> </div> <div class="step"> <p class="math">If we zoom into the convergence at infinity, we actually end up at $ \class{orangered}{\frac{2}{3}} $.<br /> Somehow we've managed to coax a fraction of $ 3 $ out of a perfectly regular <em>binary</em> tree.</p> </div> <div class="step"> <p class="math">If we <span class="orangered">alternate two lefts with one right</span>, we can end up at $ \class{orangered}{\frac{4}{7}} $. This is remarkable: when we tried to visualize all the rational numbers by combining all kinds of divisions, we were overthinking it. We only needed to take <em>binary divisions</em> and repeat them infinitely with a <em>limit</em>.</p> </div> <div class="step"> <p>Every single rational number can then be found by taking a finite amount of steps to get to a certain point, and then settling into a <em>repeating pattern of lefts and/or rights</em> all the way to infinity.</p> </div> <div class="step"> <p class="math">If we can find numbers between $ 0 $ and $ 1 $ this way, we can apply the exact same principle to the range $ 1 $ to $ 2 $. So we can connect two of these graphs into a single graph with its tip at $ 1 $.</p> </div> <div class="step"> <p class="math">But we can repeat it as much as we like. The full graph is not just infinitely divided, but infinitely big, in that no finite box can contain it. That means it leads to <em>every single positive rational number</em>. We can start anywhere we like. Is your mind blown yet?</p> </div> <div class="step"> <p class="math">No? Ok. But if this works for positives, we can build a similar graph for the negatives just by mirroring it. So we now have a map of the entire rational number set. All we need to do is take <em>infinite paths that settle into a repeating pattern</em> from either a positive or a negative starting point. When we do, we find every such path leads to a rational number.<br /> So any rational number can be found by taking an infinite stroll on one of <em>two</em> infinite binary trees.</p> </div> <div class="step"> <p class="math">Wait, did I say two infinite trees? Sorry, I meant <em>one</em> infinitely big tree.<br />See, if we repeatedly scale up a <span class="green">fractal binary tree</span> and apply a limit to that, we end up with almost exactly the same thing. Only this time, the two downward diagonals always eventually fold back towards $ 0 $. This creates a path of <em>infinity + 1</em> steps downward. While that might not be very practical, it suggests you can ride out to the restaurant at the end of the universe, have dinner, and take a single step to get back home.</p> </div> <div class="step"> <p class="math">Is it math, or visual poetry? It's time to bring this fellatio of the mind to its inevitable climax.</p> </div> <div class="step"> <div class="extra hold2 bottom left" data-align-x=".4" data-align-y=".8">$ \class{blue}{0} $</div> <div class="extra hold2 bottom right" data-align-x=".4" data-align-y=".8">$ \class{green}{1} $</div> <div class="extra hold2 left top" data-align-x="1.0" data-align-y="0.25">$ \class{blue}{0} $</div> <div class="extra hold2 left top" data-align-x=".6" data-align-y="0.25">$ \class{green}{1} $</div> <div class="extra hold2 right top" data-align-x=".6" data-align-y="0.25">$ \class{blue}{0} $</div> <div class="extra hold2 right top" data-align-x="1.0" data-align-y="0.25">$ \class{green}{1} $</div> <p class="math">You may wonder, if this map is so amazing, how did we ever do without?<br /> Let's label our branches. If we go left, we call it $ 0 $. If we go right, we call it $ 1 $.</p> </div> <div class="step"> <div class="extra"> $$ \frac{5}{3} = \class{green}{11}\class{blue}{0}\hspace{2pt}\class{green}{1}\class{blue}{0}\hspace{2pt}\class{green}{1}\class{blue}{0}… $$ </div> <p class="math">We can then identify any number by writing out the infinite path that leads there as a sequence of ones and zeroes—bits.<br /><br />But you already knew that.</p> </div> <div class="step"> <div class="extra"> $$ \frac{5}{3} = \class{green}{1}.\class{green}{1}\class{blue}{0}\hspace{2pt}\class{green}{1}\class{blue}{0}\hspace{2pt}\class{green}{1}\class{blue}{0}…_2 $$ </div> <p class="math">See we've just rediscovered the binary number system. We're so used to numbers in decimal, <em>base 10</em>, we didn't notice. Yet we all learned that rational numbers consist of digits that settle into a repeating sequence, a <em>repeating pattern of turns</em>. Disallowing finite paths works the same, even in decimal: the number $ 0.95 $ can be written as $\, 0.94999…\, $, i.e. <em>take one final step in one direction, followed by infinitely many steps the other way</em>.</p> </div> <div class="step"> <div class="extra"> $$ \frac{4}{5} = \class{blue}{0}.\class{green}{11}\class{blue}{00}\hspace{2pt}\class{green}{11}\class{blue}{00}…_2 $$ </div> <p class="math"> When we write down a number digit by digit, we're really <em>following the path to it</em> in a graph like this, dialing the number's … er … number. The rationals aren't <em>shaped</em> like a binary tree, rather, they <em>look</em> like a binary tree when viewed through the lens of binary division. Every infinite binary, ternary, quinary, etc. tree is then a different but complete perspective of the same underlying thing. We don't have <em>the</em> map, we have one of infinitely many maps.</p> </div> <div class="step"> <div class="extra top" data-delay=".8" data-align-y=".25"> $$ π = \class{green}{11}.\class{blue}{00}\class{green}{1}\class{blue}{00}\class{green}{1}\class{blue}{0000}\class{green}{1}…_2 $$ </div> <p class="math"> Which means we can show this graph is actually an interdimensional number portal.<br /> See, we already know <em>where</em> the missing numbers are. Irrational numbers like $ π $ form a never-repeating sequence of digits. If we want to reach $ π $, we find it's at the end of an infinite path whose turns <em>do not repeat</em>. By allowing such paths, our map leads us straight to them. Even though it's made out of only <em>one kind of rational number</em>: division by two.</p> </div> <div class="step"> <div class="extra" data-delay="1.6"><big><big> $$ π = \mathop{\class{no-outline}{►\hspace{-2pt}►}}_{\infty\hspace{2pt}} x_n \,? $$ </big></big> </div> <p class="math"> So now we've invented <em>real numbers</em>. How do we visualize this invention? And where does continuity come in? What we need is a procedure that generates such a non-repeating path <em>when taken to the limit</em>. Then we can figure out where the behavior at infinity comes from. </p> </div> <div class="step"> <p>Because the path never settles into a pattern, we can't pin it down with a single neat triangle like before. We try something else. At every step, we can see that the <em>smallest</em> number we can still reach is found by <span class="orangered">always going left</span>. Similarly, the <em>largest</em> available number is found by <span class="green">always going right</span>. Wherever we go from here, it will be somewhere in this range.</p> </div> <div class="step"> <p>We can set up shrinking intervals by placing such triangles along the path, forming a nested sequence.</p> </div> <div class="step"> <div class="extra left"> $$ \begin{align} 3 \leq & π \leq 4 \\ 3.1 \leq & π \leq 3.2 \\ 3.14 \leq & π \leq 3.15 \\ 3.141 \leq & π \leq 3.142 \\ 3.1415 \leq & π \leq 3.1416 \\ 3.14159 \leq & π \leq 3.14160 \\ \end{align} $$ </div> <div class="extra right"> $$ \begin{align} 11_2 \leq & π \leq 100_2 \\ 11.0_2 \leq & π \leq 11.1_2 \\ 11.00_2 \leq & π \leq 11.01_2 \\ 11.001_2 \leq & π \leq 11.010_2 \\ 11.0010_2 \leq & π \leq 11.0011_2 \\ 11.00100_2 \leq & π \leq 11.00101_2 \\ \end{align} $$ </div> <p class="math"> What we've actually done is rounded up and down at every step, to find an upper and lower bound with a certain amount of digits. This works in any number base. </p> </div> <div class="step"> <p class="math">Let's examine these intervals by themselves. We can see that due to the binary nature, each interval covers either the left or right side of its ancestor. Because our graph goes on forever, there are infinitely many nested intervals. This <em>tower of $ π $</em> never ends and never repeats itself, we just squeezed it into a finite space so we could see it better.</p> </div> <div class="step"> <p class="math">If we instead approach a rational number like $ \frac{10}{3} = 3.333…\, $ then the tower starts repeating itself at some point. Note that the intervals <em>don't slide smoothly</em>. Each can only be in one of two places relative to its ancestor.</p> </div> <div class="step"> <p class="math">In order to reach a different rational number, like $ 3.999… = 4 $, we have to establish a different repeating pattern. So we have to rearrange infinitely many levels of the tower all at once, from one configuration to another. This reinforces the notion that rational numbers are not continuous.</p> </div> <div class="step"> <p class="math">If the tower converges to a number, then the top must be infinitely thin, i.e. $ 0 $ units wide. That would suggest it's meaningless to say what the interval at infinity looks like, because it stops existing. Let's try it anyway.</p> </div> <div class="step"> <p class="math"> There is only one question to answer: does the interval cover the <span class="orangered">left side</span>, or the <span class="green">right</span>? </p> </div> <div class="step"> <p class="math"> Oddly enough, in this specific case of $ 3.999…\, $ there is an answer. The tower <em>leans to the right</em>. Therefor, the state of the interval is the same all the way up. If we take the limit, it converges and the <em>final interval</em> goes right. </p> </div> <div class="step"> <p class="math"> But we can immediately see that we can build a second tower that leans left, which converges on the same number. We could distinguish between the two by writing it as $ 4.000…\, $ In this case the <em>final interval</em> goes left. </p> </div> <div class="step"> <p class="math"> If we approach $ 10/3 $, we take a path of <em>alternating left and right steps</em>. The state of the interval at infinity becomes like our paradoxical lamp from before: it has to be both left and right, and therefor it is neither, it's simply undefined. </p> </div> <div class="step"> <p class="math"> The same applies to irrational numbers like $ π $. Because the sequence of turns never repeats itself, the interval flips arbitrarily between left and right forever, therefor it is in an undefined state at the end. </p> </div> <div class="step"> <p class="math"> But there's another way to look at this.<br /> If the interval converges to the number $ π $, then the two sequences of respectively <span class="orangered">lower</span> and <span class="green">upper bounds</span> also converge to $ π $ individually. </p> </div> <div class="step"> <p class="math"> Remember how we derived our bounds: we rounded down by always taking <span class="orangered">lefts</span> and rounded up by always taking <span class="green">rights</span>. The shape of the tower depends on the specific path you're taking, not just the number you reach at the end. </p> </div> <div class="step"> <p class="math"> That means we're approaching the <span class="orangered">lower bounds</span> so they all end in $ 0000… \, $ Their towers always lean left. </p> </div> <div class="step"> <p class="math">If we then take the <em>limit of their final intervals</em> as we approach $ π $, that goes <span class="orangered">left</span> too. Note that this is a double limit: first we find the <em>limit of the intervals</em> of each tower individually, then we take the <em>limit over all the towers as we approach $ π $</em>. </p> </div> <div class="step"> <p class="math"> For the same reason, we can think of all the <span class="green">upper bounds</span> as ending in $ 1111 …\, $ Their towers always lean right. When we take the limit of their final intervals and approach $ π $, we find it points <span class="green">right</span>. </p> </div> <div class="step"> <p class="math"> But, we could actually just reverse the rounding for the upper and lower bounds, and end up with the exact opposite situation. Therefor it doesn't mean that we've invented a <span class="orangered">red $ π $</span> to the left and <span class="green">green $ π $</span> to the right which are somehow different. $ π $ is $ π $. This only says something about our procedure of building towers. It matters because the towers is how we're trying to reach a real number in the first place. </p> </div> <div class="step"> <p class="math"> See, our tower still represents a binary number of infinitely many bits. Every interval can still only be in one of two places. To run along the real number line, we'd have to rearrange infinitely many levels of the tower all at once to create motion. That still does not seem continuous. </p> </div> <div class="step"> <p> We can resolve this if we picture the final interval of each tower as a <em>bit at infinity</em>. If we flip the bit at infinity, we swap between two equivalent ways of reaching a number, so this has no effect on the resulting number. </p> </div> <div class="step"> <p class="math"> In doing so, we're actually imagining that every real number is a rational number whose <em>non-repeating head</em> has grown infinitely big. Its <em>repeating tail</em> has been pushed out all the way past infinity. That means we can flip the repeating part of our tower between different configurations without creating any changes in the number it leads to. </p> </div> <div class="step"> <p class="math"> That helps a little bit with the intuition: if the tower keeps working <em>all the way up there</em>, it must be continuous at its actual tip, wherever that really is. A <em>continuum</em> is then what happens when the smallest possible step you can take isn't just as small as you want. It's so small that it no longer makes <em>any</em> noticeable difference. While that's not a very mathematical definition, I find it very helpful in trying to imagine how this might work. </p> </div> <div class="step"> <div class="extra bottom" data-delay="1.6" data-align-y=".15"> $ 1, 2, 3, 4, 5, 6, … $ </div> <p class="math"> Finally, we might wonder how many of each type of number there are.<br />The natural numbers are <em>countably infinite</em>: there is a procedure of steps which, in the limit, counts all of them. </p> </div> <div class="step"> <div class="extra bottom" data-align-y=".15"> $$ 1, 2, 3, 4, 5, 6, … $$ <br /><br /><br /><br /> </div> <div class="extra bottom" data-delay=".4" data-align-y=".15"> <br /><br /> $$ \class{orangered}{2, 4, 6, 8, 10, 12, …} $$ <br /><br /> </div> <div class="extra bottom" data-delay=".8" data-align-y=".15"> <br /><br /><br /><br /> $$ \class{green}{0, 1, -1, 2, -2, 3, …} $$ </div> <p class="math"> We can find a similar sequence for the <span class="orangered">even natural numbers</span> by multiplying each number by two. We can also alternate between a positive and negative sequence to count <span class="green">the integers</span>. The three sequences are <em>all</em> countably infinite, and we can relate the elements one-to-one. Which means all sequences are <em>equally long</em>.<br />There are as many even positives as positives. Which is exactly as many as all the integers combined. As counter-intuitive as it is, it is the only consistent answer. </p> </div> <div class="step"> <div class="extra bottom right" style="background-image: url(/files/infinity-and-beyond/rationals.png); background-size: 100%; background-position: 0 0; background-repeat: no-repeat;" data-align-x=".2" data-align-y=".5"><small><small> $$ \begin{array}{cccccccc} 1 \hspace{2pt}&\hspace{2pt} 2 \hspace{2pt}&\hspace{2pt} 3 \hspace{2pt}&\hspace{2pt} 4 \hspace{2pt}&\hspace{2pt} 5 \hspace{2pt}&\hspace{2pt} 6 \hspace{2pt}&\hspace{2pt} … \\[6pt] \frac{1}{2} \hspace{2pt}&\hspace{2pt} \class{grey}{\frac{2}{2}} \hspace{2pt}&\hspace{2pt} \frac{3}{2} \hspace{2pt}&\hspace{2pt} \class{grey}{\frac{4}{2}} \hspace{2pt}&\hspace{2pt} \frac{5}{2} \hspace{2pt}&\hspace{2pt} \class{grey}{\frac{6}{2}} \hspace{2pt}&\hspace{2pt} \\[3pt] \frac{1}{3} \hspace{2pt}&\hspace{2pt} \frac{2}{3} \hspace{2pt}&\hspace{2pt} \class{grey}{\frac{3}{3}} \hspace{2pt}&\hspace{2pt} \frac{4}{3} \hspace{2pt}&\hspace{2pt} \frac{5}{3} \hspace{2pt}&\hspace{2pt} \class{grey}{\frac{6}{3}} \hspace{2pt}&\hspace{2pt} \cdots \\[3pt] \frac{1}{4} \hspace{2pt}&\hspace{2pt} \class{grey}{\frac{2}{4}} \hspace{2pt}&\hspace{2pt} \frac{3}{4} \hspace{2pt}&\hspace{2pt} \class{grey}{\frac{4}{4}} \hspace{2pt}&\hspace{2pt} \frac{5}{4} \hspace{2pt}&\hspace{2pt} \class{grey}{\frac{6}{4}} \hspace{2pt}&\hspace{2pt} \\[3pt] \frac{1}{5} \hspace{2pt}&\hspace{2pt} \frac{2}{5} \hspace{2pt}&\hspace{2pt} \frac{3}{5} \hspace{2pt}&\hspace{2pt} \frac{4}{5} \hspace{2pt}&\hspace{2pt} \class{grey}{\frac{5}{5}} \hspace{2pt}&\hspace{2pt} \frac{6}{5} \hspace{2pt}&\hspace{2pt} \\[3pt] \frac{1}{6} \hspace{2pt}&\hspace{2pt} \class{grey}{\frac{2}{6}} \hspace{2pt}&\hspace{2pt} \class{grey}{\frac{3}{6}} \hspace{2pt}&\hspace{2pt} \class{grey}{\frac{4}{6}} \hspace{2pt}&\hspace{2pt} \frac{5}{6} \hspace{2pt}&\hspace{2pt} \class{grey}{\frac{6}{6}} \hspace{2pt}&\hspace{2pt} \\[3pt] \hspace{2pt}&\hspace{2pt} \vdots \hspace{2pt}&\hspace{2pt} \hspace{2pt}&\hspace{2pt} \vdots \hspace{2pt}&\hspace{2pt} \hspace{2pt}&\hspace{2pt} \hspace{2pt}&\hspace{2pt} \hspace{2pt}&\hspace{2pt} \class{white}{\ddots} \end{array} $$ </small></small> </div> <p class="math"> But we can take it one step further: we can find such a sequence for the rational numbers too, by laying out all the fractions on a grid. We can follow diagonals up and down and pass through every single one. If we eliminate duplicates like $ 1 = 2/2 = 3/3 $ and alternate positives and negatives, we can 'count them all'. So there are as many fractions as there are natural numbers. <em>"Deal with it"</em>, says Infinity, donning its sunglasses. <p> </div>

```
<div class="step">
<div class="extra">
$$
\begin{array}{c}
0.\hspace{1pt}\class{green}{1}\hspace{1pt}0\hspace{1pt}0\hspace{1pt}1\hspace{1pt}1\hspace{1pt}1\hspace{1pt}0\hspace{1pt}…_2 \\
0.\hspace{1pt}1\hspace{1pt}\class{blue}{0}\hspace{1pt}0\hspace{1pt}1\hspace{1pt}0\hspace{1pt}0\hspace{1pt}1\hspace{1pt}…_2 \\
0.\hspace{1pt}1\hspace{1pt}0\hspace{1pt}\class{green}{1}\hspace{1pt}0\hspace{1pt}0\hspace{1pt}1\hspace{1pt}0\hspace{1pt}…_2 \\
0.\hspace{1pt}0\hspace{1pt}1\hspace{1pt}1\hspace{1pt}\class{green}{1}\hspace{1pt}0\hspace{1pt}1\hspace{1pt}1\hspace{1pt}…_2 \\
0.\hspace{1pt}1\hspace{1pt}0\hspace{1pt}1\hspace{1pt}1\hspace{1pt}\class{blue}{0}\hspace{1pt}0\hspace{1pt}1\hspace{1pt}…_2 \\
0.\hspace{1pt}0\hspace{1pt}1\hspace{1pt}0\hspace{1pt}1\hspace{1pt}0\hspace{1pt}\class{blue}{0}\hspace{1pt}0\hspace{1pt}…_2 \\
0.\hspace{1pt}0\hspace{1pt}1\hspace{1pt}1\hspace{1pt}1\hspace{1pt}1\hspace{1pt}0\hspace{1pt}\class{green}{1}\hspace{1pt}…_2 \\
… \\
\\
0.\hspace{1pt}\class{blue}{0}\hspace{1pt}\class{green}{1}\hspace{1pt}\class{blue}{0\hspace{1pt}0}\hspace{1pt}\class{green}{1\hspace{1pt}1}\hspace{1pt}\class{blue}{0}\hspace{1pt}…_2
\end{array}
$$
</div>
<p class="math">
The real numbers on the other hand are <em>uncountably infinite</em>: no process can list them all in the limit. The proof is short: suppose we did have a sequence of all the real numbers between $ 0 $ and $ 1 $ in some order. We could then build a new number by taking <span class="green">all</span> <span class="blue">the</span> <span class="green">bits</span> <span class="green">on</span> <span class="blue">the</span> <span class="blue">diagonal</span>, and flipping zeroes and ones.<br>That means this number is different from every listed number in at least one digit, so it's <em>not on the list</em>. But it's also between $ 0 $ and $ 1 $, so it should be. Therefor, <em>the list can't exist</em>.
</p>
</div>
<div class="step">
<p class="math">
This even matches our intuitive explanation from earlier. There are so many real numbers, that we had to invent a bit at infinity to try and count them, and find something that would <em>tick at least once</em> for every real number. Even then we couldn't say whether it was $ 0 $ or $ 1 $ anywhere in particular, because it literally depends on how you approach it.
</p>
</div>
```

REXML could not parse this XML/HTML: </div>

REXML could not parse this XML/HTML: </div>

What we just did was a careful exercise in hiding the obvious, namely the digit-based number systems we are all familiar with. By viewing them not as digits, but as paths on a directed graph, we get a new perspective on just what it means to use them. We've also seen how this means we can construct the rationals and reals using the least possible ingredients required: division by two, and limits.

In school, we generally work with the decimal representation of numbers. As a result, the popular image of mathematics is that it's the science of *digits*, not the underlying structures they represent. This permanently skews our perception of what numbers really are, and is easy to demonstrate. You can google to find countless arguments of why $ 0.999… $ is or isn't equal to $ 1 $. Yet nobody's wondering why $ 0.000… = 0 $, though it's practically the same problem: $ 0.1, 0.01, 0.001, 0.0001, … $

Furthermore, in decimal notation, rational numbers and real numbers look incredibly alike: $ 3.3333… $ vs $ 3.1415…\, $ The question of what it actually means to have infinitely many non-repeating digits, and why this results in continuous numbers, is hidden away in those 3 dots at the end. By imagining $ π $ as $ 3.1415…0000… $ or $ 3.1415…1111… $ we can intuitively bridge the gap to the infinitely small. We see how the distance between two neighbouring real numbers must be so small, that it really is equivalent to $ 0 $.

That's not as crazy as it sounds. In the field of *hyperreal numbers*, every number actually has additional digits 'past infinity': that's its infinitesimal part. You can imagine this to be a multiple of $ \frac{1}{\infty} $, an infinitely small unit greater than $ 0 $, which I'll call $ ε $. The idea of equality is then replaced with *adequality*: being equal aside from an infinitely small difference.

You can explore this hyperreal number line below.

Note that $ ε^2 $ is also infinitesimal. In fact, it's even infinitely smaller than $ ε $, and we can keep doing this for $ ε^3, ε^4, …\,$ To make matters worse, if $ ε $ is infinitesimal, then $ \frac{1}{ε} $ must be infinitely big, and $ \frac{1}{ε^2} $ infinitely bigger than that. So hyperreal numbers don't just have inwardly nested infinitesimal levels, but outward levels of increasing infinity too. They have infinitely many dimensions of infinity both ways.

So it's perfectly possible to say that $ 0.999… $ does not equal $ 1 $, if you mean they differ by an infinitely small amount. The only problem is that in doing so, you get much, *much* more than you bargained for.

That means we can finally answer the question we started out with: why did our continuous atoms seemingly all have $ 0 $ mass, when the total mass was not $ 0 $? The answer is that the mass per atom was *infinitesimal*. So was each atom's volume. The density, *mass per volume*, was the result of dividing one infinitesimal amount by another, to get a normal sized number again. To create a finite mass in a finite volume, we have to add up infinitely many of these atoms.

These are the underlying principles of calculus, and the final puzzle piece to cover. The funny thing about calculus is, it's conceptually easy, especially if you start with a good example. What is hard is actually working with the formulas, because they can get hairy very quickly. Luckily, your computer will do them for you:

That was differential and integral calculus in a nutshell. We saw how many people actually spend hours every day sitting in front of an *integrator*: the odometers in their cars, which integrate speed into distance. And the derivative of speed is acceleration—i.e. how hard you're pushing on the gas pedal or brake, combined with forces like drag and friction.

By using these tools in equations, we can describe laws that relate quantities to their *rates of change*. Drag, also known as air resistance, is a force which gets stronger the faster you go. This is a relationship between the first and second derivatives of position.

In fact, the relaxation procedure we applied to our track is equivalent to another physical phenomenon. If the curve of the coaster represented the temperature along a thin metal rod, then the heat would start to equalize itself in exactly that fashion. Temperature wants to be smooth, eventually averaging out completely into a flat curve.

Whether it's heat distribution, fluid dynamics, wave propagation or a head bobbing in a roller coaster, all of these problems can be naturally expressed as so called *differential equations*. Solving them is a skill learned over many years, and some solutions come in the form of infinite series. Again, infinity shows up, ever the uninvited guest at the dinner table.

Infinity is a many splendored thing but it does not lift us up where we belong. It boggles our mind with its implications, yet is absolutely essential in math, engineering and science. It grants us the ability to see the impossible and build new ideas within it. That way, we can solve intractable problems and understand the world better.

What a shame then that in pop culture, it only lives as a caricature. Conversations about infinity occupy a certain sphere of it—Pink Floyd has been playing on repeat, and there's usually someone peddling crystals and incense nearby.

*"Man, have you ever, like, tried to imagine infinity…?"* they mumble, staring off into the distance.

"Funny story, actually. We just came from there…"

*Comments, feedback and corrections are welcome on Google Plus. Diagrams powered by MathBox.*

*More like this: How to Fold a Julia Fractal.*

First things first: the CSS 3D renderer used to power ~~this~~ *the previous* site is now available on GitHub.com. However, it's still limited to only solid lines and planes. It's also limited to WebKit browsers, as Firefox's CSS 3D support just isn't quite there yet.

But CSS 3D is not a one trick pony, and as with many things, what you get out of it depends entirely on what you put in. So here's a disembodied head made out of CSS 3D. It consists of nothing more than a bunch of images stacked up against each other, and integrates perfectly with the existing 3D parallax on this site. Click and drag to rotate, or use the slider to look inside.

Making the basic effect was actually quite easy. I took an MRI from the Stanford Volume Data Archive and wrote a small script to turn it into a sheet of CSS sprites. There's one file for color, one for opacity, totalling about 2.1 MB. Both files are composited into Canvases and placed in slices into the DOM, offset forward or backwards in 3D. Then there's just some minor logic to rotate the slices in 90 degree increments to follow the camera.

But the slices are rendered as is, and the MRI consists of boring grayscale data. Luckily, I can precompute any amount of shaders and effects I want and just bake them into the slices. I geeked out by applying fake specular lighting, for that 'fresh meat' look, and volumetric obscurance to enhance the sense of depth on the inside. I changed the palette to gory colors based on local density, giving the impression of flesh and bone knitting itself together. Creepy, but cool.

I wrapped it in a custom widget, using straight up CSS rather than Three.js this time. I've wanted to play with Tangle.js, so I used that to hook up the camera controls and slider. That's pretty much it. In an ideal world, the jarring transition when rotating would be covered up by a nice transition, but the browsers don't like it.

REXML could not parse this XML/HTML: <script type="text/javascript"> Acko.queue(function () { var model = { initialize: function () { // State this.theta = 0.0; this.phi = 0.5; this.slice = 0; }, update: function () { this.transform = 'rotateX('+ -this.theta +'rad) rotateY('+ this.phi +'rad)'; }, }; Tangle.classes.CSS3DCamera = { initialize: function (element, options, tangle, variables) { this.element = element; var that = this; element.addEventListener('mousedown', function (event) { that.drag = true; that.dragLast = that.dragOrigin = { x: event.pageX, y: event.pageY }; event.preventDefault(); }); document.addEventListener('mouseup', function (event) { that.drag = false; }); document.addEventListener('mousemove', function (event) { if (!that.drag) return; var total = { x: event.pageX - that.dragOrigin.x, y: event.pageY - that.dragOrigin.y }, delta = { x: event.pageX - that.dragLast.x, y: event.pageY - that.dragLast.y }; that.dragLast = { x: event.pageX, y: event.pageY }; mousemove(that.dragOrigin, total, delta); }); function mousemove(origin, total, delta) { var phi = tangle.getValue('phi') + delta.x * .01, theta = Math.min(1, Math.max(-.2, tangle.getValue('theta') + delta.y * .01)); tangle.setValue('phi', phi); tangle.setValue('theta', theta); } }, update: function (element, value) { this.element.style.WebkitTransform = value; this.element.style.MozTransform = value; this.element.style.transform = value; }, }, Tangle.classes.Slider = { initialize: function (element, options, tangle, variables) { var that = this; this.tangle = tangle; this.element = element; this.bar = document.createElement('div'); this.bar.className = 'bar'; this.element.appendChild(this.bar); this.handle = document.createElement('div'); this.handle.className = 'handle'; this.element.appendChild(this.handle); this.element.addEventListener('mousedown', function (event) { var el = this.element, o = 0; do { o += el.offsetLeft; el = el.offsetParent; } while (el); this.origin = o; this.width = this.bar.offsetWidth; this.drag = true; return false; }.bind(this)); document.addEventListener('mousemove', function (event) { if (!that.drag) return; tangle.setValue('slice', Math.max(0, Math.min(1, (event.pageX - that.origin) / that.width))); }); document.addEventListener('mouseup', function () { that.drag = false; }); }, update: function (element, value) { this.handle.style.left = (100*value) + '%'; }, }, Tangle.classes.VolumetricView = { initialize: function (element, options, tangle, variables) { var that = this; this.tangle = tangle; this.element = element; this.width = 364; this.height = 384; this.depth = 256; this.resX = 182; this.resY = 192; this.slices = 108; this.stride = 8; this.rows = Math.ceil(this.slices / this.stride); this.createSlices(); var load = 0; this.image = new Image(); this.image.onload = function () { if (++load == 2) that.drawSlices(); }; this.mask = new Image(); this.mask.onload = function () { if (++load == 2) that.drawSlices(); }; // this.image.src = 'data/MRbrain.png'; this.image.src = '/files/mri/MRbrain-color.jpg'; this.mask.src = '/files/mri/MRbrain-alpha8.png'; }, update: function (element, value) { var l = Math.abs(Math.cos(value)) > Math.abs(Math.sin(value)); if (this.l != l || this.slice != slice) { var slice = this.tangle.getValue('slice'), index, n = (l ? Math.cos(value) : Math.sin(value)) > 0, sn = n ? slice : 1 - slice; index = +(this.slicesX.length * sn); var display = l ? 'block' : 'none'; forEach(this.slicesX, function (el, i) { el.style.display = display; var opacity; if (i >= index) { opacity = n ? .95 : .001; } else { opacity = !n ? .95 : .001; } el.style.opacity = opacity; }); index = +(this.slicesZ.length * sn); var display = !l ? 'block' : 'none'; forEach(this.slicesZ, function (el, i) { el.style.display = display; var opacity; if (i >= index) { opacity = n ? .95 : .001; } else { opacity = !n ? .95 : .001; } el.style.opacity = opacity; }); this.slice = slice; this.l = l; } }, createSlices: function () { this.element.innerHTML = ''; this.ctxX = []; this.ctxZ = []; // X slices for (var i = 0; i < this.slices; ++i) { var z = -((i / this.slices) - .5) * this.depth, t = 'translateZ(' + z + 'px) translateX(70px)'; var canvas = document.createElement('canvas'); canvas.className = 'x'; canvas.width = this.resX; canvas.height = this.resY; canvas.style.width = this.width + 'px'; canvas.style.height = this.height + 'px'; canvas.style.WebkitTransform = t; canvas.style.MozTransform = t; canvas.style.transform = t; this.element.appendChild(canvas); this.ctxX.push(canvas.getContext('2d')); } // Z slices for (var i = 0; i < this.resX; ++i) { var z = -(this.depth - this.width) / 2, x = ((i / this.resX) - .5) * this.width, t = 'translateX(' + x + 'px) translateX(70px) rotateY(90deg) translateZ(' + z + 'px)'; var canvas = document.createElement('canvas'); canvas.className = 'z'; canvas.width = this.slices; canvas.height = this.resY; canvas.style.width = this.depth + 'px'; canvas.style.height = this.height + 'px'; canvas.style.WebkitTransform = t; canvas.style.MozTransform = t; canvas.style.transform = t; canvas.style.opacity = 0; this.element.appendChild(canvas); this.ctxZ.push(canvas.getContext('2d')); } this.slicesX = this.element.querySelectorAll('canvas.x'); this.slicesZ = this.element.querySelectorAll('canvas.z'); }, drawSlices: function () { var s = this.stride, sl = this.slices, r = this.rows, w = this.resX, h = this.resY, img = this.image, mask = this.mask, ctxX = this.ctxX, ctxZ = this.ctxZ; var alpha, color; // X slices forEach(this.slicesX, function (slice, i) { var c = ctxX[i], ox = (i % s) * w, oy = Math.floor(i / s) * h; // Draw alpha channel and get pixels c.drawImage(mask, ox, oy, w, h, 0, 0, w, h); alpha = c.getImageData(0, 0, w, h); // Draw color channel and get pixels c.drawImage(img, ox, oy, w, h, 0, 0, w, h); color = c.getImageData(0, 0, w, h); // Copy red to alpha. var src = alpha.data, dst = color.data; for (var y = 0; y < h; ++y) { for (var x = 0; x < w; ++x) { var o = (x + y * w) * 4; dst[o + 3] = src[o]; } } // Draw RGBA. c.putImageData(color, 0, 0); }); // Z slices forEach(this.slicesZ, function (slice, i) { var c = ctxZ[i]; // Render transposed slices as vertical strips. for (var j = 0; j < sl; ++j) { var ox = (j % s) * w, oy = Math.floor(j / s) * h; // Draw alpha channel c.drawImage(mask, ox + i, oy, 1, h, j, 0, 1, h); } // Get pixels alpha = c.getImageData(0, 0, w, h); // Render transposed slices as vertical strips. for (var j = 0; j < sl; ++j) { var ox = (j % s) * w, oy = Math.floor(j / s) * h; // Draw color channel c.drawImage(img, ox + i, oy, 1, h, j, 0, 1, h); } // Get pixels color = c.getImageData(0, 0, w, h); // Copy red to alpha. var src = alpha.data, dst = color.data; for (var y = 0; y < h; ++y) { for (var x = 0; x < w; ++x) { var o = (x + y * w) * 4; dst[o + 3] = src[o]; } } // Draw RGBA. c.putImageData(color, 0, 0); }); }, }; var tangle = new Tangle(document.querySelector('#head-3d'), model); }, 200); </script>

REXML could not parse this XML/HTML: <script> // // Tangle.js // Tangle 0.1.0 // // Created by Bret Victor on 5/2/10. // (c) 2011 Bret Victor. MIT open-source license. // // ------ model ------ // // var tangle = new Tangle(rootElement, model); // tangle.setModel(model); // // ------ variables ------ // // var value = tangle.getValue(variableName); // tangle.setValue(variableName, value); // tangle.setValues({ variableName:value, variableName:value }); // // ------ UI components ------ // // Tangle.classes.myClass = { // initialize: function (element, options, tangle, variable) { ... }, // update: function (element, value) { ... } // }; // Tangle.formats.myFormat = function (value) { return "..."; }; // var Tangle = this.Tangle = function (rootElement, modelClass) { var tangle = this; tangle.element = rootElement; tangle.setModel = setModel; tangle.getValue = getValue; tangle.setValue = setValue; tangle.setValues = setValues; var _model; var _nextSetterID = 0; var _setterInfosByVariableName = {}; // { varName: { setterID:7, setter:function (v) { } }, ... } var _varargConstructorsByArgCount = []; //---------------------------------------------------------- // // construct initializeElements(); setModel(modelClass); return tangle; //---------------------------------------------------------- // // elements function initializeElements() { var elements = rootElement.getElementsByTagName("*"); var interestingElements = []; // build a list of elements with class or data-var attributes for (var i = 0, length = elements.length; i < length; i++) { var element = elements[i]; if (element.getAttribute("class") || element.getAttribute("data-var")) { interestingElements.push(element); } } // initialize interesting elements in this list. (Can't traverse "elements" // directly, because elements is "live", and views that change the node tree // will change elements mid-traversal.) for (var i = 0, length = interestingElements.length; i < length; i++) { var element = interestingElements[i]; var varNames = null; var varAttribute = element.getAttribute("data-var"); if (varAttribute) { varNames = varAttribute.split(" "); } var views = null; var classAttribute = element.getAttribute("class"); if (classAttribute) { var classNames = classAttribute.split(" "); views = getViewsForElement(element, classNames, varNames); } if (!varNames) { continue; } var didAddSetter = false; if (views) { for (var j = 0; j < views.length; j++) { if (!views[j].update) { continue; } addViewSettersForElement(element, varNames, views[j]); didAddSetter = true; } } if (!didAddSetter) { var formatAttribute = element.getAttribute("data-format"); var formatter = getFormatterForFormat(formatAttribute, varNames); addFormatSettersForElement(element, varNames, formatter); } } } function getViewsForElement(element, classNames, varNames) { // initialize classes var views = null; for (var i = 0, length = classNames.length; i < length; i++) { var clas = Tangle.classes[classNames[i]]; if (!clas) { continue; } var options = getOptionsForElement(element); var args = [ element, options, tangle ]; if (varNames) { args = args.concat(varNames); } var view = constructClass(clas, args); if (!views) { views = []; } views.push(view); } return views; } function getOptionsForElement(element) { // might use dataset someday var options = {}; var attributes = element.attributes; var regexp = /^data-[\w\-]+$/; for (var i = 0, length = attributes.length; i < length; i++) { var attr = attributes[i]; var attrName = attr.name; if (!attrName || !regexp.test(attrName)) { continue; } options[attrName.substr(5)] = attr.value; } return options; } function constructClass(clas, args) { if (typeof clas !== "function") { // class is prototype object var View = function () { }; View.prototype = clas; var view = new View(); if (view.initialize) { view.initialize.apply(view,args); } return view; } else { // class is constructor function, which we need to "new" with varargs (but no built-in way to do so) var ctor = _varargConstructorsByArgCount[args.length]; if (!ctor) { var ctorArgs = []; for (var i = 0; i < args.length; i++) { ctorArgs.push("args[" + i + "]"); } var ctorString = "(function (clas,args) { return new clas(" + ctorArgs.join(",") + "); })"; ctor = eval(ctorString); // nasty _varargConstructorsByArgCount[args.length] = ctor; // but cached } return ctor(clas,args); } } //---------------------------------------------------------- // // formatters function getFormatterForFormat(formatAttribute, varNames) { if (!formatAttribute) { formatAttribute = "default"; } var formatter = getFormatterForCustomFormat(formatAttribute, varNames); if (!formatter) { formatter = getFormatterForSprintfFormat(formatAttribute, varNames); } if (!formatter) { log("Tangle: unknown format: " + formatAttribute); formatter = getFormatterForFormat(null,varNames); } return formatter; } function getFormatterForCustomFormat(formatAttribute, varNames) { var components = formatAttribute.split(" "); var formatName = components[0]; if (!formatName) { return null; } var format = Tangle.formats[formatName]; if (!format) { return null; } var formatter; var params = components.slice(1); if (varNames.length <= 1 && params.length === 0) { // one variable, no params formatter = format; } else if (varNames.length <= 1) { // one variable with params formatter = function (value) { var args = [ value ].concat(params); return format.apply(null, args); }; } else { // multiple variables formatter = function () { var values = getValuesForVariables(varNames); var args = values.concat(params); return format.apply(null, args); }; } return formatter; } function getFormatterForSprintfFormat(formatAttribute, varNames) { if (!sprintf || !formatAttribute.test(/\%/)) { return null; } var formatter; if (varNames.length <= 1) { // one variable formatter = function (value) { return sprintf(formatAttribute, value); }; } else { formatter = function (value) { // multiple variables var values = getValuesForVariables(varNames); var args = [ formatAttribute ].concat(values); return sprintf.apply(null, args); }; } return formatter; } //---------------------------------------------------------- // // setters function addViewSettersForElement(element, varNames, view) { // element has a class with an update method var setter; if (varNames.length <= 1) { setter = function (value) { view.update(element, value); }; } else { setter = function () { var values = getValuesForVariables(varNames); var args = [ element ].concat(values); view.update.apply(view,args); }; } addSetterForVariables(setter, varNames); } function addFormatSettersForElement(element, varNames, formatter) { // tangle is injecting a formatted value itself var span = null; var setter = function (value) { if (!span) { span = document.createElement("span"); element.insertBefore(span, element.firstChild); } span.innerHTML = formatter(value); }; addSetterForVariables(setter, varNames); } function addSetterForVariables(setter, varNames) { var setterInfo = { setterID:_nextSetterID, setter:setter }; _nextSetterID++; for (var i = 0; i < varNames.length; i++) { var varName = varNames[i]; if (!_setterInfosByVariableName[varName]) { _setterInfosByVariableName[varName] = []; } _setterInfosByVariableName[varName].push(setterInfo); } } function applySettersForVariables(varNames) { var appliedSetterIDs = {}; // remember setterIDs that we've applied, so we don't call setters twice for (var i = 0, ilength = varNames.length; i < ilength; i++) { var varName = varNames[i]; var setterInfos = _setterInfosByVariableName[varName]; if (!setterInfos) { continue; } var value = _model[varName]; for (var j = 0, jlength = setterInfos.length; j < jlength; j++) { var setterInfo = setterInfos[j]; if (setterInfo.setterID in appliedSetterIDs) { continue; } // if we've already applied this setter, move on appliedSetterIDs[setterInfo.setterID] = true; setterInfo.setter(value); } } } //---------------------------------------------------------- // // variables function getValue(varName) { var value = _model[varName]; if (value === undefined) { log("Tangle: unknown variable: " + varName); return 0; } return value; } function setValue(varName, value) { var obj = {}; obj[varName] = value; setValues(obj); } function setValues(obj) { var changedVarNames = []; for (var varName in obj) { var value = obj[varName]; var oldValue = _model[varName]; if (oldValue === undefined) { log("Tangle: setting unknown variable: " + varName); continue; } if (oldValue === value) { continue; } // don't update if new value is the same _model[varName] = value; changedVarNames.push(varName); } if (changedVarNames.length) { applySettersForVariables(changedVarNames); updateModel(); } } function getValuesForVariables(varNames) { var values = []; for (var i = 0, length = varNames.length; i < length; i++) { values.push(getValue(varNames[i])); } return values; } //---------------------------------------------------------- // // model function setModel(modelClass) { var ModelClass = function () { }; ModelClass.prototype = modelClass; _model = new ModelClass; updateModel(true); // initialize and update } function updateModel(shouldInitialize) { var ShadowModel = function () {}; // make a shadow object, so we can see exactly which properties changed ShadowModel.prototype = _model; var shadowModel = new ShadowModel; if (shouldInitialize) { shadowModel.initialize(); } shadowModel.update(); var changedVarNames = []; for (var varName in shadowModel) { if (!shadowModel.hasOwnProperty(varName)) { continue; } if (_model[varName] === shadowModel[varName]) { continue; } _model[varName] = shadowModel[varName]; changedVarNames.push(varName); } applySettersForVariables(changedVarNames); } //---------------------------------------------------------- // // debug function log (msg) { if (window.console) { window.console.log(msg); } } }; // end of Tangle //---------------------------------------------------------- // // components Tangle.classes = {}; Tangle.formats = {}; Tangle.formats["default"] = function (value) { return "" + value; }; </script>]]>