text:
Three Body Problem
The Three Body Problem is a four hundred year old problem of mathematics which has its roots in the unsuccessful attempts to simulate a heliocentric Sun-Earth-Moon system.
Due to the nature of gravity, a three body system inherently prefers to be a two body orbit and will attempt to kick out the smallest body from the system—often causing the system to be destroyed altogether.[1] There are a limited range of scenarios in which three body orbits may exist.[2] It is seen that those configurations require at least two of the three bodies to be of the same mass, can only exist with specific magnitudes in specific, sensitive, and highly symmetrical configurations, and exhibit odd loopy orbits that look quite different than the systems of astronomy proposed by Copernicus. The slightest imperfection, such as with bodies of different masses, non-symmetrical spacing, or the effect of a gravitational influence external to the system, causes a chain reaction of random chaos which compels the entire system to fall apart.[3]
A typical response to this is to claim that there are numerical solutions. However, these are approximations which do not fully simulate the situation. See the page Numerical Solutions. We are taught that it should be possible for a star to have a planet which has a moon, yet the greatest mathematicians of human history have been unable to get it to work.
" Describing the motion of any planetary system (including purely imaginary ones that exist only on paper) is the subject of a branch of mathematics called celestial mechanics. Its problems are extremely difficult and have eluded the greatest mathematicians in history. " —Paul Trow, Chaos and the Solar System
400 Years of Defiance
In The Physics Problem that Isaac Newton Couldn't Solve (Archive) Vanderbilt University physics and astronomy professor Robert Scherrer (bio) tells us:
" There's a physics problem so difficult, so intractable, that even Isaac Newton, undoubtedly the greatest physicist who ever lived, couldn't solve it. And it's defied everyone else's attempts ever since then.
This is the famous three-body problem. When Newton invented his theory of gravity, he immediately set to work applying it to the motions of the planets in the solar system. If you have a planet orbiting a much larger body, like the sun, and the orbit is circular, then the problem is easy to solve -- it's something that's done in a high school physics class.
But a circular orbit isn't the most general possibility, and sometimes one body isn't much smaller than the object it orbits (think of the Moon going around the Earth). This more complicated case can still be solved -- Newton showed that the two bodies orbit their common center of mass in elliptical orbits. In fact, this prediction of elliptical orbits really cemented the case for Newton's theory of gravity. The calculation is a lot trickier than for circular orbits, but we still throw it at undergraduate physics majors in their second or third year.
Now add a third body, and everything falls apart. The problem goes from one that a smart undergraduate can tackle to one that has defied solution for 400 years. "
NOVA Documentary
A Nova documentary, The Strange New Science of Chaos, states that mathematicians were unable to extend Newton's model beyond two bodies. See from 9:40 to 13:20 (~4m):
Newton's Solution
Mathematician and astronomer Issac Newton is credited to have "brought the laws of physics to the solar system."1 To solve the multi-body problems of his system Newton famously invoked divine intervention (Archive):
" At the beginning of the 18th century, Newton famously wrote that the solar system needed occasional divine intervention (presumably a nudge here and there from the hand of God) in order to remain stable.11 This was interpreted to mean that Newton believed his mathematical model of the solar system—the n body problem—did not have stable solutions. Thus was the gauntlet laid down, and a proof of the stability of the n body problem became one of the great mathematical challenges of the age.
- 11Newton's remarks about divine intervention appear in Query 23 of the 1706 (Latin) edition of Opticks, which became Query 31 of the 1717 (2nd Edition) edition see Quote Q[New] in Appendix E). Similar 'theological' remarks are found in scholia of the 2nd and 3rd editions of Principia, and in at least one of Newton's letters. In a 1715 letter to Caroline, Princess of Wales, Leibniz observed sarcastically that Newton had not only cast the Creator as a clock-maker, and a faulty one, but now as a clock-repairman (see [Klo73], Part XXXIV, pp. 54-55). "
- 1The University of California San Diego credits Newton with providing the laws of physics for the Solar System (Archive):
- " Then came Isaac Newton (1642-1727) who brought the laws of physics to the solar system. Isaac Newton explained why the planets move the way they do, by applying his laws of motion, and the force of gravitation between any two bodies, letting the force decrease with the square of the distance between the two bodies. "
Henri Poincaré
Caltech physicist Sean Carrol (bio) gives a history of the problem on his page N-Bodies:
" The N-body problem is one of the most famous, and easily stated, problems in mathematical physics: find exact solutions to point masses moving under their mutual Newtonian gravitational forces (i.e. the inverse-square law). For N=2 the complete set of solutions is straightforward and has been known for a long time — each body moves in a conic section (circle, ellipse, parabola or hyperbola) around the center of mass. In fact, Kepler found the solution even before Newton came up with the problem!
But let N=3 and chaos breaks loose, quite literally. For a long time people recognized that the motion of three gravitating bodies would be a difficult problem, but there were hopes to at least characterize the kinds of solutions that might exist (even if we couldn't write down the solutions explicitly). It became a celebrated goal for mathematical physicists, and the very amusing story behind how it was resolved is related in Peter Galison's book Einstein's Clocks and Poincare's Maps. In 1885, a mathematical competition was announced in honor of the 60th birthday of King Oscar II of Sweden, and the three-body problem was one of the questions. (Feel free to muse about the likelihood of the birthday of any contemporary world leader being celebrated by mathematical competitions.) Henri Poincare was a favorite to win the prize, and he submitted an essay that demonstrated the stability of planetary motions in the three-body problem (actually the "restricted" problem, in which one test body moves in the gravitational field generated by two others). In other words, without knowing the exact solutions, we could at least be confident that the orbits wouldn't go crazy; more technically, solutions starting with very similar initial conditions would give very similar orbits. Poincare's work was hailed as brilliant, and he was awarded the prize.
But as his essay was being prepared for publication in Acta Mathematica, a couple of tiny problems were pointed out by Edvard Phragmen, a Swedish mathematician who was an assistant editor at the journal. Gosta Mittag-Leffler, chief editor, forwarded Phragmen's questions to Poincare, asking him to fix up these nagging issues before the prize essay appeared in print. Poincare went to work, but discovered to his consternation that one of the tiny problems was in fact a profoundly devastating possibility that he hadn't really taken seriously. What he ended up proving was the opposite of his original claim — three-body orbits were not stable at all. Not only were orbits not periodic, they didn't even approach some sort of asymptotic fixed points.
Now that we have computers to run simulations, this kind of behavior is less surprising (example here) from Steve McMillan — note how the final "binary" is not made of the same "stars" as the original one), but at the time it came as an utter shock. In his attempt to prove the stability of planetary orbits, Poincare ended up inventing chaos theory.
But the story doesn't quite end there. Mittag-Leffler, convinced that Poincare would be able to tie up the loose threads in his prize essay, went ahead and printed it. By the time he heard from Poincare that no such tying-up would be forthcoming, the journal had already been mailed to mathematicians throughout Europe. Mittag-Leffler swung into action, telegraphing Berlin and Paris in an attempt to have all copies of the journal destroyed. He basically succeeded, but not without creating a minor scandal in elite mathematical circles across the Continent. (The Wikipedia entry on Poincare tells a much less interesting, and less accurate, version of the story.)
However, just because the general solution to the three-body (and more-body) problem is chaotic, doesn't mean we can't find special exact solutions in highly-symmetric conditions, and that's just what Cris Moore and Michael Nauenberg have recently been doing. The image at the top really is an exact solution to twenty-one equal-mass objects moving in a figure-eight under their mutual gravitational attraction. They're moving in a plane, of course, but that's not strictly necessary; here's a close relative of the figure-8, perturbed outside the plane. "
" From there you can just go nuts; here's an example with twelve objects orbiting with cubic symmetry — four distinct periodic paths with three particles each. "
Sean Carrol describes the three body problem orbits as chaotic and classifies the special orbits which were discovered as "highly-symmetric." Dr. Carrol proceeds to give animations of figure eight configurations and other special symmetrical orbits which have been discovered.
Readers should decide for themselves whether the Sun-Earth-Moon system or other systems proposed by contemporary Astronomy are "highly symmetric" systems.
Ask a Mathematician
https://www.askamathematician.com/2011/10/q-what-is-the-three-body-problem/ (Archive)
" Q: What is the three body problem?
Physicist: The three body problem is to exactly solve for the motions of three (or more) bodies interacting through an inverse square force (which includes gravitational and electrical attraction).
The problem with the 3-body problem is that it can't be done, except in a very small set of frankly goofy scenarios (like identical planets following identical orbits). "
No General Solutions
Physics Professor Richard Fitzpatrick at the University of Texas says (Archive):
" We saw earlier, in Section 2.9, that an isolated dynamical system consisting of two freely moving point masses exerting forces on one another--which is usually referred to as a two-body problem--can always be converted into an equivalent one-body problem. In particular, this implies that we can exactly solve a dynamical system containing two gravitationally interacting point masses, because the equivalent one-body problem is exactly soluble. (See Sections 2.9 and 4.16.) What about a system containing three gravitationally interacting point masses? Despite hundreds of years of research, no useful general solution of this famous problem--which is usually called the three-body problem--has ever been found. "
Science China Press says (Archive):
" In general, orbits described by the three-body problem are non-periodic, i.e. chaotic, and are rather sensitive to initial conditions. According to the theory of chaos, uncertainty in initial conditions enlarges exponentially for chaotic dynamic systems. Therefore, it is rather difficult to gain reliable convergent numerical simulations of chaotic orbits of three-body systems across a long interval of time. Due to this, it is also difficult to find periodic orbits of three-body systems by means of numerical methods. "
From The Three-Body Problem (Archive) by Z.E. Musielak and B. Quarles we see:
" In the three-body problem, three bodies move in space under their mutual gravitational interactions as described by Newton's theory of gravity. Solutions of this problem require that future and past motions of the bodies be uniquely determined based solely on their present positions and velocities. In general, the motions of the bodies take place in three dimensions (3D), and there are no restrictions on their masses nor on the initial conditions. Thus, we refer to this as the general three-body problem . At first glance, the difficulty of the problem is not obvious, especially when considering that the two-body problem has well-known closed form solutions given in terms of elementary functions. Adding one extra body makes the problem too complicated to obtain similar types of solutions. In the past, many physicists, astronomers and mathematicians attempted unsuccessfully to find closed form solutions to the three-body problem. Such solutions do not exist because motions of the three bodies are in general unpredictable, which makes the three-body problem one of the most challenging problems in the history of science. "
As we read above, there are no general solutions to the Three Body Problem and that the motions are unpredictable. As Sean Carroll and the authors of "Ask A Mathematician" related, the only solutions require very specific and odd scenarios.
A Thousand New Solutions
In 2017 researchers used a supercomputer to test various configurations and reported over one thousand new special solutions to the Three Body Problem. We read an account from a New Scientist article titled Infamous three-body problem has over a thousand new solutions (Archive) :
" For more than 300 years, mathematicians have puzzled over the three-body problem – the question of how three objects orbit one another according to Newton's laws. Now, there are 1223 new solutions to the conundrum, more than doubling the current number of possibilities.
No single equation can predict how three bodies will move in relation to one another and whether their orbits will repeat or devolve into chaos. Mathematicians must test each specific scenario to see if the objects will stay bound in orbit or be flung away.
The new solutions were found when researchers at Shanghai Jiaotong University in China tested 16 million different orbits using a supercomputer.
All the fresh orbits found are periodic. This means that each object, whether it's a planet or a proton, ends up where it first began its orbit, with their paths forming three intertwined, closed loops.
"It is impressive that they've made the list a lot longer," says Robert Vanderbei at Princeton University in New Jersey – though he adds that there is "basically an unlimited number of orbits", so it may be overkill if anyone sought to find them all.
Perhaps the most important application of the three-body problem is in astronomy, for helping researchers figure out how three stars, a star with a planet that has a moon, or any other set of three celestial objects can maintain a stable orbit.
But these new orbits rely on conditions that are somewhere between unlikely and impossible for a real system to satisfy. In all of them, for example, two of the three bodies have exactly the same mass and they all remain in the same plane.
Knot-like paths
In addition, the researchers did not test the orbits' stability. It's possible that the tiniest disturbance in space or rounding error in the equations could rip the objects away from one another.
"These orbits have nothing to do with astronomy, but you're solving these equations and you're getting something beautiful," says Vanderbei.
Aside from giving us a thousand pretty pictures of knot-like orbital paths, the new three-body solutions also mark a starting point for finding even more possible orbits, and eventually figuring out the whole range of winding paths that three objects can follow around one another.
"This is kind of the zeroth step. Then the question becomes, how is the space of all possible positions and velocities filled up by solutions?" says Richard Montgomery at the University of California, Santa Cruz. "These simple orbits are kind of like a skeleton to build the whole system up from." "
As suggested by the above article, the field of Celestial Mechanics is still on step zero—the stone age. The found orbits are nothing like heliocentric astronomy and there will be an attempt to use them as a skeleton to "build the whole system up from."
Hill's Region
Astronomer and mathematician George William Hill studied the Three Body Problem. The only way Hill was able to make any progress at all was by using the Restricted Three Body Problem, where one of the bodies was of zero or negligible mass. Even then, the body was still chaotic. The benefit of the Restricted Three Body Problem and the Mass-less moon meant that that the moon would be no longer ejected from the system, as it would usually be. It is confined to what is known as "Hill's Region".
From Scholarpedia's Three Body Problem page by mathematician Alain Chenciner (bio):
http://www.scholarpedia.org/article/Three_body_problem (Archive)
The above depicts a crazy and chaotic moon which even makes a u-turn in mid orbit.
From the text that accompanies the image:
" The simplest case:
It occurs when, the Jacobi constant being negative and big enough, the zero mass body (we shall still call it the Moon) moves in a component of the Hill region which is a disc around one of the massive bodies (the Earth). This fact already implies Hill's rigorous stability result: for all times such a Moon would not be able to escape from this disc. Nevertheless this does not prevent collisions with the Earth. "
"Zero mass body" -- One of the bodies in the restricted three body problem is of zero mass.
"Nevertheless this does not prevent collisions with the earth" -- It's still chaotic, even in that simplified version.
One might observe that Newtonian Mechanics most certainly does not naturally default to the heliocentric system of Copernicus.
Poliastro, an astrodynamics software developer, shares several numerical methods for the restricted three body problem:
https://twitter.com/poliastro_py/status/993418078036873216?lang=en (Archive)
" Look at this beautiful plot of several numerical methods for the restricted three body problem taken from Harier et al. "Solving Ordinary Differential Equations I". The use of high order Runge-Kutta methods is pervasive in Celestial Mechanics. Happy Monday! "
Arenstorf orbits are the knotted closed trajectories which are the result of Restricted Three Body Problem solutions.
It is sometimes asserted that the above source is not simulating the orbit of the Moon, to which the reply is simple: Do you think that they were trying to simulate an incorrect orbit of the Moon?
Chaos Theory: A Demo
The available solutions to the Two and Three Body Problems are so sensitive that the slightest change or imperfection will tear the entire system apart. From 'Mathematics Applied to Deterministic Problems in Natural Sciences' we read another account of Poincaré's discoveries:
" As Poincaré experimented, he was relieved to discover that in most of the situations, the possible orbits varied only slightly from the initial 2-body orbit, and were still stable, but what occurred during further experimentation was a shock. Poincaré discovered that even in some of the smallest approximations some orbits behaved in an erratic unstable manner. His calculations showed that even a minute gravitational pull from a third body might cause a planet to wobble and fly out of orbit all together. "
The orbits are incredibly sensitive. As a very illustrative demonstration, take a look at this online Three Body Problem simulator that uses the symmetrical figure eight pattern, which requires three identical bodies of equal mass which move at very specific momentum and distance in relation to each other.
Demo: Figure-Eight Three Body Problem
Adjust the mass slider value for one of the bodies in the upper left of the simulation to something very slight to find what happens. What you will see is a demonstration of Chaos Theory. Any slight modification to a perfect system creates a chain reaction of random chaos.
This is precisely the issue of modeling the Heliocentric System, and why its fundamental system cannot exist. Only very specific, sensitive, and highly symmetrical configurations may exist. The slightest deviation, such as with a system with unequal masses, or the minute influence from a gravitating body external to the system, will cause the entire system to fly apart. The reader is invited to decide for his or her own self whether those scenarios would occur in nature as described by popular theory.
N-Body Solution Galleries
Below are links to galleries of various Three Body and n-Body solutions which have been found. One should note the lack of heliocentric orbits and the inherent semmetry inherent in all orbits.
Wolfram Science
https://www.wolframscience.com/nks/notes-7-4--three-body-problem/ (Archive)
" In Henri Poincaré's study of the collection of possible trajectories for three-body systems he identified sensitive dependence on initial conditions (see above), noted the general complexity of what could happen (particularly in connection with so-called homoclinic tangles), and developed topology to provide a simpler overall description. With appropriate initial conditions one can get various forms of simple behavior. The pictures below show some of the possible repetitive orbits of an idealized planet moving in the plane of a pair of stars that are in a perfect elliptical orbit. "
Institute of Physics Belgrade
http://three-body.ipb.ac.rs/ (Archive)
n-Body Choreographies
http://rectangleworld.com/demos/nBody/ (Archive) - Notice that the common theme is highly symmetrical shapes.
http://www.scholarpedia.org/article/Three_body_problem (Archive)
Euler Math Toolbox
http://euler.rene-grothmann.de/Programs/Examples/Three-Body%20Problem.html (Archive)
Find N-Body Solutions in Your Browser
Supercomputing Challenge
Programming students participated in the New Mexico Supercomputing Challenge to simulate the solar system and found issues with creating basic orbits:
Simulation of Planetary Bodies in the Universe (N-Body) (Archive) (Source Code)
" Our solar system is an N-body system. N-body simulation is the simulation of astral bodies under gravity, using laws of classical mechanics to define how the astral bodies move. The goal of our project is to model the N-body problem in NetLogo. Code defining how astral bodies interact implements the inverse square law and a gravitational constant to calculate gravitational force between them.
Verification and Validation
Even though our model is not entirely accurate, it recreates with graphical simplicity and mathematical correctness of the N-body simulation. Through many many trials, we realize that normal orbits are incredibly complex and hard to obtain through any normal means, and causes us to conclude that our own solar system is an incredible anomaly of the universe. "
The PDF report explains with additional details that all attempts at observing orbit were unsuccessful.
Universe Sandbox 2
Universe Sandbox 2 (Universe Sandbox ²) is a physics based space simulation developed and published by Giant Army. It has often been claimed that this simulation provides evidence that the Sun-Earth-Moon System and the Solar System are able to be simulated with gravity.
Read the following from a developer blog post and decide whether the program is using a full simulation of gravity:
Working Through the N-Body Problem in Universe Sandbox ² (Archive)
" By default, the simulations in Universe Sandbox ² try to set an accuracy which prevents orbits from falling apart due to error. This means setting a maximum error tolerance for each step and also making sure the total error doesn't reach an upper limit.
If you crank up the time step, the simulation then has to take fewer, larger steps. This means the potential for greater error. And the greater the error, the more likely it is that an orbit, which otherwise would be stable, falls apart. Moons crash into planets, Mercury gets thrown out of the solar system — things like that.
This isn't what most people want in their simulations. But at the same time, most people also don't want a limit on how fast they can run their simulation. This is a problem.
An imperfect solution
So how can we get around this problem? How can we accurately simulate thousands of objects while still allowing for large steps forward in time? For example, what if you wanted to simulate our solar system on a time scale of millions of years per second so that you could see the evolution of our Sun?
One solution proposed by Thomas, our physics programmer, is to allow for a special mode within simulations running at high time steps. This mode (which of course could be toggled) would collapse the existing n-body simulation into a series of 2-body problems: Moon & Earth, Earth & Sun, Europa & Jupiter, Jupiter & Sun, etc.
Solving a 2-body problem is much easier than solving an n-body problem. Not only is it faster computationally, but there is also a relatively arbitrary difference between figuring out where the two objects will be in one year and where they'll be in a million years — it still requires just one calculation. So if you collapse an n-body simulation into a series of two-body problems, the simulation could take one big step forward, instead of taking the small steps needed for calculating it as an n-body problem.
The results won't be entirely accurate, as this method would effectively ignore all gravitational influences outside of the main attractor. As mentioned before, calculating Earth's orbit by looking at how it interacts with just the Sun is not accurate, as Earth is also affected by every other body. The Sun, however, is the most significant factor by far, because it is much more massive than any other object in our solar system. The other, much smaller forces tend to have little effect overall in non-chaotic systems. So while it's not correct, it's close enough when simulating something relatively stable like our solar system.
This isn't a perfect solution. But we think it could be an improvement over the current system and its limitations, which leave you with the choice of either destabilizing the orbits with massive errors, or waiting days for the simulation to advance the millions of years needed for the Sun to evolve. Neither is particularly interesting. "
One might ponder that, surely, if all they had to do was to wait days for the simulation to advance millions of years for the 'sun to evolve' in order for heliocentric orbits to become possible, they could simply run that simulation and save its state to use as a baseline for further simulations.
Despite any fanciful allusions that the choice is between either "destabilizing the orbits with massive errors" or "waiting for Sun to evolve," and reassurances that our solar system is stable despite the inability of simulating it—all common statements to excuse away the problems of simulating bodies in heliocentric orbits—its developers freely admit that the program is not using a full simulation of gravity. The article states "By default, the simulations in Universe Sandbox ² try to set an accuracy which prevents orbits from falling apart due to error".
Symmetrical Simulations
The simulations are highly symmetrical with mass restrictions:
Over a Thousand New Solutions - New Scientist
From the New Scientist article Infamous three-body problem has over a thousand new solutions we read:
- " Perhaps the most important application of the three-body problem is in astronomy, for helping researchers figure out how three stars, a star with a planet that has a moon, or any other set of three celestial objects can maintain a stable orbit.
- But these new orbits rely on conditions that are somewhere between unlikely and impossible for a real system to satisfy. In all of them, for example, two of the three bodies have exactly the same mass and they all remain in the same plane. "
Clicking on the arxiv.org source at the bottom of the that article takes us to the paper The 1223 new periodic orbits of planar three-body problem with unequal mass and zero angular momentum, where we see at the bottom of p.1:
- " Therefore, without loss of generality, we consider m1 = m2 = 1 and m3 is varied. "
We see that these are symmetrical systems:
- FIG. 1. (color online.) Brief overview of the six newly-found families of periodic three-body orbits.
Over 600 New Orbits
Similarly, the phys.org article Scientists discover more than 600 new periodic orbits of the famous three-body problem (Archive) describes the discovery of other symmetrical orbits:
- " These 695 periodic orbits include the well-known figure-eight family found by Moore in 1993, the 11 families found by Suvakov and Dmitrasinovic in 2013, and more than 600 new families reported for the first time. "
Three Body Dynamics
In Three Body Dynamics and Its Applications to Exoplanets by Professor of Physics Z. Musielak (bio) and astrophysicist Billy Quarles, we see:
" The three-body problem is one of the best known scientific problems, and there are three main reasons. First, the problem has fundamental importance in science, mathematics and engineering. Second, the problem is truly difficult to solve, which has been manifested by thousands of papers written by numerous outstanding researchers, who have tried (very) hard but failed. Third, the problem can be stated simple enough, so non-experts can understand it and appreciate its importance. As described in this book, all attempts to solve this problem have enriched celestial and classical mechanics, and mathematics with many new methods, powerful theorems, and novel ideas that are already being used in applications in different fields of research. "
David Gozzard
Physcist David Gozzard (bio) says in his video Weird Orbits - the three body problem (Runtime - 4m):
" Three hundred and fifty years ago Isaac Newton formulated his theory of gravity Newton's theory unified the heavens and the earth under the same physical laws and neatly explained the orbits of the planets, the motion of comets, and how the moon causes the tides. Although Einstein's general relativity has supplanted Newton's theory as a better model of gravity, Newtonian mechanics got us to the moon and are still used to calculate the trajectories of spacecraft throughout the solar system. In spite of this success and more than three centuries of progress we still do not have a neat set of equations that allow us to calculate the orbital parameters of more than two objects at once. This is called the three-body problem, or more generally the n-body problem. "
Paul Nahin
From p.132 of Number-Crunching by Dr. Paul J. Nahin (bio):
" The study of how three massive bodies gravitationally interact is called the three-body problem, and its general solution eluded even the genius of Newton. But, of course, that didn't mean it was necessarily an impossible problem, just that it was a very, very difficult problem. Perhaps, it was hoped, with advancing technical knowledge and the appearance of an even greater intellect than Newton's, the three-body problem could be solved. That lure, of being the one that finally did what the great Newton could not, attracted some of the most brilliant analysts over the next 250 years. Such luminaries as the Swiss Leonhard Euler (1707-1783), the French Joseph Lagrange (1736-1813), and the German Carl Jacobi (1804-1851), for example, all tried their hands at it, but except for limited partial successes made under special, restrictive assumptions, the general solution of the three-body problem defeated every one of them. "
Vinay Ambegaokar
In the Chaos chapter (Archive) of Reasoning about Luck: Probability and Its Uses in Physics, its author physics professor Vinay Ambegaokar (bio) tells us that the three-body problem is not studied in the physics curriculum:
" The next simplest case is the 'three body problem' - sun, earth, and moon, for example - taking into account the attraction between each body and the other two. No simple solution to this problem exists, and it is not studied in the physics curriculum. "
Isaac Newton
On p.174 of Medical Reasoning: The Nature and Use of Medical Knowledge (Archive) its author Erwin B. Montgomery shares this quote from Newton:
" An example of a system that can be described explicitly by a mathematical metaphor proved unsolvable (at least explicitly in algebraic or integral functions) is the three-body problem, such as the orbits of the earth, moon, and sun when all three are considered simultaneously. While the two-body problem is solvable, such as the orbits of the earth and moon, even Newton recognized the difficulty and indeed potential intractability of the three-body problem, commenting in 1684 that "to define these motions by exact laws admitting of easy calculation exceeds, if I am not mistaken, the force of any human mind" (from a draft of De Motu, tentatively dated in December 1684; Wilson 1989). "
Martin Gutzwiller
The end section of a paper titled Moon-Earth-Sun: The oldest three-body problem (Archive) by physicist Martin C. Gutzwiller (bio) concludes that Newton's laws are not a sufficient explanation:
" The three-body problem teaches us a sobering lesson about our ability to comprehend the outside world in terms of a few basic mathematical relations. Many physicists, maybe early in their careers, had hopes of coordinating their field of interest, if not all of physics, into some overall rational scheme. The more complicated situations could then be reduced to some simpler models in which all phenomena would find their explanation. This ideal goal of the scientific enterprise has been promoted by many distinguished scientists [see Weinberg's (1992) Dream of a Final Theory, with a chapter ''Two Cheers for Reductionism'']....Many physicists may be tempted to see in Newton's equations of motion and his universal gravitation a sufficient explanation for the three-body problem, with the details to be worked out by the technicians. But even a close look at the differential equations (29) and (30) does not prepare us for the idiosyncracies of the lunar motion, nor does it help us to understand the orbits of asteroids in the combined gravitational field of the Sun and Jupiter. "
Mark Cunningham
On p.189 of Neoclassical Physics by physicist Mark Cunningham (bio) we read the following (Archive):
Classical Mechanics
" Issac Newton's notable success in providing a theoretical explanation for the motion of planets around the sun was followed quickly by his realization that the gravitational problem involving three bodies was immensely more difficult than the two-body problem. Where the two-body problem, as we have seen in Chapter 2, can be solved exactly, Newton's attempts to provide a concise mathematical description of the earth-sun-moon system were not successful.1 This, of course, is not due to Newton's lack of mathematical skills. Indeed, a series of notable mathematicians all applied their skills to the problem but without success, although it depends somewhat on how one defines success. It is true that no general solutions of the three-body problem have been constructed but the assault on the problem led to powerful new mathematical methods for understanding dynamical systems.2 "
Yet again, we find direct statements telling us that the venture of describing or simulating the earth-sun-moon system has been unsuccessful, from the time of Newton up to present. Numerous and notable mathematicians over the years have attempted to describe or simulate the earth-sun-moon system without success—telling us everything that we need to know about the systems of Newton and Copernicus.
Richard D. Mattuck
Contrary to common dogma, the ability of various fields to describe physical systems based on the underlying laws has been going down with time, not up. Richard D. Mattuck writes in his A Guide to Feynman Diagrams in the Many-Body Problem (Archive):
The Many-Body Problem for Everybody
" How many bodies are required before we have a problem? G. E. Brown [bio] points out that this can be answered by a look at history. In eighteenth-century Newtonian mechanics, the three-body problem was insoluble. With the birth of relativity around 1910 and quantum electrodynamics in 1930, the two- and one-body problems became insoluble. And within modern quantum field theory, the problem of zero bodies (vacuum) is insoluble. So, if we are out after exact solutions, no bodies at all is already too many! "
Sundman's Solution
A typical reply to the topic of the Three Body Problem is to perform some light searching and cite Sundman's solution as a solution to the Three Body Problem. This is displayed as front and center in the Three Body Problem Wikipedia page as a solution to the Three Body Problem.
" At the beginning of the 20th century, Karl Sundman approached the problem mathematically and systematically by providing a function theoretical proof to the problem valid for all values of time. It was the first time scientists theoretically solved three-body problem. However, because there was not enough qualitative solution of this system, and it was too slow for scientists to practically apply it, this solution still left some issues unresolved.[30] "
On p.5 of Three-Body Problem (Archive) by physics professor Z.E. Musielak and astrophysicist B. Quarles we read more about Sundman's solution, and how his solution compared to Poincare's postulation that the motions of three bodies were unpredictable -
" Indeed, Painleve was right and Sundman [1912] found a complete solution to the three-body problem given in terms of a power series expansion. Unfortunately, Sundman's solution converges very slowly so that it cannot be used for any practical applications. An important question to ask is: Does the existence of Sundman's solution contradict the unpredictability of motions in the three-body problem postulated by Poincare [1892]? Well, the answer is that it does not because trajectories of any of the three bodies cannot be determined directly from Sundman's solution, which means that the trajectories can still be fully unpredictable, as this is observed in numerical simulations (see Section 4, 5 and 8) "
According to the above the solution is about modeling the result of a potentially chaotic interaction, and does not guarantee any predictable or stable result.
Stability of the Solar System
It has been asserted that Laplace and Lagrange demonstrated the stability of the Solar System. On this topic, Professor H. Scott Dumass tells us in The KAM Story (Archive):
" In the early 19th century, building on earlier work of Lagrange, 12 Laplace 'proved' the stability of the solar system, and although this work was an important step and is mathematically correct as far as it goes, it was soon recognized that he had not shown stability for the n body problem, but rather for an attenuated version of it in which higher-order interactions between planets are ignored. Such claims and half-successes by the mathematical giants of the ages (and many other less-than-giants) of course only added celebrity to the n body problem, and to the stability problem in particular. "
Later researchers went on to 'simulate' the solar system with two body approximation and geometry preserving schemes. See the pages Numerical Solutions and Symplectic Integrators.
N-Body Symmetry
Code documentation for N-Body simulation software at Rosetta Code states the following:
https://rosettacode.org/wiki/N-body_problem (Archive)
" The slightest perturbation from symmetry causes the system to become unstable. "
See Also
- Three Body Problem - The heliocentric Sun-Earth-Moon system cannot be simulated
- Numerical Solutions - The available solutions for celestial systems do not fully simulate gravity
- Perturbation Methods - Epicycles are still used for astronomical prediction
- Eclipse Prediction - The eclipses are predicted with cycles and patterns
- Symplectic Integrators - A special method of orbital simulation which preserves geometry and forces stability


