Hacker News new | ask | show | jobs
by satu0king 2936 days ago
Please look at the examples to see what the simulator engine is capable off. As for designing the simulator engine to solve these kind of cyclic circuits, and advice on how to do it?
2 comments

As for designing the simulator engine to solve these kind of cyclic circuits, and advice on how to do it?

The general idea is to iterate while changes are still propagating through the circuit; here's some pseudocode:

    changedNets.add(initial stimulus)
    for each net in changedNets
        changedNets.remove(net)
        for each node in nodes(net)
            for each output in outputs(node)
                evaluate output
                if output changed
                    changedNets.add(output)
        if state cycle detected
            break
The above algorithm reasonably accurately models what happens in a real digital circuit: changes propagate through each node until the whole circuit reaches a steady state. You can even add visualisations to show each step of the propagation as it takes place, and more elaborate versions can take into account different propagation delays (i.e. the output of each node can change at a different time relative to its input, so you process them in a queue ordered by that.)

To use my example circuit, with both inputs low initially: when one of the inputs of one NOR is set high, in the next step the output goes low, then the other NOR's output goes high, and the input of the first NOR goes high. This doesn't change anything else, so the circuit reaches equilibrium. When you set that input back down, the NOR already has the other input high, so it doesn't change state and equilibrium is already reached.

Cycle detection can be as simple as a hardcoded iteration count, or something a bit more accurate and useful:

https://en.wikipedia.org/wiki/Cycle_detection

Interesting fact: A true cycle-detection algorithm will theoretically let you simulate a whole CPU running any Turing-complete program, if you clock it with an "inherently unstable" ring oscillator...

Thank you! Not sure if this is within my ability to implement but will give a definite try
You probably have to model the fact that gates need time to change their output. You can use a data-structure like this ([1]) to keep an ordered list of events (ordered by the virtual time), and you just work your way down the list, generating new events, until the network is stable.

[1] https://en.wikipedia.org/wiki/Priority_queue