# Mechanical Computer

Mechanical computer (simple ones also being called *mechanical [calculators](calculator.md)*) is a [computer](computer.md) that uses mechanical components (e.g. levers, marbles, gears, strings, even fluids ...) to perform computation (both [digital](digital.md) and [analog](analog.md)). Not all non-[electronic](electronic.md) computers are mechanical, there are still other types too -- e.g. computers working with [light](light.md), biological, [quantum](quantum.md), [pen and paper](pen_and_paper.md) computers etc. Sometimes it's unclear what counts as a mechanical computer vs a mere calculator, an automaton or mere instrument -- here we will consider the term in a very wide sense. Mechanical computers used to be used in the [past](history.md), mainly before the development of [vacuum tubes](vacuum_tube.md) and [transistors](transistor.md) that opened the door for much more powerful computers. However some still exist today, though nowadays they are usually intended to be educational toys, they are of interest to many (including [us](lrs.md)) as they offer simplicity (independence of [electricity](electricity.md) and highly complex components such as transistors and microchips) and therefore [freedom](freedom.md). They may also offer help after the [collapse](collapse.md). While nowadays it is possible to build a simple electronic computer at home, it's only thanks to being able to buy highly complex parts at the store, i.e. still being dependent on [corporations](corporation.md); in a desert one can much more easily build a mechanical computer than electronic one. Mechanical computers are very cool.