text:
Clayton Kershaw (5-5, 2.06) vs. Tim Lincecum (4-7, 4.52).
So this happened last night:
Remember when the Kershaw-Lincecum rivalry was going to be one for the ages? Well, Kershaw kept up his end of the bargain and is in position to help the Dodgers sweep the Giants tonight.
Meanwhile, everybody from the projected opening day lineup is back, sans Carl Crawford, so let's enjoy the maximum firepower until the next injury occurs.

subset: commoncrawl


text:
In the book, it's described as a swiss chard tart, but I had beet and collard greens to use. Those were cleaned and chopped and sauteed in olive oil with shallot and thyme. I've used Whole Foods' all butter puff pastry with good results a few times now, and that's what I used here. The puff pastry was thawed and then just unfolded onto a baking sheet. No rolling was required. That was topped with a mixture of ricotta, egg yolk, olive oil, creme fraiche, and salt and pepper. Goat cheese was crumbled on top of that. Then, the cooked and cooled greens were squeezed to remove liquid and then spread on top of the cheese mixture and were topped with more crumbled goat cheese. It was baked for 25 minutes while the relish was assembled. The pastry with cheese and greens was a great start, but what really made this dish was the currant pine nut relish. Pine nuts were toasted and set aside. Olive oil was heated in a saute pan and a rosemary sprig and a dried chile de arbol were added. Minced onion went into the pan, stewed for 10 minutes, and then was transferred to a small bowl. The saute pan was then used to reduce a quarter cup of balsamic vinegar down to one tablespoon. Meanwhile, currants were plumped in hot water and then drained. The bowl of sauteed onions was mixed with the toasted pine nuts, plumped currants, and reduced balsamic, and chopped parsley was added.
The richness of the ricotta and creme fraiche was fanastic with the greens. And, this could, of course, be made with milder spinach, but let me tell you about the relish first. The currant pine nut relish with the sauteed onions and reduced balsamic vinegar was such a perfect complement to the greens, I would recommend using the boldest flavored greens you can find. The layers of sweetness and spice and the hint of acidity mingled with the bitterness of the greens in amazing ways. Instead of making this to use up some greens, in the future, I'll be making this because it's really delicious.


