![]() |
|
Python Project: Binary Adding Machine
Hey what's up guys. About a month and a half ago I decided I wanted to seriously try learning programming (took few courses in uni but mostly bombed them playing poker all day). I did about 20 project euler problems and realized that I was just building algorithms. And I wasn't learning about classes, which I figured are important, so I decided I needed to actually start some kind of project.
I decided on building a program that would model a physical binary adding machine. I got the idea from reading a book called Code by Charles Petzold. This book basically teaches you how computers work starting from morse code and flashlights, to binary and relays, all the way up to RAM, CPU, etc. It's turned out to be my favorite thing I've read in a long time, and I highly recommend it. So anyway, about halfway through the book he explains how to make a binary adding machine. Basically you make relays out of wires and switches, and then combine those relays into logic gates, and then eventually combine those logic gates and get a binary adding machine. And while reading this, I really wanted to try to build one of my own. But a machine that can add two 8 bit numbers require a lot of relays, and I didn't want to have to build them all. So instead I've decided to recreate the binary adding machine as a Python program. So far I've written up the code for a simple circuit with a switch (a flashlight). Here's a visual model i found off google: http://www.rfcafe.com/references/ele...-schematic.gif And here's the module: Code:
#parts: wire, switch, and batteryCode:
Once I've got that i'll move on to building the logic gates. I'll try to explain what's going on for those that are interested. If you have any suggestions I'd love to hear them. If you just want to chat about programming send me a PM. I don't really know where to find people who can help me so I'm basically learning everything on my own through the internet. |
Re: Python Project: Binary Adding Machine
Here's a suggestion:
Keep going and keep posting ITT. This is a neat project :) |
Re: Python Project: Binary Adding Machine
I think this is really awesome project. I recently worked through something like this. Maybe you can watch this video so you can see how to generalize the procedures a little bit:
http://www.youtube.com/watch?v=9jbQrNGQVKc Unfortunately, you'll have to translate all of the above to python, but I think you'll get the general idea down. Basically, they build a wire, then the various gates, and store the state of the gates. They create a the whole program using a queue: Python has a Queue module, http://docs.python.org/library/queue.html, though I don't know anything about it. |
Re: Python Project: Binary Adding Machine
this is pretty cool and I'd really like to see the project grow. But I don't understand this
Code:
def check_in(self): |
Re: Python Project: Binary Adding Machine
Quote:
One thing I'm not sure about is why the function doesn't exit at the first iteration with a return statement. Instead it appears to hold the return statement from completing until its "outer" recursion iterations complete. At least I think that's what's happening when i stick a print statement before the return statement. I get more than one print out. |
Re: Python Project: Binary Adding Machine
Hey, I'm really glad that you guys think the project is interesting. So I finished the relay program which required a lot of interesting adjustments to accommodate its new properties since the flashlight.
For people who don't know how a relay works, here's a picture of one: http://1.bp.blogspot.com/-R-ql_9HCUJ...1600/relay.gif Basically a wire goes into an electromagnet (an electromagnet turns into a magnet when supplied electricity) which pulls a switch. And you can set up the switch so that when it gets pulled it completes a circuit (or break an already complete circuit). This is useful because you can pull switches remotely now, instead of having to open and close switches by hand. Then if you wire multiple relays in different ways, you can get them to open and close switches under various conditions, which is a rough explanation of how you make logic gates. Anyway here's the code. A lot of things are changed since the flashlight program. Electromagnet class and Relay class are at the bottom. Code:
#parts: wire, switch, battery plus, battery minus, lightbulb, electromagnet, relayCode:
#test relaySo one weird thing you might see in here is that I added a connect_back function. Where after I connect to a part, the connected_to part connects back. And then in the Relay class, I overwrote the connect_back function so that it changes the connected_to. So if a part connects to a relay, it would tell relay to create a connect_back attribute linking back, but then the relay's overridden connect_back function would change the part's connected to attribute from "relay" to "relay.electromagnet". Maybe this is a convoluted way of doing it but I had a hard time thinking of another way. So next I'm going to work on the logic gates. From what I've read I'm only going to need three gates and an inverter. I'll try to explain what those are and how I went about making them next time. There were a ton of things I wanted to write about but it was just getting too long and complicated, so if you had any questions feel free to let me know. |
Re: Python Project: Binary Adding Machine
What is the "black box problem?" I'm not sure what you think "black box" means, but there's some evidence you may be confused here, but I should hear it from you before I carry on.
I also think that it is better if you have the wire have a single state, thus you won't have to write all of this, and similar: Code:
class Wire (Parts):I'm not entirely sure why you are inheriting the features of the wire to the other objects. This is akin to having a bicycle class inheriting from a car class because you need tires. |
Re: Python Project: Binary Adding Machine
I just wanted to thank OP for bringing Petzold's book Code to my attention. This is one of the most entertaining and insightful technical books I've read and makes me even more resentful of the awful CS classes I waded through that touched on a lot of the same topics in a far more confusing manner.
|
Re: Python Project: Binary Adding Machine
Quote:
And by easy to use and understand, I mean I want the user to be able to write x.connect(y) for any part (wire, lightbulb, etc), even parts that are constructed from parts (relays, logic gates). This kind of got complicated though because with the logic gates I realized that some of the parts are requiring multiple inputs. Maybe another problem is that I want the program to model the properties of an electrical device as closely as possible. So for the relay I could have programmed it to just take an input of 1 or 0 and pump out an according 1 or 0. But I wanted the operation of the relay to actually reflect the workings of its inner parts. So a circuit check would follow a current from outside the relay, and then go into the relay itself to power the electromagnet inside. So the blackbox problem is essentially getting that to happen without having to write "wire.connect(relay.electromagnet)" because the "relay.electromagnet" is referencing the inside of the relay. Which I don't want because I want people to be able to use the Relay class without having to know its construction. The reason I make classes inherit Wire is I also don't want to have to write: x.connect(wire1) wire1.connect(y) y.connect(wire2) wire2.connect(z) If I don't have the parts inherit class Wire, then I'll have to insert a wire in between every part. Having all the parts inhertit the class Wire allows me to write the above previous as: x.connect(y) y.connect(z) which I think is still quite intuitive. weevil, I'm glad you're enjoying the book! everyone, I'm still working on the project, and almost finished with the logic gates. I had to make a lot of adjustments along the way. But I think the logic gates should be done pretty soon, and then it'd just one more small step to the finished program. I hope. |
Re: Python Project: Binary Adding Machine
Why don't you just create a list like [wire, gate, wire, gate, wire, gate]?
|
Re: Python Project: Binary Adding Machine
Quote:
device = Device() device.construct([switch,relay,lightbulb]) #random example And then have the finished product pop out. The only thing is that now I'm working on the logic gates and they have multiple inputs. And I can't think of how to put all the parts in a list and feed it into just one function in an intuitive way. But I still really like the idea and I'm still kind of using it. So, the way I wrote things before you'd have to write x.connect(y). But your post gave me the idea to do it this way: connect(x,y) This way x and y can refer to each other in a much cleaner way. It collapses connect() and connect_back() functions I was using before into one function. It's so simple, but it didn't occur to me at first that I could use a global function. |
Re: Python Project: Binary Adding Machine
Excellent. I asked you why you didn't use a list so you can see where you current techniques are heading, and your current thought process shows you understand. I just wanted to ask you in the most simplistic way possible. Of course, the list isn't really the correct answer, IMO, but it's in the correct direction, and perhaps the final answer will be a list, but probably not in a way you are familiar with, but I'll let you determine the best way.
You are basically creating a program on top of a program, and your program, you are dealing with 4 basic primitives: wire, and-gate, or-gate, inverter, and only one of these primitives have a state you really need to keep track of: wire. If you make a function like so: Code:
Python also keeps state easily: Code:
def wireState(wire):Code:
>>> wire1 |
Re: Python Project: Binary Adding Machine
This is cool, I think I'll get me that book too (I want to puzzle with it myself a little).
I feel like doing something similar in Java. If it's appropriate to do so, I could discuss about my way to build the actual circuit (I have something in mind that makes use of a list). Keep up the good work, it's inspiring. |
Re: Python Project: Binary Adding Machine
Whew, so I finally finished the logic gates. I really didn't expect it to get as complicated as it was, and I feel like I've just been running my brain to exhaustion for the last couple days. Debugging was a nightmare and now I can really see the value of good planning and good development practices, It was so satisfying though to see the last logic gate pump out the correct outputs. I really feel like this is the home stretch.
Ok for people who don't know how the logic gates work. Basically you have two binary inputs and one binary output. So for our machine, you have two switches as inputs. They are binary because they're either switched on or off. The output is a lightbulb, which is also either on or off. Depending on what kind of logic gate it is, your inputs will have different outputs. For example AND gates only turn the light on if both switches are on. OR gates can turn the light on if either one or both switches are on. NAND is short for "Not AND" and the light is on unless both switches are on. And NOR is short for "Not OR" and light is on only when both switches are off. Here's a few pics that show how this would be put together. http://i.imgur.com/naTKn.jpghttp://i.imgur.com/A1KyX.jpg and here are some logic tables: http://www.johnloomis.org/ece314/notes/carch/img243.gif I also needed to build an inverter (can also be called a NOT gate). When a current goes into an inverter, the inverter turns it off. When no current goes into the inverter, the inverter produces a current. This was really easy to make though, because it's the same as a relay with the switch turned to "closed" as default and then have the electromagnet "open" the switch when powered. So here's the code: Code:
# parts: wire, switch, battery plus side (voltage), battery minus side (ground), lightbulbCode:
# logic gate testerBut then you have multiple circuits that are connected by relays, and whether certain circuits are going to be complete will depend on whether the circuit connected to it by the relay is complete. Now this made it so that I also needed to know what order to check the circuits in also. Add to that, wires that can be split and merged. This got really complicated for me really fast. With the split wires you have to check both sides of the split before you know if either side has a charge. Similar problem (but different) with merged wires. Also since I was using recursive loops to check through the connected parts, now I had a problem where everything wasn't called input and output anymore. Now I had input1, input2 and output1, output2 and I couldn't just run the same function through them. Anyway, I'm pretty happy with some of the solutions I made, although others less so. If you have any thoughts I'd love to hear them. I think the next post will be the final part of this project where I'll explain how to put the logic gates together to do binary addition. Stay tuned! :) |
Re: Python Project: Binary Adding Machine
I've got a question about how 'simultaneous events' are handled:
Suppose Wire X is split into A and B, so they carry both the same signal. And suppose the two logic gates are EX-NOR. How is a change in X handled by the logic gates? I thought you could do it 1 by 1 until some sort of steady-state was reached but in cases like this the result might be different. http://www.radio-electronics.com/inf..._flip_flop.gif |
Re: Python Project: Binary Adding Machine
I'm not really an expert on circuits, so I'm not really sure. Did you mean to say EX-NOR, because the gates in the picture are NAND gates, but I think you're assuming that they are EX_NOR. In which case I think the C and D outputs would follow an oscillating pattern, and then I guess when you turn on X, C and D would stabilize at whatever value they were at at the time. If I were programming it I guess I'd have it return a random value, 1 or 0.
That's my guess just looking at it, but I'm not really one to ask. And if you have anything you want to post feel free! |
Re: Python Project: Binary Adding Machine
Thanks, the gates were indeed EX-NOR (I couldn't find a correct picture).
I will try to build an actual circuit by using 2 lists: 1) objects (logic gates, lights, buttons, ...) 2) objects (wires) Every wire has an input/output which needs to be attached to an object from the first list. All objects from the first list need wires to be attached to their inputs/outputs. (output to input and input to output) After this proces I turn the objects from the first list on (from top to bottom), they check input and adjust output. When an 'action' object from the first list is used (switch, clock, ...): I would adjust the state of the wire attached to the output and iterate through the first list adjusting output-wires until a steady-state was reached. I think I might have problems with these 'simultaneous events'. But even besides that it's maybe not a correct way to build this (not a good representation of reality, ...). |
Re: Python Project: Binary Adding Machine
I decided to try this in the Python way, but I'm not going to go past where OP is at, so all I have is a framework of primitives here, thus my paltry excuse is that it isn't done. Regardless, Feel free to poke holes in this:
(fwiw, I really hate the repetition of the gates, but I can't seem to ponder a better solution today.) Code:
def objectState(x): |
Re: Python Project: Binary Adding Machine
Just turbobrowsing (and I have picked up Code for reading on the train, read upto the relay chapter during the last couple of rides...seems like I'll really like the book). I guess I'd model a circuit as graphs with the nodes being gates and links being wires or smth like that. Might try hacking something up later :)
Conceptionally this seems extremly similar to the neural networks I coded during university. Each neuron having inputs/outputs stuff "propergating" through the net etc etc. so maybe if you're interested neural networks might be an interesting follow up project :) |
Re: Python Project: Binary Adding Machine
Where is OP? I'm still waiting for the adders and stuff. I decided to work on this a little bit this morning and created the half adder, full adder and ripple adder. The ripple adder allows you the add n-bit characters. Right now, the ripple adder just takes strings because in Python land, 000100001 and [0001110001] are illegal, and if you do 0o0000100010 it will simply spit out a number, which isn't cool. Well, actually this feature makes debugging really easy.
|
Re: Python Project: Binary Adding Machine
Hey I'm still here! :) I've actually finished everything up to the full adder and hoping to get around to posting them later today.
Quote:
Quote:
|
Re: Python Project: Binary Adding Machine
Well, once you get yours posted, I'll post mine. Yeah, I can add in some probes to the program to show the wire- and object-states as they progress, but not today. Sort of burned out with the project I'm currently working on.
As for using lists: they'll be available to use for custom circuits and stuff like that but they aren't used in the primitives. They would be abstracted into a function, though of course, someone can use lists directly. I'll try to match the functionality of whatever you post after I see it and play around with it. My program, at this point, only has the various gates, three adders, and a few helper functions. Still have to make the lightbulb, wires, and the connection function. |
Re: Python Project: Binary Adding Machine
Ok so here are the half adder and the full adder, and one more logic gate. But before that I'll explain what I'm trying to do with them.
If you don't know how binary numbers work, basically, in binary there's only 0's and 1's. There's no 2 - 9. Normally after 9, you've run out of unique numbers so you go to 10, essentially adding another digit and starting over with 0-9 except with a 1 in front (ie ten through nineteen). In binary you go 0, 1, and then you've run out of unique numbers so you add a new digit and start over. So you go to 10 which represents 2 in our normal decimal system. And from there you can count, 11 (3), 100 (4), 101 (5), 110 (6). The advantage of using binary numbers is that you can use something like a switch or a light and when it's off or on, you can have that represent 0 or 1. And that's exactly what we're doing in this program. With the logic gates, we're taking in two inputs that we control with two switches, (switch on = 1, switch off = 0) and then returning a single output (light on = 1, light off = 0), who's result will depend on how the logic gates are wired. What we want is to wire them so that the inputs and resulting output will match what we would expect from adding two binary numbers. For example, here's the simplest case adding two one digit numbers. 0+0=0 - switch1 off and switch2 off results in lightbulb off 1+0=1 - switch1 on and switch2 off results in lightbulb on 0+1=1 - switch1 off and switch2 on results in lightbulb on 1+1=10 - ? The first three cases are straightforward, but what about 1+1. Well, each logic gate only has one output, so we want two logic gates, one for each digit of the result. So we have: 0+0=00 1+0=01 0+1=01 1+1=10 We want one gate which will output 0 (lightbulb off) in every case except when we have two inputs of 1 (both switches on). That would be the first digit. And then for the second digit we want the output 0 when both inputs are 0 or 1, and output 1 in the other cases. The first digit can be represented by the AND gate. The second digit is a little more complicated, it's represented by the XOR gate. I didn't have the XOR gate last time, but I've written the code and put it at the bottom of my module this time. Here's what the XOR gate looks like: http://i.imgur.com/ILJvs.gif So then the "half adder" is just two switches wired to an AND gate and XOR gate: http://i.imgur.com/UC6nL.gif But it's called a half adder because it doesn't account for "carrying the one". Let's imagine we're adding two, two digit binary numbers. 11 +11 On the right side we just add two 1's and get 10. So we would write down the 0, but then "carry the 1". Now on the left side we're adding 1+1+1, where the last 1 is the carry-in. The full adder then will be able to account for the carry in. This is wired as follows: http://i.imgur.com/KbRrp.gif So here's the module so far: Code:
# parts: wire, switch, battery plus side (voltage), battery minus side (ground),Code:
# half adder testerCode:
# full adder testerhttp://i.imgur.com/g2j6w.gif All the adding machine really does is connect the switches (at the P's and Q's in the picture) and lightbulbs (at the S's in the picture). I was hoping to be finished by this post, but I've decided to keep going and create a graphic interface for this program. It's my first time working with a graphics module and I'm pretty happy with the way it's turning out so far. I like the fact that using a GUI retains the feeling of using a machine more as opposed to using a program. I have a lot of it done already so it should be done before the weekend. |
Re: Python Project: Binary Adding Machine
When it the light supposed to turn on? Or can you give me an explanation of what is happening here?
Code:
>>> Code:
first switch: enter 1 to switch on, 0 to switch off |
Re: Python Project: Binary Adding Machine
Code:
def reverse(x):I think it's interesting that WeAreSamurai and I have very different approaches to the problem set. I don't know which is better or which is worse. As I said, I already did something like this, and that was from a book that is hard-core functional programming. Most of that translates okay to Python, but there's some things to work around. I know, the start() function could use some improvement, but I think that you can see at least how I plan to tie things together. The Ripple Adder works just as expected. I used this simulation to test against. The ripple adder in the simulation does only 8-bit. If you do test mine against his, remember that his reads from right to left and mine reads from left to right. My Ripple Adder is supposed to work with n-bits, so if you really feel inspired to run 128 bits, have at it, but I can't guarantee the results. To use the Ripple Adder, comment out the start() at the bottom, run the program and go to your command prompt: Code:
So, aside from the ripple adder, I think I haven't went past WeAreSamurai. |
| All times are GMT -4. The time now is 12:21 PM. |
|
Powered by vBulletin®
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.
Copyright © 2008-2020, Two Plus Two Interactive