{ Britannica 11th edition has a truly amazing article on mechanical computers under the term *Calculating Machines*: https://en.wikisource.org/wiki/1911_Encyclop%C3%A6dia_Britannica/Calculating_Machines. Also this leads to many resources: https://www.johnwolff.id.au/calculators/Resources.htm. ~drummyfish }

If mechanical computer also utilizes [electronic](electronics.md) parts, it is called an **electro-mechanical** computer; here we'll however be mainly discussing purely mechanical computers.

**Disadvantages** of digital mechanical computers against electronic ones are great, they basically lose at everything except simplicity of implementation (in the desert). Mechanical computer is MUCH slower (speed will be measured in Hz), has MUCH less memory (mostly just a couple of [bits](bit.md) or [bytes](byte.md)), will be difficult to program ([machine code](machine_code.md) only), is MUCH bigger, limited by mechanical friction (so it will also be noisy), suffers from mechanical wear etc. Analog mechanical computers are maybe a bit better in comparison, but still lose to electronics big time. But remember, [less is more](less_is_more.md).

Some **notable mechanical computers** include e.g. the 1882 [Difference Engine](difference_engine.md) by Charles Babbage (aka the first [programmer](programmer.md)), Antikythera mechanism (ancient Greek astronomical computer), the famous [Curta](curta.md) calculators (quality, powerful pocket-sized mid-20th century calculators) { These are really cool, check them out. ~drummyfish }, [Enigma](enigma.md) ciphering device (used in WWII), [abacus](abacus.md), [slide rule](slide_rule.md), Odhner Arithmometer (extremely popular Russian table calculator), [Digi-Comp](digi_comp.md) I (educational programmable 3 bit toy computer) or [Turing Tumble](turing_tumble.md) { Very KISS and elegant, also check out. ~drummyfish } (another educational computer, using marbles).

Let's also take a look at how we can classify mechanical computers. Firstly they can be:

- **special purpose**: Made to solve only limited set of problems, example being a mechanical calculator that can only perform a few operations like addition and subtraction. A special purpose computer may be easier to make as it doesn't have to bother with the flexibility needed for solving general problems.
- **general purpose**: Full programmable [Turing complete](turing_complete.md) computer capable of solving very wide range of tasks efficiently. This is of course harder to make, so general purpose mechanical computers are rarer.

Next we may divide mechanical computers to:

- **[analog](analog.md)**: Working with analog data, i.e. continuous, infinitely precise values, typical examples are various integration machines. The analog approach is probably more natural and efficient in the mechanic world, so we encounter many of analog computers here (compared to the electronic world).
- **[digital](digital.md)**: Working with discrete values, i.e. [whole numbers](integer.md), [bits](bit.md) etc.
- **analog-digital**: Combination of both digital and analog, again this is more common in mechanic world than in electronic world.

And to:

- **autonomous**: Computers that only require to be started and then work completely on their own, without human intervention.
- **semi-autonomous**: Computers largely working on their own but still requiring some human assistance during computation, for example turning some handle to keep the parts moving.
- **computation helpers**: Tools that only aid the man who is doing most of the computation -- typical examples are [abacus](abacus.md), [slide rule](slide_rule.md) or [integraph](integraph.md).

## Basics

**Analog** computers are usually special purpose. { At least I haven't ever heard about any general purpose analog computer, not even sure if that could work. ~drummyfish } Very often they just solve some specific equation needed e.g. for computing ballistic curves, they may perform [Fourier transform](fourier_transform.md), compute areas of arbitrary shapes that can be traced by a pencil (see [planimeter](pleanimeter.md)) etc. Especially useful are computers performing [integration](integration.md) and solving [differential equations](differential_equation.md) as computing many practically encountered equations is often very hard or impossible -- mechanical machines can integrate quite well, e.g. using the famous ball and disk integrator.

As mere [programmers](programming.md) let us focus more on **digital** computers now.

When building a digital computer from scratch we usually start by designing basic [logic gates](logic_gate.md) such as AND, NOT and OR -- here we implement the gates using mechanical principles rather than transistors or relays. For simple special-purpose calculators combining these logic gates together may be enough (also note we don't HAVE TO use logic gates, some mechanisms can directly perform arithmetic etc.), however for a highly programmable general purpose computer **logic gates alone practically won't suffice** -- in theory when we have finite memory ([in real world](irl.md) always), we can always just use only logic gates to perform any computation, but as the memory grows, the number of logic gates we would need would grow exponentially, so we don't do this. Instead we will need to additionally implement some **sequential processing**, i.e. something like a [CPU](cpu.md) that performs steps according to program instructions.

Now we have to choose our model of computation and general architecture, we have possibly a number of options. Mainly we may be deciding between having a separate storage for data and program (Harvard architecture) or having the program and data in the same memory (intending for the computer to "reshape" this initial program data into the program's output). Here there are paths to explore, the most natural one is probably trying to imitate a **[Turing machine](turing_machine.md)** (many physical finite-tape Turing machines exist, look them up), probably the simplest "intuitive" computer, but we can even speculate about e.g. some kind of rewriting system imitating formal [grammars](grammar.md), [cellular automata](cellular_automaton.md) etc -- someone actually built a simple and elegant [rule 110](rule110.md) marble computer (look up on YT), which is Turing complete but not very practical (see [Turing tarpit](turing_tarpit.md)). So Turing machine seems to be the closest to our current idea of a computer (try to program something useful in rule 110...), it's likely the most natural way, so that might be the best first choice we try.

Turing machine has a separate memory for program and data. To build it we need two main parts: memory tape (an array of [bits](bit.md)) and control unit (table of states and their transitions). We can potentially design these parts separately and let them communicate via some simple interface, which simplifies things. The specific details of the construction will now depend on what components we use (gears, marbles, dominoes, levers, ...)...

## Concepts

Here we will overview some common concepts and methods used in mechanical computers. Remember the concepts may, and often are, **combined**. Also note that making a mechanical computer will be a lot about mechanical engineering, so great many concepts from it will appear -- we can't recount all of them here, we'll just focus on the most important concepts connected to the computing part.

### Gears/Wheels

Gears (wheels with teeth) are a super simple mechanism popular in mechanical computers. Note that **gears may be both digital and analog** -- whether they're one or the other depends on our interpretation (if we assign importance to every arbitrary orientation or just a finite number of orientations that click the tooth into some box).

The **advantages** of gears are for example instant transfer of motion -- even if we have many wheels in sequence, rotating the first one instantly (practically) rotates the last one as well. Among **disadvantages** on the other hand may be the burden of friction (having too many gears in a row will require a lot of power for rotation and strong fixation of the gears) and also manufacturing a non-small number of good, quality gears may be more difficult than alternatives (marbles, ...).

Besides others gears/wheels can be used to:

- **Transmit power**, i.e. delivering motion to components that need motion to work (even in computers that don't use gears themselves as computing components).
- **Do [arithmetic](arithmetic.md)**: for example a differential can be used to instantly add two numbers (or actually to compute any linear combination, e.g. average, ... using the [slide rule](slide_rule.md) concept we can probably even implement multiplication, division etc.). A simple stepped-cylinder (kind of a "gear") alongside with normal gears can also be used to implement addition, subtraction and even multiplication (as explained e.g. in 1911 Encyclopedia Britannica; this principle was used e.g. by the old Russian calculators).
- **Represent a general digital value** by how they are currently rotated, i.e. a gear with *N* teeth -- each one labeled with a value -- can hold one of *N* values depending on which of the values is currently under some pointer -- this is often used in mechanical calculators e.g. to display computed values. This has the advantage of being able to represent a digital number with one relatively simple part (the wheel) without having to encode multiple bits (i.e. many smaller parts). This may also be used to make a **[look up table](lut.md)** -- imagine e.g. a wheel which by rotating looks up some value that may be represented e.g. by displacement (imagine spinning spiral) or holes on the wheel. If the gear represents a natural number, it naturally implements [modulo](mod.md) increment/decrement (highest value will overflow to lowest and vice versa).
- **Represent one [bit](bit.md)** by turning either clockwise or counterclockwise.
- Possibly represent values also in other ways, for example by speed of rotation, rotation vs stillness, position (gear traveling on some toothed slider, ...) etcetc.
- ...

```
       1         1
  __  ,-,  ___  ,-,  _______
 |   { o }     { o }   ,-,  |
 |    '-;,     ,-;'   { o } |
 |    _|||____{ o }____;-;  |
 |             '-;-.  { o } |
 |_____________ { o } _'-'__|   
                 '-'
                  1


       0         1
  __  ,-,  ___  ,-,  _______
 |   { o }     { o },-,     |
 |   ,;-'  ,-,  '-'{ o }    |
 |  _|||__{ o }_____;-;     |
 |         '-'   .-{ o }    |
 |_____________ { o }-'_____|   
                 '-'
                  0
```

*NXOR (equality) gate implemented with gears (counterclockwise/clockwise rotation mean 1/0); the bottom gear rotates counterclockwise only if the both input gears rotate in the same direction.*

### Buttons/Levers/Sliders/Etc.

Buttons, levers, sliders and similar mechanism can be used in ways similar to gears, the difference being their motion is linear, not circular. A button can represent a bit with its up/down position, a lever can similarly represent a bit by being pointed left/right. As seen below, implementation of basic logic gates can be quite simple, which is an advantage. Disadvantages include for example, similarly to gears, vulnerability to friction -- with many logic gates in a row it will be more difficult to "press" the inputs.

```
   ___ 0               ___ 0   ___ 0       ___ 0   ___ 0
  _ | _________       _ | _____ | _       _ | _____ | _
 |  |          |     |  |       |  |     |  |       |  |
 |   '--o---.  |     |  '-------'  |     | -----.----- |
 |________  | _|     |_____ | _____|     |_____ | _____|
           _|_             ---                 ---
               1               0

       1                   1   ___ 0           1   ___ 0
  _---_________       _---_____ | _       _---_____ | _
 |  |     .-|  |     |  |       |  |     |  |       |  |
 |  |  .o'  |  |     |  | __.--''  |     | _|________  |
 |__'-'____ | _|     |__''_ | _____|     |_____ | _____|
           ---             ---                 _|_
               0               0                   1
       NOT                 AND                  OR
```

*Possible implementation of logic gates with buttons.*

### Marbles/Balls/Coins/Etc.

Using moving marbles (and possibly also similar rolling shapes, e.g. cylinders, disks, ...) for computation is **one of the simplest** and most [KISS](kiss.md) methods for mechanical computers and may therefore be considered very worthy of our attention -- the above mentioned marble [rule 110](rule110.md) computer is a possible candidate for **the most KISS Turing complete computer**. But even with a more complicated marble computer it's still much easier to build a "marble maze" than to build a geared machine (even gears themselves aren't that easy to make).

**Basic principle** is that of a marble performing computation by going through a maze -- while a single marble can be used to evaluate some simple [logic circuit](logic_circuit.md), usually (see e.g. [Turing Tumble](turing_tumble.md)) the design uses many marbles and performs sequential computation, i.e. there is typically a **bucket** of marbles placed on a high place from which we release one marble which (normally by relying on [gravity](gravity.md)) goes through the maze and performs one computation cycle (switches state, potentially flips a memory bit etc.) and then, at the bottom (end of its path), presses a switch to release the next marble from the top bucket. So the computation is autonomous, it consumes marbles from the top bucket and fills the bottom bucket (with few marbles available an operator may sometimes need to refill the top bucket from the bottom one). The maze is usually an angled board onto which we just place obstacles; multiple layers of boards with holes/tunnels connecting them may be employed to allow more complexity. { You can build it from lego probably. ~drummyfish }

If it's possible it may be actually simpler to use coins instead of marbles -- as they are flat, building a potentially multi-layered maze (e.g. with shifting elements) can be easier, it may be as simple as cutting the layers out of thick cardboard paper and stacking them one on another.

Also an alternative to having a top bucket full of marbles going to the bottom bucket is just having one marble and transporting it back up after each cycle -- this can be done very simply e.g. by tilting the maze the other way, so the computation is then powered by someone (or something) repeatedly tilting the board one way and back again; this is e.g. how the simple rule 110 computer works -- there the marble also does another work on its way back (it updates the barriers in the maze for itself and its neighbors for the next round of the downwards trip), so the "CPU cycle" has two phases.

NOTE: Balls, or potentially other "falling/moving objects", may be used to perform computation also in other ways than we'll describe further on -- some of the alternative approaches are for example:

- The **[billiard ball computer](billiard_ball_computer.md)** (which also has a great advantage of performing [reversible computation](reversible_computing.md)).
- Another possible idea is that of the falling object ITSELF encoding a value (likely just a bit), for example imagine some kind of arrow shape which itself represents either 1/0 by pointing up/down, changing its orientation as it passes through the gates (we would also have to ensure the orientation can't change spontaneously on its own of course).
- A bit can also be represented by presence/absence of the marble -- this is utilized e.g. by *binary marbles* (https://binarymarbles.weebly.com/how-it-works.html). For example the AND gate is implemented by one input marble falling into a hole, making a "bridge" for the other marble that then overcomes the hole and reaches output. Timing may play an important role as some gates (e.g. XOR) require dropping the input marbles simultaneously.
- ...

These approaches may be tried as well, however further on here we will focus on the traditional "marble maze" approach in which the marbles mostly serve as a kind movement force that flips bits represented by something else (or possibly indicate answer by falling out through a specific hole).

The **disadvantage** here is that the computation is **slow** as to perform one cycle a marble has to travel some path (which may take many seconds, i.e. in the simple form you get a "CPU" with some fractional frequency, e.g. 1/5 Hz). This can potentially be improved a little, e.g. by [pipelining](pipeline.md) (releaseing the next marble as soon as possible, even before the current one finishes the whole path) and [parallelism](parallelism.md) (releasing multiple marbles, each one doing some part of work in parallel with others). **Advantages** on the other hand include mentioned simplicity of construction, visual clarity (we can often make the computer as a flat 2D board that can easily be observed, debugged etc.) and potentially good extensibility -- making the pipeline (maze) longer, e.g. to add more bits or functionality, is always possible without being limited e.g. by friction like with gears (though usually for the cost of speed).

Some things that can be done with marbles include:

- **Flipping/setting bits**: A marble running through some specific part of the maze can flip something over, which we may interpret as flipping a bit. A simple rotating "T" shape can be used to make a one bit [flip-flop](flip-flop.md) (see below).
- **Branching**: If/else/switch branching can be implemented simply as a marble taking one road or another on a crossroad, which can be decided by some moving part connected to some bit elsewhere.
- **Rotating gears**: A marble may rotate a gear by precise number of teeth, this can be used e.g. to implement a shift on memory tape (see pictures below).
- **Weight/count representing a value**: instead of encoding a number with flippable bits we may instead use a small bucket into which marbles fall -- the number of marbles in the bucket then encode the number stored. We may e.g. introduce a limit number (`if x > N`), i.e. weight at which the bucket becomes heavier than a counterweight and opens some new path for the marbles.
- ...

```
     :
 #   o   #     #       #     #       #     #       #
 ##     ##     ##     ##     ##     ##     ##     ##
 ###   ###     ### : ###     ###   ###     ###   ###
 #  \ /  #     #  \o/  #     #  \ /  #     #  \ /  #
 #   O   #     #   O   #     #  oO   #     #   O   #
 #   #\  #     #   #\  #     #  /#   #     #  /#   #
 #   #   #     #   #   #     #   #   #     # : #   #
 #   #   #     #   #   #     #   #   #     # o #   #
   0   1         0   1         0   1         0   1
```

*Marble falling into a [flip-flop](flip_flop.md) will test its value (fall out either from the 0 or 1 hole) and also flip the bit -- next marble will fall out from the other hole. Flip-flops can be used to implement **[memory](memory.md)**.* 

```
\:  marble slide
 \o
  \           hole      sliding plane
=============----===============VVVVVVVVVVV====  <----->
  |    |    |    |    |    |       -''-
  | b0 | b1 | b2 | b3 | b4 |      { () } 
  |    |    |    |    |    |       '--' gear
             bits
```

*Above a gear is used to select which hole an incoming marble will fall into (each hole may contain e.g. a flip-flop bit shown above). This may potentially be used to e.g. implement random access memory.*

```
              O                        O                        O                        O
            | : |                    | : |                    | : |                    | : |
       _____| : |_              _____| : |_           ________| : |            ________| : |
      |  |A | :  /| A = 1      |  |A | :  /| A = 1   |  |A |   ./|    A = 0   |  |A |   ./|    A = 0
      |  |__| : /A|          __|  |__| : /A|         |  |__|  ./A|            |__|__|  ./A|__
      |    /| :  /| B = 1   |    /|   ./|""  B = 0   |    /| :  /|    B = 0      |   ./|    /| B = 1
      |   /B| : /B|         |__ /B| : /B|__          |   /B| : /B|             __|  ./B|   /B|
      |      |\ . |            |   :  |\   |         |      |\.  |            |     :|\   |
      |      |A\ .|            |   :  |A\  |         |___   |A\. |__          |___  :|A\  |__
       \    |   ./              \  : |    /              \    | :  /              \ :  |    /
        \   |  ./                \ : |   /                \   | : /                \.  |   /
          1   0                    1   0                    1   0                    1   0
```

*XOR computed by a marble falling through the gate (it will fall out of the 1 hole only if inputs are set to different values), inputs are implemented as shifting two parts of the gate left or right (this can be done by another falling marble) -- the parts marked with the same letter move together.*

Here are some **additional tips** for marbles: if you want to allow a marble to be only able to go one way in the maze, you can use a mini ramp (one way it will climb it and fall over but from the other way it just behaves like a wall). You can also utilize helper marbles that can e.g. temporarily lock a moving part (obstacle) in place when computation is in progress (so that the falling marbles don't move the obstacles by bumping into them), the helper marble simply falls into some small hole where it will block horizontal movement of the part that shouldn't move, and later it can be released from this hole (this is super easy with the "changing tilt" approach mentioned above, the blocking marble simply goes up and down while in one position it's blocking, in the other it's not).

### Fluids

Whether the use of fluids/gases (water, air, steam, maybe even sand, ...) is still considered mechanical computing may be debatable, but let's take a look at it anyway.

- **Power**: flowing fluid (steam, water stream, falling sand, ...) can be the source of movement in the mechanism.
- **[Hydraulics](hydraulic.md) can easily transmit movement**: fluid in a tube under pressure can transfer movement on a long distance and can be curved in any way, this may be much simpler way of transferring movement than e.g. a sequence of many gears.
- **[Logic](logic.md)**: fluids can also implement logic gates, see [fluidics](fluidics.md).
- **Weight/volume can have significance**: similarly to marbles, the amount of water in a bucket may record a value, we may employ weights, overflows etc. to incorporate this into computations.
- **[Electronics](electronics.md) emulation**: it's known many electronic concepts can be imagined with water pipes instead that deal with similar concepts (pressure ~= voltage, flow ~= current, resistor ~= narrower pipe, ...). By this we may possibly emulate very simple electronics without actual electricity.
- ...

### Other

Don't forget there exist many other possible components and concepts a mechanical computer can internally use -- many things we leave out above for the questionability of their practical usability can be used to in fact carry out computation, for example dominoes or slinkies. Furthermore many actually useful things exist, e.g. teethed **cylinders/disks** may be used to record plots of data over time or to store and deliver read/only data (e.g. the program instructions) easily, see music boxes and gramophones; **[punch card](punch_card.md) and paper tapes** have widely been used for storing read-only data too. Sometimes deformed cylinders were used as an analog **2D [look up table](lut.md)** for some mathematical [function](function.md) -- imagine e.g. a device that has input *x* (rotating cylinder along its axis) and *y* (shifting it left/right); the cylinder can then at each surface point record function *f(x,y)* by its width which will in turn displace some stick that will mark the function value on a scale. To transfer movement **strings, chains and belts** may also be used. [Random number generation](rng.md) may be implemented e.g. with [Galton board](galton_board.md). If timing is needed, pendulums can be used just like in clock. Some mechanical computers even use pretty complex parts such as mechanical arms, but these are firstly hard to make and secondly prone to breaking, so try to avoid complexity as much as possible. Some old mechanical calculators worked by requiring the user to plug a stick into some hole (e.g. number he wanted to add) and then manually trace some path -- this can work on the same principle as e.g. the marble computer, but without needing the marbles complexity and size are drastically reduced. Another ideas is a "combing" computer which is driven by its user repeatedly sliding some object through the mechanism (as if combing it) which performs the steps (sequential computation) and changes the state (which is either stored inside the computer or in the combing object).

BONUS THOUGHT: We have gotten so much used to using our current electronic digital computers for everything that sometimes we forget that at simulating actual physical reality they may still fail (or just be very overcomplicated) compared to a mechanical simulation which USES the physical reality itself; for example to make a simulation of a tsunami wave it may be more accurate to build an actual small model of a city and flood it with water than to make a computer simulation. That's why aerodynamic tunnels are still a thing. Ancient NASA flight simulators of space ships did use some electronics, but they did not use computer graphics to render the view from the ship, instead they used a screen projecting view from a tiny camera controlled by the simulator, moving inside a tiny environment, which basically achieved photorealistic graphics. Ideas like these may come in handy when designing mechanical computers as simulating reality is often what we want to do with the computer; for example if we want to model a [sine](sin.md) function, we don't have to go through the pain of implementing binary logic and performing iterative calculation of sine approximation, we may simply use a pendulum whose swinging draws the function simply and precisely.