text:
Have you seen The List?
A few weeks ago Danny Evans at Dad Gone Mad invited all of his readers to post links to their blogs, and then encouraged all of them to spread some bloggy love.
Well, earlier this week Dee Dee at Random Daily Ramblings compiled a single list of all of those blogs and posted them.
She was then challenged by Heather to visit and comment on all of them. She accepted the challenge (on the condition that Heather do so as well).
While they were busy challenging each other I went ahead and finished The List.
It took days, and my daughter has been in the same diaper since Thursday, and I think she's had to teach herself to cook, and my wife has since fled to Seattle and Chicago in succession.
But it was worth it.
I met a ton of great bloggers out there in the world (many of whom were already daily reads for me, some of whom are now daily reads for me). I won't post individual links, because I want all of you to go and traverse the list. Do it at your own pace (because my pace might be considered child neglect). You don't have to let them know that they're on the list, although they might know already. Just leave a comment: a hi, a hey, a "that's hilarious" or "great picture" (my two favourites).
And, if you are really masochistic, turn on the "e-mail follow-up comments" function of the blogs you hit. Oh my god, I'll be going through my inbox for days.
One upside to doing that, though, is you can see who's following along behind you. Currently in second place on the Race to Finish the List is Mad Woman Meg. I've seen her dogging my steps for days. But she didn't have the benefit of naptimes coinciding with no hockey (the Red Wings swept the Avalanche on Thursday, so I have to wait until next week for their next round).
Another thing about doing The List is the chain-letter-type bloggy love you get in return. Sure I had to comment on over a hundred blogs over the last few days; it was fun. But in return I also had a ton of new visitors myself.
Now, if only it hadn't been the "Stand-Up Tragedy" post that they landed on :}
Now, if anyone is any good at designing Blog Badges maybe you could throw together a "I'm on The List" badge that links to Dee Dee's site, or a "I Completed the List" badge.
For me. Because I did it.
Your turn.


