Have you heard that the whole universe, including you and me, might simply be a simulation? I don't know about you but that doesn't seem so simple to me. Why not? What is simulation after all? Let's talk about an example and unwrap that concept a bit.
I understand circuit simulation, one of the key technologies to help design electronic chips. I understand that very well. I wrote all kinds of circuit simulators in the early days of my graduate study located at the beautiful Hammershlag Hall in Carnegie Mellon University.
The idea is simple: designing and building those chips is like rocket science, in fact, much harder and rather expensive when we try to cram a million or a billion transistor into what we call integrated circuits. Funny we are talking of larger numbers, again. Take a quick guess how many transistors there are in a flash memory stick that has 128 GB (Gigabytes). Think of a very big number. Then, take a look at the first footnote at the end of this page. The answer might surprise you*.
A circuit is a bunch of transistors connected together in order to calculate something (computation) or to remember something (memory).Two quick examples: logic gates compute and flip-flops remember! And, they rarely make mistakes and even more rarely forget!** Electrical engineers like this author here, or Radio Shack enthusiasts, used to go to the electronics lab, or the basement or the garage, build a circuit on a breadboard and test it with multi-meters or oscilloscopes. You can still do that even though Radio Shack is out of business. You can order transistors, resistors, capacitors and wiring from Amazon. But, imagine doing that with thousands of transistors, let alone millions. Well, enter circuit simulation. Some of us electrical and computer engineers go on to study graduate-level courses and learn to model such real circuits using math and computer programming. The resulting software is called a circuit simulator. Check this out: a simulator for a simpler circuit without any transistors, but with one inductor, one capacitor and one resistor. You can play with more circuits listed in the menu.
I know that you are not likely to be interested in getting a PhD degree in such a deeply technical engineering occupation. But, I suspect that you might be interested about simulation in general as an idea. After all, you heard about Artificial Intelligence which is almost like a simulation of a mind trained on all the books, magazines, newspapers and the writings on the internet! But, let's start with the basics. Let us use our computers to simulate a ball moving. Yes, back to physics! Some of my favorite science communicators claim that physics is everything and it can provide a theory of everything. I highly doubt it, but I'll let you come up with your own conclusions. But here, I would like us to get some hands-on experience and a grounded understanding of what the heck simulation is :-). And for that we will use iKojo. If you would like an introduction to what Kojo and iKojo are, start here. Otherwise, let's dive in:
Basics of simulation explained. It all starts with the canvas in iKojo***. We write and draw on it. Oh, I should have said: we ask kindly that our artificial friend, the computer, writes and draws for us, as we instruct it. Of course nothing really moves in a computer. It only seems like it, just like a movie film reel. So, there is no real motion. It is all simulation. But, more on that later. As we were saying, the canvas is like the world where things play out. Our playing field. And, just like the real world, the canvas is infinite****. Actually, I am not so sure about the universe. It does seem to be infinite. But, our canvas is almost infinite, or indefinitely big, so to speak, just like the largest numbers (what? There is no such thing as largest numbers, is there? Future reading and future fun for you...). Yet, given the screen you're looking at, the visible part is rather bounded. It's good to know how to keep our drawings and animations inside the visible part. Kojo gives us this information with a simple programming object called canvasBounds. Remember that this is only the visible part. Now, run it by clicking the link at the beginning of this paragraph (it's text says: Basics of simulation explained) and see what happens. Then, come back to read on.
Earlier (in another page), we asked our turtle to do some drawings on the canvas. The turtle got animated, meaning moved, when we told it to go forward, turn right, etc. And, it left its mark as drawings on the canvas. In this example, we see how we can draw shapes in the canvas, just like a painter, using another cool programming object called Picture. It's getting tiring to keep saying programming. So, from now on, I will just say object, and, if you'd like, you can qualify it with or without programming, as the case may be.
The first line creates a circle which comes with very useful methods like position and setPosition. We give that a name, ball, so we could interact with it later in the loop called animate. That loop is an infinite loop until we stop it, or we pause it when you leave iKojo's webpage to look at news and social media. However, Kojo makes sure it is neither too fast nor too slow, but runs at the just right frame rate, so that animations are smooth as in a movie made out of many frames of individual and static photographs. And, that's the essence of simulation. No wonder it seems as if the whole universe is a simulation for us to not only enjoy as a 3D high-fidelity movie, but also participate in it and co-author the script. Are we?
Okay, let's come back to this simpler script. BTW a script is what shorter programs are called in computer lingo. In our script, we skipped over the second and the third lines. In the second line, we use the trans function to move the circle to the top-left corner of the visible canvas and draw it. Until we draw the circle, it was created only in the memory of the computer. Note that we can modify the shape in memory before we draw it in the canvas.
The third line is just another example where we define and draw another circle. This time around we don't move it with trans so it goes to the origin, (0, 0), the center of the canvas, but we use two functions to change the pen color and fill it. Note the asterisk (*) that combines those two functions and the arrow (->) which applies the result to the new circle. We call these special functions Composable as they can be composed to transform the shape we want to draw.
Do you understand better now how the circle is animated, how its motion is simulated? The setPosition method takes as input the x and y coordinates of a point on the canvas and moves the circle to that point. The position method gives us the point where the center of the circle is located now. So, do you see how we "move" it? And, remember our discussion of the animate function above. It runs the setPosition method at least 30 times. So, in effect, we are redrawing the circle faster than the eye can detect, but every time, we move it a tiny bit. How much? Only one pixel, horizontally. But, we also move it vertically by an amount determined by the ratio of the height over width of the canvas. The result is motion along the diagonal of the canvas. Can you make it move faster or slower? Give it a shot. By the way, it is very easy to modify this script so that the red ball is not hidden behind the blue circle as it moves across it. Any guesses how? Feel free to click here to see the answer. A slightly harder challenge: can you make the ball start at the upper right corner, instead of the upper left, and move diagonally to the lower left corner? The answer is here. But, it's better, I think, if you give it a shot yourself first. You know, move those brainy muscles. BTW. There are also comments at the top of the script. See if you can put them to some good use, too.
I hope you learned something here. More importantly, I really hope you enjoyed it and had some fun. Well, why not? With these simple methods, we'll be able to animate and simulate many more things below. And, did you notice how well our computers listened to us? It did exactly what we told it to do. We humans may not be as obedient as computers, but we can at least try to listen to our friends when they want to tell us their story, can't we?
Simulation of a bouncing ball: Here is another simulation, but this time we also model gravity. No damping or friction, yet. In the next example you will see that they are not too much of a challenge to add, once you understand this little script.
Simulation of gravity with damping and friction: Damping is loss of energy when the ball bounces. Friction is due to air and ground impurities which also slow the ball.
Two body problem This was a big problem for Aristotle and the wise old guys until the new kids on the block, Galileo and Newton, challenged the status quo. Ancients saw the world as two: Heavens (above) and Earth (here, below). As per their observations, they assumed that heavenly bodies like the Sun, the Moon and the stars and the wanderers (original meaning of the word planet is to wander) were fundamentally different in how they moved from those on Earth. Well, until Galileo's wonderful thought experiments and Newton's math unified the seeming dichotomy. Galileo and Newton worked hard and positively obsessed like geniuses (and they were). The culmination of their work is the simple laws of mechanics and gravity. They are indeed very simple to state, and they are almost true (until Einstein improved on them), but, let's see how we can simulate them with a cute little animation. We have two twin stars in an eternal, perpetual motion (guess what, following elliptical orbits). Please see the last footnote for a quick refresher on the laws of gravity and motion *****. You can also look at the simple code, only about 20 lines, and see how all of those laws can be simulated using basic trigonometry and basic programming methods.
The second two body problem -- Just like the previous one. Here we also trace the orbits and find out that they are ellipses. But, we also added a lot of information (called comments in programming lingo) so you can learn how the program works. If you do that, you'll notice that there is a variable that sets the initial speed of the stars. It is set to 1.1. Try changing it to 0.5 or 0.6 and re-run. You're in for a surprise. And what about 0.4? See what a difference the initial state makes?
Three body problem, the infamous problem of mechanics which Newton famously could not solve. But, we realized later that it is actually impossible to solve in the general case. Because, it has mathematical chaos within! Please feel free to reload this link as many times as you'd like. Each time, you'll get a unique solution to the problem. The three stars will do all kinds of crazy things. Their trajectories are impossible to predict. You can also just click the Run button at the top of the canvas where the stars are wandering...
Four color art. This is for my mom, Reyhan, a painter and an amazing artist, to play with. But, she is very generous. She'll let you partake in the fun.
Five color fun. Ditto, for Reyhan and for you to have more fun...
A planet orbiting a star. Play with the ratio of the masses of the two bodies in gravitational pull and see how the orbit changes. Also play with the initial speed of the planet
Two planets orbiting a star, somewhat like Mercury and Venus around the Sun. But, these two have crossing orbits. Do you think they are destined to crash into each other, at some point in the future? Run the simulation a bit and see. And, how about three planets orbiting a star? Try it here. If you compare the two scripts, you'll see that it's fairly easy to add more planets. Care to add a fourth? Or change things a bit? You can change the initial placement and initial velocity of each planet and their star, or change their masses. Have fun and find out how, despite the simple laws of nature that governs such motion, the gravitational dance of these bodies could get so complex. Oh, by the way, you may also want to check out this newer but equivalent script. I updated it to factor out all the trigonometric functions the older one used: sine, cosine and arc-tangent. It is now based on simple arithmetic and geometry of right triangle where we have the square of the long edge equal to the sum of the squares of the two right edges. And, here is the latest and greatest script with four "planets." Do run it and wait for the surprise: just before the orange planet completes its second full turn, the purple and green "planets" almost hit each other and demonstrate the slingshot effect as they get thrown off this "solar system." And with this hindsight, we might want to think of purple and green objects as two comets as opposed to planets that are supposed to have stable orbits around their stars. More importantly, please take a quick look at the program and observe that there is no use of trigonometric functions like arc-tangent or sines or cosines. The function named dv computes the delta velocity -- meaning change in the speed of the first body at the given point -- due to the influence of the second body with the given mass at another point. Newton's gravitational law is simplified to a couple of lines of Kojo code. Isn't this very expressive and impressive? Note that we sum of all dvs across all interacting bodies (two, three, four, ... as many as you'd like) within the animate loop in four additional lines.
Game of Life! Sometimes we save the best for the last. I think that's not always very wise. But, that's another story. I feel like I've saved the best simulation for last, too! Why is this the best? Because, we will simulate life itself! What do we mean by life? You know biological stuff that reproduces and grows and uses energy... But, this is artificial life where no biology, not even any chemistry is involved. Have you heard about cellular automata? They are simple-looking but powerful machines. Game of Life is the most famous one of them all. It's also called a no-player game and was created by John H. Conway, the famed Princeton math wiz. Please click on the previous link or here and watch a wonderful YouTube video about it. You may also enjoy this more geeky intro in YouTube. Or just read on as the rules are very, very simple: we have a level playing field populated with square cells. Each cell can have at most 8 neighbors: one directly above, one directly below, one on each side and one on each corner: top-left, top-right, bottom-right, bottom-left. If a cell has 2 or 3 neighboring cells, it lives on in the next iteration. Otherwise, it dies. But, if a dead cell has exactly 3 neighboring cells, it comes back to life. And, we just repeat. Here is a longer intro with more links and variations. The code is short, about 50 lines to define and run the rules and then some more to show you some of the most famous starting patterns. But, we make use of some more advanced functional programming concepts (like the higher-order function foldLeft). So, at the first glance, it can be a bit hard to make sense of. Just play with it. Pick different patterns and have fun. But, also notice that very small differences make a big splash (try the patterns tee, plus vs fpend). Just like the butterfly and the hurricane. Earlier in the three-body problem we've also stumbled upon this amazingly fun and interesting world of mathematical chaos. Life, we could say, thrives in the region between frozen order and chaos. Like water, the sweet spot between ice and steam. Be a saint like water, Sufis from Asia Minor say.
Now then. Having seen all that, and inquiring into what it all means... what do you think? Do you feel like you understand what simulation is all about? What it means to simulate something? Motion is something so basic to our everyday experience that we take it for granted. Move from A to B. Yet, you probably heard Zeno's paradox that motion is impossible because, to go from A to B one first needs to go to the mid-point between A and B, say C. But, before one can get to C, she needs to go to the mid-point between A and C. And ad infinitum we go! Because, given two distinct points, no matter how close they are, there is another point in the middle. Isn't there? So how come? How do we move at all?
In the simulations we created above, we "moved" a ball from where it was by deleting it first and then redrawing it on another point close to where it was. And we did that faster than the eye could detect. And, we got motion! Or more accurately, we simulated motion. So, coming back to our original question, what is this thing we call Reality? Could it all be a simulation that we are dreaming of? If so, its Creator must be in charge of a pretty amazing piece of software running on a supremely high performance hardware. And talking about software and hardware, I am reminded how sophisticated, nay, miraculous, our minds and bodies are.
Footnotes:
* Remember that Kilo is for 1000 (or 1024 in the binary digital world because it is equal to 2 to the power 10, as opposed to the physical one used in metric units like kilometer and kilogram), Mega is for one million and Gig (not a Jazz gig) is for a billion. A byte is 8 bits. 8 * 128 is 1024, or K, again, meaning more than another 1000. So, that's how we got from 128 GB on your flash drive to more than a trillion, or just Tera (and not Terra!) transistors in it. And, that's simply because we need at least one transistor to implement one bit in silicon. And what's a trillion? Only a lot more than all the stars in our Milky Way galaxy! That is, of course, if you believe the latest estimates by astrophysicists. And why not? You don't believe that the Earth is flat just because it's flat enough, do you? Lol.
** Do you ever feel burdened by your mind trying to remember or think hard to, you know, figure things out, to accomplish more in life, get more things done (multi-tasking anyone?), to get your friends to go along with your preferences, to transcend it all and finally, eventually, be really happy? And then, you realize that you don't even remember what you had for breakfast or dinner yesterday? That's where computers and AI come to our rescue! I remember the days before Google search happened: we used to go to the library to look for papers, buy maps on big sheets of folded paper to find directions, write paper mails and post them with, you know, paper postage stamps! Now that we can easily find what we search on our smart phones, the next step, I imagine, is an artificial mind to think for us all: what should I do today? What problems do I solve today? What do I shop, cook, eat, dress... Imagine the artificial mind providing the best answers so that you and I can finally relax and enjoy this wonderful life in this wonderful universe. That dream might be closer to reality than you imagine. But, why not relax now and enjoy what your mind does. The trick is to not take it so seriously all the time. The voice in the head, that is. It's just a marvelously powerful tool for us all to put to use. That's our true calling.
*** Kojo has an even better canvas than the simpler one in iKojo. You may want to download it to your computer and explore further when you get around to it. Here is the download page.
**** Infinite is too big. So, I am not really sure about the physical universe being infinitely big. But, our canvas is truly big. To see for yourself how far you can send our turtle or any Picture object, just go to ikojo.in and copy and paste the following snippet:
val ball = Picture.circle(10) // Our ball has a radius of 10 pixels
ball.draw() // Draw the ball on the canvas
ball.setPosition(Double.MaxValue, Double.MinValue) // Move it to given x,y coordinates. Center of the canvas is x=0, y=0. x and y increase as we go right and up.
println(ball.position.x, ball.position.y) // write ball's coordinates on a new line
And if you want to bring the ball back into the visible part of the canvas, add the following to the end of your new code:
invisible // to hide our green turtle
ball.setPosition(0, 0) // bring it back to the center of the canvas
But, if you want a more fun way to bring it back from "infinity," just click: come back from the far side!
Is there anything you don't understand in the six lines of code above? I added long comments after each line. But, line #3 may still be a puzzle for most of you. What the heck is Double? Feel free to explore the wikipedia article here. But, in a nutshell, it gives us a way to play with decimal numbers, like 3.1415. Why is it called a Double? It actually stands for DoubleFloat, meaning, a floating point, meaning a decimal, number using double the memory of a less precise float. And you can compare the two (and more!) by running the following line of code. In Kojo/Scala, we got all kinds of numbers (-:
println(Double.MaxValue, Float.MaxValue, Long.MaxValue, Int.MaxValue, Byte.MaxValue)
***** The simpler laws of mechanics are indeed simple, but they are also fairly subtle:
a) For every action, there is an equal and reverse reaction. If you push your friend, she will push you back :-)
b) Rest and uniform motion are one: if there is no force acting on an object, then it will stay as is, or will continue to move with the same speed in the same direction.
Now, the last two, we are a bit trickier:
c) Any given object with a mass, denoted as m, will accelerate or decelerate, denoted with a, in inverse proportion to m and in direct proportion to the net force acting on it (force being a constant push in a constant direction), F. It's much simpler to remember all that as:
F = m * a
d) Two objects with masses m1 and m2 attract each other with a force, F. And that force is inversely proportional to the square of the distance between them. Meaning that the closer they are much greater the pull. The force is also directly proportional to each mass, in fact, the multiplication of them. If we could place a ball smack between the Earth and the Moon, it would be pulled more towards the Earth and would eventually fall on it. So, we say:
F = m1 * m2 / (r * r)
There is a constant, too, but, that's only to match the units of mass, kg or lbs, and units of distance, meters or inches, feet, etc. Nothing essential.
****** How many stars are there, here? Almost too many. So let us just say "no more footnotes."😅