text:
Getting the Most Out of Your HVAC System This Summer
April showers bring May flowers … and often June, July and August heat waves. If you'd like to enjoy your HVAC cooling system to the fullest this summer without breaking the bank, spring is the time to take a few simple steps to prepare.
First Things First
Why not do a test run of your cooling system right now? This way, you can see how well it's working and troubleshoot any issues before the thermometer soars way out of sight. Besides safeguarding your family comfort, you'll be able to quickly get professional help for problems that are beyond your DIY scope. Rule of thumb: HVAC technicians are almost invariably easier to get hold of during the off-peak season – and their rates may reflect this.
Next, go outside and inspect the exterior unit for debris, dead leaves and plant growth that have the potential to block the airflow.
Regular Maintenance
Make sure you check your HVAC filter regularly. During heavy summer use, the filter will likely need to be washed or replaced about once a month (possibly more if you live in an especially dusty area or have house pets). While you're at it, dust the grates as well. Clean the evaporator coils annually, straightening any bent ones.
Schedule your annual HVAC tune-up if you are due for one. A system that is over 10 years old may be costing you more in electricity bills than it is worth, especially if you live in an area with long, hot summers such as Austin, Texas. Ask your Austin HVAC tech or your local HVAC service provider whether it would pay to install a new Energy Star system instead. If you do opt for a new model, order it ASAP and make sure it is properly installed.
Save Electricity ... and Cash
Use your HVAC system's programmable thermostat to schedule operation for times when you are at home. Efficient use of this handy device can save you close to $200 per year on your utility bills. When your family's schedule changes, reassess your needs and adjust the programmable thermostat if appropriate.
For further savings, set the thermostat a few degrees higher than you normally would and use a low-energy-consumption fan to help circulate the cool air. Ceiling fans should be switched to turn in the correct direction (counter-clockwise); this directs hot air upward and away from the center of the room.
Keep Cool Air In, Hot Air Out
Prevent leakage of precious cool air by sealing around the HVAC unit and your ducts' seams and connections. Then wrap the ducts in insulation. If the ducts pass through an attic space, consider insulating that too. Sealing and insulation require a certain amount of effort but will be well worthwhile in energy efficiency both summer and winter.
It's recommended to seal around windows, doors and baseboards also or even to replace windows if necessary.
Close your windows and drapes during the day to exclude the hot air; then open them at night to ventilate your home. You may wish to install interior or exterior blinds, shutters, shades or awnings, particularly on south- or west-facing windows. Additional energy effective window treatments such as reflective films and insulated panels are available as well.
Reduce the heat that is generated inside your home by using your electric clothes dryer during cooler hours (or line drying!) and cooking at off-peak times, microwaving or barbecuing outdoors.
Laura Firszt writes for Networx.com.
Related Articles
Looking for a Pro? Call us(866) 441-6648


text:
Enjoy your favorite online videos anywhere
ChrisPC VideoTube Downloader Pro
A powerful software that allows you to download videos from 20.000+ websites, including TV3 a la carta, Pluzz France, NRK, TV2, YouTube, Vimeo & convert them to popular video formats like MPEG-4, MKV, MP3.
- Downloads MP4, FLV, MOV, MP3
- Download whole YouTube playlist
- Support for RTMP, HDS & HLS protocols and VOD files downloads
- Link Finder with Chrome mode, IE mode, Android mode, iOS mode
Download Now! Purchase Now! Supported sites


text:
Hobie Island Club
The Hobie Island Club is a place to meet other Hobie Mirage Adventure Island and Hobie Mirage Tandem Island owners to share passions for the waterways and oceans of our world. Hobie Dealers are organizing local Island Clubs worldwide. The Hobie Island Club will assist in the introduction of Island owners to one another where dreams of sailing to places unknown and countless adventures can become a reality.
Find your local Hobie Island Club
How to Join?
Browse the Hobie Island Club map to find a local Island Club near you. Click the club marker and click 'Join this club', then simply fill out the form to the left and click 'Join'. If you don't see a club near you, continue reading.
Why Join?
Join the Hobie Island Club with your fellow Adventure and Tandem Island owners. Hobie Island owners are now sailing on oceans, rivers, lakes and waterways in over 40 countries worldwide. Island sailors are meeting in pairs and in the dozens to sail and have fun.
Can't Find an Island Club near you?
Although new clubs are being created at a rapid pace, there are some areas where clubs have not yet been established. If there isn't an Island Club near you at the moment, don't let this keep you from getting out on the water with friends. As the number of Island owners who join the Hobie Island Club increases we will be working closely with our Hobie Dealers to encourage club creation in most all areas where Hobie is present.
The Hobie Island Club Facebook page is a great place to share all of your Island Club experiences. Upload your photos and videos, and keep in touch with other Island enthusiasts.
Upcoming Events
There are no events.


text:
Discuss mobile application development issues. e.g. games development, wap development etc.
Use this control to limit the display of threads to those newer than the specified time frame.
Allows you to choose the data by which the thread list will be sorted.
Order threads in...
Note: when sorting by date, 'descending order' will show the newest results first.


text:
Now showing items 1-1 of 1
Harmonizing circumpolar monitoring of Arctic fox: benefits, opportunities, challenges and recommendations
(Journal article; Tidsskriftartikkel; Peer reviewed, 2017-08-16)
The biodiversity working group of the Arctic Council has developed pan-Arctic biodiversity
monitoring plans to improve our ability to detect, understand and report on long-term
change in Arctic biodiversity. The Arctic fox (Vulpes lagopus) was identified as a target of
future monitoring because of its circumpolar distribution, ecological importance and reliance
on Arctic ecosystems. We provide ...


text:
From the diaries.
Dear Mister President:
I stopped by your house the other day because I wanted to talk with you about what's happened since we last met.
I vividly remember the day you passed through my neighborhood during your 2008 campaign for President. I looked you in the eye and asked how your tax plan would affect a business I was going to buy. Ultimately, after describing a complicated tax scheme that seemed to require jumping through hoops to avoid being punished for success, you finished by saying that "when you spread the wealth around, it's good for everybody". Surely you remember that, don't you?
More after the jump…
In the time since we first met, a lot of folks have lost their job while you got the one for which you were applying. Funny how that worked out: millions of folks out here are living the nightmare of broken dreams, lost livelihoods, and crushing unemployment under your watch while you enjoy the perks of your new job being President of the greatest country on earth. It must be nice to get lavish vacations in exotic places for you and your family, playing unending rounds of golf at the world's best country clubs while most of us Americans are just happy to be able to pay our bills.
Your burdensome and punishing regulations made sure that job-creating small businesses suffer like never before. And yet, through it all, your friends, bundlers, and campaign contributors seem to be doing just fine. Thanks to your "spread the wealth" message, we've got people "occupying" legitimate businesses and industries, terrorizing the children of business leaders in their own homes, and calling for government control of everything and everybody. I thought you'd like to hear how all that is working out for us out here in the real world.
Mister President, I think it's time you and I continued our conversation.
I tried early and late, but you weren't home and I couldn't find anyone to take a message. Perhaps you had a good score at the golf course today? Any luck getting more campaign donations? I'm sure that's taking up a lot of your energy.
By the way… you may have heard I am running for Congress in the OH-9 district. I'm going to win. Maybe you can stop by my office when you and your family visit DC and I'll show you around my new digs. We can finish that chat then.
Crossposted at Joe for Congress 2012


text:
Kim Kardashian & Kanye West -- North West's Name Is Non-Directional
Kim & Kanye North West Is Non-Directional
Kim Kardashian and Kanye West were not inspired by a compass when they named their kid North ... fact is, the name's more inspirational than directional.
Sources close to K & K tell TMZ ... they chose the name North because they see it as a metaphor for "up", telling friends, "What's North of North? Nothing." Translation ... nothing better.
We're told the duo believes baby North is their highest point together as a couple ... the pinnacle of the relationship ... and they consider her their "North Star."
Kinda sweet. Almost makes ya feel bad for mocking it, right?


text:
President Obama's second inaugural address is being hailed (and attacked) as the most progressive speech he's ever given, a full-throated game changer that suggests an aggressive new vision for his second term. I don't know. I thought it was kind of boring. It seemed like a rehash of his we're-all-in-this-together campaign themes, with some familiar shots at you're-on-your-own Republicans. Then again, I've always been less impressed than most by Obama's words — I thought his 2012 convention speech was a dud too — and more impressed than most by his deeds.
I saw the speech as an extension of Obama's divide-and-conquer legislative strategy, trying to break pragmatic Republicans — the kind who understand that "we cannot mistake absolutism for principle" — away from rejectionist Tea Partiers. The President repeatedly described a broad national consensus, then repeatedly claimed that his harshest critics are outside it: antigovernment extremists who don't want to build railroads, educate children or protect the vulnerable; reactionaries who "still deny the overwhelming judgment of science" regarding climate change; neocons who don't understand that "enduring peace and lasting security do not require perpetual war."
He also implied that Republicans pushing for deep cuts in entitlements during the current round of fiscal negotiations are so far out of the mainstream they believe "that America must choose between caring for the generation that built this country and investing in the generation that will build its future." Here he is twisting the knife:
We do not believe that in this country, freedom is reserved for the lucky, or happiness for the few. We recognize that no matter how responsibly we live our lives, any one of us, at any time, may face a job loss, or a sudden illness, or a home swept away in a terrible storm. The commitments we make to each other — through Medicare and Medicaid and Social security — these things do not sap our initiative. They strengthen us. They do not make us a nation of takers. They free us to take the risks that make this country great.
I thought that was a clever way to trash Mitt Romney, Paul Ryan and other Republicans who see half their fellow Americans as lollygaggers. The subtext was: My critics are reactionary extremists! I happen to agree, but I don't see what's so statesmanlike or visionary about saying so in a speech billed as a homily about common ground. Obviously, Obama wants reality-based Republicans to abandon the dead-enders; that's what happened on the fiscal-cliff deal, which got Obama just about everything he wanted, as well as the relief bill for Hurricane Sandy victims. But equating opposition to Obama's policies with nostalgia for an America where "parents of a child with a disability had nowhere to turn" might not be the best way to sow that kind of division in the GOP.
In any case, Obama has governed as a left-of-center pragmatist, and I see no evidence from his rhetoric that he intends a different approach in his second term. He did make a strong pitch for climate action, but he did that in his first inaugural too, and then he followed up with strong climate action. He did make a strong pitch for gay marriage, but he's been doing that for the past year. Anyone who thinks that Obama never talks about alleviating poverty or training science teachers or building research labs or reducing inequality or pushing equal pay for equal work has never heard Obama talk.
"We must act, knowing that today's victories will be only partial," he said. That's classic Obama. He's not an Ivory-soap liberal. He's a guy who gets things done. His progressive rhetoric doesn't impress me, but he's making a lot of progress.


text:
Yhc/Javascript/Programmers guide
Up from the ground
This part of the Programmers Guide is a collection of notes taken during the development of the first Haskell-in-Browser demo, a program that accepts users' input using a HTML input element, and repeats whatever the user typed upon pressing Enter
. Additionally, Roman numeral conversion will occur if user's input is a decimal or a Roman numeral that can be converted. A timer is provided to measure code performance. More...
DOM framework
In this section of the Yhc/Javascript Programmers Guide, the implementation of Document Object Model in Haskell is described. Continuation Passing Style usage is discussed. The section provides details on conversion of DOM specifications from Interface Definition Language to Haskell, and related issues and features. Finally, examples of Haskell programming with DOM are provided.
Continuation passing style
Unlike the previous Echo example, the DOM framework uses CPS rather than monads to provide proper sequence of Haskell expressions evaluation. The choice of CPS is dictated by the internal structure of Fudget kernels which use CPS. An original Fudget (built on top of the X11 protocol and related I/O) sends a message to Fudlogue each time an input/output action is needed (even one not involving waiting for any asyncronous input, such as opening a window). With DOM interface implemented in CPS style, all synchronous operations (such as creating a DOM node, and basically all operations not involving event handling) can be performed without such message exchange, which significantly reduces execution overhead.
Note: Fudgets (stream processors) unfortunately did not make it into web browser because of terrible memory leaks (almost 500k browser size increase on each user action like mouse click). there is however another rationale to use CPS, that is to simulate cooperative threads via scheduling further execution of continuations, see the new Threads and events section.
Wrapper functions
A function conforming the Continuation Passing Style always has as its last argument, continuation, which will take the result of this function's application to its other arguments, as an argument. Any non-CPS expression may be converted into a CPS one by applying a wrapper which transforms the expression into a function with one argument:
toCPS x = \k -> k x
where x
is an expression to convert. The expression will be passed to the continuation unevaluated.
A variant of this wrapper:
toCPE x = \k -> x `seq` (k x)
forces evaluation of the expression before passing it to the continuation.
for this purpose. So, at the first look the following might be enough:
getTimeStamp' a = unsafeJS "return new Date().getTime();"
The dummy parameter a
is necessary to prevent creation of a CAF, that is, every time the function is called with any value of this parameter, evaluation will take place.
To convert this expression, e. g. getTimeStamp' 0
in CPS, it needs to be given a parameter representing continuation which will use its result, that is, the current time. This may be written as:
getTimeStamp k = k `seq` (getTimeStamp' 0)
where k
is a continuation which will be given the current time. The seq
combinator ensures that the continuation will get an evaluated expression.
So, in a larger example:
main = getTimeStamp $ \t1 ->
foo $ \_ ->
bar $ \_ ->
getTimeStamp $ \t2 ->
putLine ("Time interval: " ++ show (t2 - t1) ++ " ms") $ id
two time stamps will be obtained, before and after the two computations foo
and bar
(whose results are not of interest) are performed. The result will be output with some imaginary function putLine
The id
call after putLine
is necessary to "close" the chain of continuations: the value that putLine
returns, becomes return value of main
. If however it is necessary to return something else, say, the length of the time interval measured, the last row might look like:
putLine ("Time interval: " ++ show (t2 - t1) ++ " ms") $ \_ ->
(t2 - t1)
In general, the example above gives some idea how Haskell programs using DOM in CPS style look like.
The CPS
module should be imported by any Haskell module using the Continuation Passing Style constructs and the DOM framework. The CPS
type itself is defined as:
type CPS c a = (a -> c) -> c
So, if a function has the return type CPS x y
, this means that its continuation would accept a value of type y
and return a value of type x
Unsafe interfaces with CPS
Usage of unsafeJS
has not changed from one described above. This is still a pseudo-function accepting a string literal with Javascript code as an argument. The Javascript code supplied will be wrapped into a Haskell-callable function.
To access properties of Javascript objects, the following CPS-aware functions are provided:
unsafeGetProperty :: String -> b -> CPS d c
unsafeSetProperty :: String -> b -> c -> CPS d c
unsafeCheckProperty :: String -> b -> CPS d Bool
The first function accepts Javascript property name as its first argument, and a reference to a Javascript object as the second. It passes the value of the property retrieved (in type-agnostic manner) to its continuation.
The second function accepts Javascript property name as its first argument, the value to set the property to as the second argument, and a reference to a Javascript object as the third. The continuation gets the reference to the Javascript object with updated property (that is, the update occurs in-place).
The third function checks whether the given property is set to null
, and passes True
to the continuation if it is not null
, and False
All three functions evaluate their arguments.
To unsafely convert Javascript values to Haskell Num
and String
values, the following two functions are provided:
unsafeToNum :: (Num b) => a -> CPS c b
unsafeToString :: a -> CPS c String
The first function calls the Number
Javascript constructor on the argument's value, the second calls the String
Javascript constructor on its argument. Both functions evaluate their argument first.
To catch exceptions, the following function is provided:
catchJS :: a -> (b -> a) -> a
This function takes its first argument and evaluates it. If an error occurs (Javascript exception is thrown), it is passed as an argument to the function specified as catchJS
's second argument. The function handling an exception should either return a value of the same type as the failed expression does, or to (re)throw an exception. The error
function from the Standard Prelude is implemented using the Javascript throw
Programming examples
The EchoCPS Wiki page contains an example of a working Echo demo program written using the DOM Level1 interfaces.
The EchoCPS2 Wiki page contains an example of a working Echo demo program written using the DOM Level2 interfaces which have been added to the Javascript backend. The only major difference between these two example programs is better typing of event handlers based on the definitions that appeared only in DOM Level2 specifications.
DOM and the Web Consortium
The Document Object Model (DOM) is the base interface to access the content and structure of documents in a web browser. The Web Consortium has a page dedicated to DOM.
This Programmers Guide is based on the Document Object Model (DOM) Level 1 Specification (Second Edition) provided by the Web Consortium. This version of DOM, although not very new, can serve as the greatest common denominator for many types of web browsers available these days.
DOM and Interface Definition Language (IDL)
General information
The Web Consortium uses a subset of the Interface Definition Language proposed by the Object Management Group (OMG IDL) to describe the abstract interface to the Document Object Model, so it may be implemented in various programming languages. These definitions cover basic operations to create and delete document nodes, manipulate their attributes and contents, and insert/remove nodes within the document loaded into the browser.
Conversion to Haskell
Technical details of IDL to Haskell conversion
This section gives general details of correspondence between IDL definitions and generated Haskell code. Deeper details related to programming will be discussed in next sections.
Consider this IDL definition (from the DOM section of the definitions):
interface Attr : Node {
readonly attribute DOMString name;
readonly attribute boolean specified;
// Modified in DOM Level 1:
attribute DOMString value;
// raises(DOMException) on setting
One interface definition in IDL results in creation of one Haskell module with the same name as the interface has. Module name will be prefixed with DOM.Level1
, that is, the #pragma prefix "w3c.org"
in the beginning of the file is ignored.
The Haskell translation is:
module DOM.Level1.Attr
(get'name, get'specified, set'value, get'value) where
import DOM.Level1.Dom
import CPS
import UnsafeJS
import DOM.Level1.Document (createElement)
get'name :: (CAttr this) => this -> CPS c String
get'name = unsafeGetProperty "name"
get'specified :: (CAttr this) => this -> CPS c Bool
get'specified = unsafeGetProperty "specified"
set'value :: (CAttr zz) => String -> zz -> CPS c zz
set'value = unsafeSetProperty "value"
get'value :: (CAttr this) => this -> CPS c String
get'value = unsafeGetProperty "value"
Additionally, in the DOM.Level1.Dom
module, the following is defined (comments added):
data TAttr = TAttr -- phantom type for the interface
class (CNode a) => CAttr a -- class reflecting inheritance from Node
instance CAttr TAttr -- interfaces of Attr are implemented
instance CNode TAttr -- interfaces of Node are implemented
Attributes that have readonly
in their definitions only have getter methods (e. g. get'name
). The rest of attributes also have setter methods (e. g. get'value
, set'value
). Getter and setter names are produced by prefixing IDL attribute name with get'
and set'
The Attr
interface does not have methods, only attributes. The following interface illustrates how methods are represented:
interface NodeList {
Node item(in unsigned long index);
readonly attribute unsigned long length;
module DOM.Level1.NodeList (item, get'length) where
import DOM.Level1.Dom
import CPS
import UnsafeJS
import DOM.Level1.Document (createElement)
item :: (CNodeList this, CNode zz) => this -> Int -> CPS c zz
item a b = toCPE (item' a b)
item' a b = unsafeJS "return((exprEval(a)).item(exprEval(b)));"
get'length :: (CNodeList this) => this -> CPS c Int
get'length = unsafeGetProperty "length"
There also are related lines of code in the DOM.Level1.Dom
module (not shown as they are logically identical to already reviewed).
The item
method, as implemented in Haskell, takes the reference to the DOM element (NodeList
) as the first argument, this
. The second argument is the index of a node in the NodeList
, corresponding to the in unsigned long index
in the IDL definition. The last argument is the continuation. Type constraints (CNodeList this, CNode zz) =>
state that the method operates on instances of the CNodeList
class, and values passed to the continuation are instances of the CNode
Body of the method contains a type-aware wrapper over the unsafe code calling appropriate item
method on the Javascript object implementing the NodeList
Known omissions
- Exception information (
) is completely ignored by the converter. If an exception in Javascript code occurs, it should be treated as described above, in the Unsafe interfaces with CPS section.
- The converter makes no distinction between
- The converter does not tolerate multiple methods with the same name, but different number of arguments, within a single interface. It is however possible to have methods with the same name (regardless of number of arguments) in different interfaces. The
methods serve as a good example: they appear in at least two HTML elements: <input> and <textarea>. Developers are recommended to useimport qualified
statement for importing modules with conflicting method names, and use qualified names to resolve ambiguities.
Haskell DOM vs. Javascript DOM
Haskell phantom types vs. Javascript object types
A phantom type is created for every interface defined in OMG IDL files provided by the Web Consortium. Examples above illustrated this. So, this is important that all interface names were unique across all IDL files that are processed by the converter at once (both toplevel and include). More examples of such phantom types:
data TDOMImplementation = TDOMImplementation
data TNode = TNode
data TNodeList = TNodeList
data TNamedNodeMap = TNamedNodeMap
data TCharacterData = TCharacterData
data TAttr = TAttr
data TElement = TElement
data TText = TText
data TComment = TComment
data TCDATASection = TCDATASection
data TDocumentType = TDocumentType
Names of these types are derived from interface names by adding the capital letter "T" at the beginning.
Haskell type classes reflect interfaces inheritance
IDL, like many other object-oriented languages, features inheritance between interfaces defined. This means that an object implementing an interface X
funcitonality, also implements functionality of interface Y
, as well as all ancestors of Y
if declared as
interface X : Y {
Let's trace a chain of inheritance of the HTMLButtonElement
which represents a <button> tag:
interface HTMLButtonElement : HTMLElement
interface HTMLElement : Element
interface Element : Node
interface Node
which basically means that all methods and properties of Node
are expected to be implemented in HTMLButtonElement
To tell this to the Haskell compiler, the type constraints mechanism is involved:
class (CHTMLElement a) => CHTMLButtonElement a
class (CElement a) => CHTMLElement a
class (CNode a) => CElement a
class CNode a
The correspondence between these two examples is clear. Names of classes are derived from interface names by adding the capital letter "C" at the beginning.
To enable the desired functionality on the correct (phantom) data types, instance declarations are added:
data THTMLButtonElement = THTMLButtonElement
instance CHTMLButtonElement THTMLButtonElement
instance CHTMLElement THTMLButtonElement
instance CElement THTMLButtonElement
instance CNode THTMLButtonElement
So, if we have a function that operates on Nodes (and therefore has (Cnode a ...) =>
in its type signature), it will accept values of the THTMLButtonElement
type because of the above instance declarations, but not a TNodeList
values because declaration for NodeList
interface NodeList {
Node item(in unsigned long index);
readonly attribute unsigned long length;
so NodeList
does not inherit from Node
. It is worth saying that Javascript code (which is type-agnostic) would likely accept passing a NodeList
value to a function operating on Nodes. At best, a run-time exception would occur; at worst, some hard to find problems might be introduced diring the execution of such a function. Haskell compiler would catch this at the compilation stage.
The this
object reference in Haskell code
In Javascript, methods of some object have an implicit argument, this
. When a method is executed, the argument holds a reference to the object the method was invoked upon. Thus, if we had a DOM object implementing the NodeList
interface, and wanted to extract a n
th item of it, we would write:
var itm;
var nl = /* obtain the NodeList reference here */;
itm = nl.item(n); /* item is a (only) NodeList's method taking a number */
Haskell does not allow to have such an implicit argument to a function. Instead, this
is defined explicitly:
item :: (CNodeList this, CNode zz) => this -> Int -> CPS c zz
Equivalent Haskell code to retrieve a n
th item would be:
{-- obtain the NodeList reference here --} $ \nl ->
item nl n $ \itm ->
{-- itm may be used further on in the code --}
Threads and events
Cooperative threads
There is however a Javascript function window.setTimeout
which may be used, in combination with CPS, to simulate cooperative threads. Combining this technique with run-once auto-cleaning event handlers allows to utilize an event-driven programming model with cooperative threads (similar to what was used in MS-DOS based versions of Windows).
The setTimeout
Haskell primitives
In Haskell terms, there are three things to deal with: a timeout (an integer number), an expression to evaluate after the timeout expires ("child" thread), and an expression to evaluate right after the timeout has been set ("parent" thread).
The basic threading primitive (defined in the UnsafeJS
-- Fork execution for certain amount of time (including 0) by setting timeout
-- and passing a value to be evaluated then (b) and right now (c).
forkAfter :: Int -> b -> c -> c
forkAfter a b c = (fork' a b) `seq` c
fork' a b = unsafeJS
"var t=contNum++;var s='exprEval(delCont['+t+']);delCont['+t+']=null;';
delCont[t]=b;window.setTimeout(s,exprEval(a)); return 0;"
The contNum
and delCont
objects are global Javascript variables defined in Runtime.js
. The former provides unique number for each delayed continuation, and the latter acts as a storage of references to continuations.
Note: One thing to be added here: after some number of forks, the delCont
object should be cleaned from nullified references to continuations that executed in the past; this requires trivial changes in Runtime.js
Javascript event handlers may be used similarly, considering that an event handler may execute a delayed continuation, thus allowing a thread to wait for event. An event handler should nullify itself at its target (that is, if a onclick
handler is executed, its target object should get its onclick
attribute set to null
before the handler exits. Another convention: if an object already has an event handler installed for certain event type, it cannot be replaced with another handler, thus guaranteeing that one thread will not recapture events that another thread is waiting for.
The basic event primitive (defined in CDOM.Level2.Events
-- Wait for an event from an element. Execution of the continuation given
-- is resumed as the event has been received. True is returned if the element
-- was not waiting for another event, False otherwise.
waitFor :: (CEvent e, CElement c) => c -> String -> (e -> Bool) -> Bool
waitFor elt evid k =
unsafeCheckProperty ("on" ++ evid) elt $ \h -> case h of
True -> False
False -> secl evid k elt $ \_ -> True
The secl
function used by this primitive installs a self-clearing event handler for a specified type of events. Once executed, the handler removes itself from its target.
Usage examples
This piece of code sets focus on an input element (referred to by inp
and starts the main event loop which will receive information from this input element for further processing):
focus inp $ \_ ->
forkAfter 0 (mainY inp) $
-- the rest of the program
This piece of code reads each character input from inp
, and when Enter
is pressed, passes the whole string to its continuation:
readChar :: THTMLInputElement -> CPS Bool Int
readChar inp k = waitFor inp "keypress" $ \e ->
get'keyCode (e :: TKeyEvent) $ \c -> k c
readLine inp k = readChar inp $ \kci ->
if kci == cDOM_VK_ENTER
then get'value inp $ \s -> k s
else readLine inp k
This piece of code reads the whole line, and performs some actions (omitted in this example) depending on the length of input:
mainY inp = readLine inp $ \v ->
if length v > 0
-- some actions
mainY inp
-- other actions
mainY inp
The function loops infinitely, so everything a user types will be processed.
Message boxes
Message boxes provide a way for pseudo-threads to communicate with each other. Programmatically, a message box is a mutable memory cell holding a continuation that a message sent is to be passed to. Objects of type Data.JSRef
are used for this purpose.
A simpliest message box that is capable of holding a single message, rejects any messages that arrive while the receiver thread is not expecting a message, and provides a synchronous send
operation (sender thread will not be resumed until the receiver thread begins to wait again for a message on the message box), may be implemented like shown below:
-- A continuation which is stored in the message box when no thread is waiting
-- for a message: any message sent via this message box will be rejected
-- (discarded).
ignore = \_ -> False
-- Message box constructor: initializes the JSRef object with
-- ignore-everything continuation.
mkMsgBox k = newJSRef ignore $ \mb -> k mb
-- Send a message: obtain the continuation stored in the message box,
-- construct a thunk (res) to pass the message to the continuation,
-- evaluate res, and finally, resume our own continuation (k) when
-- the receiver evaluates the message, getting the evaluation result.
-- Thus, synchronicity of send is achieved.
send mb msg k = readJSRef mb $ \cont ->
let res = cont msg
in res `seq` (k res)
-- Receive a message: store our continuation (k) in the message box,
-- once called, restore what was in the message box before (thus ignoring
-- any messages that may arrive before we wait for a message again),
-- evaluate our continuation with the message received.
recv mb k = readJSRef mb $ \prev ->
writeJSRef mb (writeJSRef mb prev $ \_ -> k ) $ \_ -> True
An example of two threads using a message box this way: the sender thread is associated with an input (select) element whose updated value may be obtained by handling an "onchange" event; the receiver thread is associated with some display element whose contents may be updated.
-- Sender thread:
-- mb: message box to use
-- par: abstract select element whose value is to be sent
acts mb par = (waitFor par "change" :: CPS Bool TEvent) $ \e ->
(unsafeToSelf par :: CPS Bool THTMLSelectElement) $ \sel ->
get'value sel $ \v ->
send mb v $ \_ -> acts mb par
-- Receiver thread:
-- mb: message box to use
-- par: abstract display element whose visible contents may be updated
-- updateD: a function to update the display element
actu mb par = recv mb $ \s ->
updateD par s $ \_ ->
actu mb par
Note: Just for the sake of giving proper credit: one might find this method of inter-thread communication very similar to one described in Gadgets: Lazy Functional Components for Graphical User Interfaces (1995) by Rob Noble, Colin Runciman. In fact, this paper was studied along with the Fudgets Thesis, and gave some inspiration to this developer.