Dmux4Way is producing error in line 7: error from Hardware Simulator? - nand2tetris

Did I miss anything or is Hardware Simulator wrong?
The simulator is producing error!
Please can you run this and see the error.
Please can you run this and see the error.
Please can you run this and see the error.
// This file is part of www.nand2tetris.org
// and the book "The Elements of Computing Systems"
// by Nisan and Schocken, MIT Press.
// File name: projects/01/DMux4Way.hdl
/**
* 4-way demultiplexor:
* {a, b, c, d} = {in, 0, 0, 0} if sel == 00
* {0, in, 0, 0} if sel == 01
* {0, 0, in, 0} if sel == 10
* {0, 0, 0, in} if sel == 11
*/
CHIP DMux4Way {
IN in, sel[2];
OUT a, b, c, d;
PARTS:
// Put your code here:
Not(in=sel[0], out=nsel0);
Not(in=sel[1], out=nsel1);
And(a=nsel0, b=nsel1, out=outa);
And(a=in, b=outa, out=a);
And(a=nsel0, b=sel[1], out=outb);
And(a=in, b=outb, out=b);
And(a=sel[0], b=nsel1, out=outc);
And(a=in, b=outc, out=c);
And(a=sel[0], b=sel[1], out=outd);
And(a=in, b=outd, out=d);
//DMux(in=in,sel=sel[1],a=ao,b=bo);
//DMux(in=ao,sel=sel[0],a=a,b=b);
//DMux(in=bo,sel=sel[0],a=c,b=d);
}

Your chip is producing the wrong result when in=1 and sel[2]=01 and also when in=1 and sel[2]=11 (line 8). If you single-step the simulator, you will see that when you do the tests, the output pin that gets set doesn't increment the way you want it to.
So why is that? It has to do with misunderstanding what bits in sel are referred to by sel[0] and sel[1]. Sel[0] is the rightmost, least-significant bit in sel. Sel[1] is the leftmost, most-significant bit. Your chip assumes the opposite.
Don't feel bad, this kind of mistake has bitten every programmer at least once.
See also: https://en.wikipedia.org/wiki/Endianness

Related

Removing DC component for matrix in chuncks in octave

I'm new to octave and if this as been asked and answered then I'm sorry but I have no idea what the phrase is for what I'm looking for.
I trying to remove the DC component from a large matrix, but in chunks as I need to do calculations on each chuck.
What I got so far
r = dlmread('test.csv',';',0,0);
x = r(:,2);
y = r(:,3); % we work on the 3rd column
d = 1
while d <= (length(y) - 256)
e = y(d:d+256);
avg = sum(e) / length(e);
k(d:d+256) = e - avg; % this is the part I need help with, how to get the chunk with the right value into the matrix
d += 256;
endwhile
% to check the result I like to see it
plot(x, k, '.');
if I change the line into:
k(d:d+256) = e - 1024;
it works perfectly.
I know there is something like an element-wise operation, but if I use e .- avg I get this:
warning: the '.-' operator was deprecated in version 7
and it still doesn't do what I expect.
I must be missing something, any suggestions?
GNU Octave, version 7.2.0 on Linux(Manjaro).
Never mind the code works as expected.
The result (K) got corrupted because the chosen chunk size was too small for my signal. Changing 256 to 4096 got me a better result.
+ and - are always element-wise. Beware that d:d+256 are 257 elements, not 256. So if then you increment d by 256, you have one overlaying point.

SWI-Prolog: Generalize a predicate to calcluate the power of some function

I want to generalize some predicate written in swi-prolog to calculate the power of some function. My predicate so far is:
% calculates the +Power and the +Argument of some function +Function with value +Value.
calc_power(Value, Argument, Function, Power) :-
not(Power is 0),
Power is Power_m1 + 1,
Value =..[Function, Buffer],
calc_power(Buffer, Argument, Function, Power_m1), !.
calc_power(Argument, Argument, _, 0).
The call calc_power((g(a)),A,f,POW). gives so far:
A = g(a),
POW = 0.
My generalization should also solve calls like that:
calc_power(A1, a, f, 3).
the solution should be in that special calse A1 = f(f(f(a))). But for some reason it doesn't work. I get the error:
ERROR: Arguments are not sufficiently instantiated
in line
Power is Power_m1 + 1
it means probably in swi prolog it is not possible to take plus with two variables. How can I solve this problem?
Can delay the + 1 operation with:
int_succ(I0, I1) :-
( nonvar(I0) ->
integer(I0),
I0 >= 0,
I1 is I0 + 1
; nonvar(I1) ->
integer(I1),
I1 >= 1,
I0 is I1 - 1
; when((nonvar(I0) ; nonvar(I1)), int_succ(I0, I1))
).
Example in swi-prolog:
?- int_succ(I0, I1), I1 = 7.
I0 = 6,
I1 = 7.
This is more flexible than https://www.swi-prolog.org/pldoc/man?predicate=succ/2 , and can of course be modified to support negative numbers if desired.
Found some solution
:- use_module(library(clpfd)).
% calculates the +Power and the +Argument of some function +Function with value +Value.
calc_power(Argument, Argument, _, 0).
calc_power(Value, Argument, Function, Power) :-
Power #\= 0,
Power #= Power_m1 + 1,
Value =..[Function, Buffer],
calc_power(Buffer, Argument, Function, Power_m1).

What's wrong with this recursive curried function

I was trying to write a function that solves following;
persistence 39 = 3 // because 3*9 = 27, 2*7 = 14, 1*4=4
// and 4 has only one digit
persistence 999 = 4 // because 9*9*9 = 729, 7*2*9 = 126,
// 1*2*6 = 12, and finally 1*2 = 2
persistence 4 = 0 // because 4 is already a one-digit number
After I solved the question I tried to make all functions looks like Ramda.js function styles like this;
This code works;
let multiply = List.reduce (*)
let gt from input = input > from
let just input = fun _ -> input
let ifElse cond trueFn falseFn input =
if cond input then trueFn input else falseFn input
let digits n =
(string n) |> Seq.toList |> List.map (System.Char.GetNumericValue >> int)
let rec persRec iter current =
current
|> digits
|> multiply
|> ifElse (gt 9) (persRec (iter + 1)) (just iter)
let persistence n = if n > 9 then persRec 1 n else 0
But when I tried to modify persRec function with a curried composed version like following, it makes this stack overflow.
let rec persRec iter =
digits
>> multiply
>> ifElse (gt 9) (persRec (iter + 1)) (just iter)
What's wrong with this?
The function persRec is calling itself unconditionally. Here:
>> ifElse (gt 9) (persRec (iter + 1)) (just iter)
^^^^^^^^^^^^^^^^^^^^
|
unconditional recursive call
This happens always. Every time persRec is called by somebody, it immediately calls itself right away.
You may expect that the recursive call should only happen when gt 9, because, after all, it's inside an ifElse, right? But that doesn't matter: ifElse is not special, it's just a function. In order to call a function, F# has to compute all its parameter before the call (aka "applicative order of evaluation"), which means it has to call persRec (iter + 1) before it can call ifElse, and it has to call ifElse before it can call (>>), and it has to call (>>) in order to compute result of persRec. So ultimately, it needs to call persRec in order to compute the result of persRec. See where this is going?
The previous version works, because the body of persRec is not actually executed before the call to ifElse. The body of persRec will only be executed when all its parameters are supplied, and the last parameter will only be supplied inside the body of ifElse when the condition is true.
The way I see it, the confusion stems from the difference between denotational and operational semantics. Yes, mathematically, logically, the functions are equivalent. But execution also matters. Normal vs. applicative evaluation order. Memory concerns. Performance. Those are all outside of the domain of lambda-calculus.

Assembly program that identifies if parameters are different or same.

Hi I am working on an assembly, technically HLA(High Level Assembly) assignment and I am a bug that I need help with. Here is the assignment: Write an HLA Assembly language program that implements a function which correctly identifies whether all the parameters are different, returning either 0 or 1 in EAX depending on whether this condition has been met. This function should have the following signature:
procedure allDifferent( x: int16; y : int16; z : int16 ); #nodisplay; #noframe;
Shown below is a sample program dialogue.
Feed Me X: 205
Feed Me Y: 170
Feed Me Z: 91
allDifferent returns true!
Feed Me X: 0
Feed Me Y: 0
Feed Me Z: 0
allDifferent returns false!
Feed Me X: 121
Feed Me Y: 121
Feed Me Z: 121
allDifferent returns false!
Here is the code I have. My problem is that regardless of what numbers I put in, it always returns "allDifferent returns false!" Thanks you for the help.
program allDifferent;
#include( "stdlib.hhf" );
static
iDataValue1 : int16 := 0;
iDataValue2 : int16 := 0;
iDataValue3 : int16 := 0;
iDataValue4 : int16 := 0;
procedure allDiff( x: int16; y : int16; z : int16 ); #nodisplay; #noframe;
static
returnAddress : dword;
temp : int16;
begin allDiff;
pop(returnAddress);
pop(z);
pop(y);
pop(x);
pop(temp);
push(returnAddress);
push(AX);
push(BX);
mov(x, AX);
cmp(y, AX);
je xyequal;
jmp notequal;
xyequal:
mov(y, BX);
cmp(z, BX);
je equal;
jmp notequal;
equal:
mov(0, EAX);
jmp ExitSequence;
notequal:
mov(1, EAX);
jmp ExitSequence;
ExitSequence:
pop(BX);
pop(AX);
ret();
end allDiff;
begin allDifferent;
stdout.put( "Gimme a X:" );
stdin.get( iDataValue1 );
stdout.put("Gimme a Y:");
stdin.get(iDataValue2);
stdout.put("Gimme a Z:");
stdin.get(iDataValue3);
push( iDataValue1 );
push( iDataValue2 );
push( iDataValue3 );
push( iDataValue4 );
call allDiff;
cmp(EAX, 1);
je ISDIFFERENT;
jmp NOTDIFFERENT;
ISDIFFERENT:
stdout.put("allDifferent retursn true",nl);
jmp EndProgram;
NOTDIFFERENT:
stdout.put("allDifferent retursn false",nl);
jmp EndProgram;
stdout.newln();
EndProgram:
end allDifferent;
notequal:
mov(1, EAX); <<- good.
jmp ExitSequence;
:
ExitSequence:
pop(BX);
pop(AX); <<- not so good.
ret();
Have a close look at what's happening to AX in the above sequence. Even though you set it to something within the code, you overwrite that value with the pop instruction, reverting AX to whatever it was when you entered the function.
Assembler functions should generally preserve and restore registers that may be being used by the callers, but not when you want to use that register to return some useful piece of information.
In addition, your parameters are not being treated correctly. You push them in the order {p1, p2, p3, junk} (not sure why you have a fourth parameter since you don't use it for anything).
But, within the function, you pop in the order {x, y, z, temp}. Now, because the stack is a LIFO (last in, first out) structure, the mappings will be:
junk -> x
p3 -> y
p2 -> z
p1 -> temp
That means the x variable will be set to some arbitrary value rather than one of the "real" parameters you passed in.
If you're not going to use that fourth parameter, I'd suggest getting rid of it. If you do want to use it at some point, you'll need to correlate your push and pop operations so you get the correct values.
As an aside, you could probably also make your code a lot cleaner in a couple of ways.
First, there's no real need to use (or save/restore) BX since AX is used locally (in a small mov/cmp block). You could use AX both for the xy check and the yz check.
Second, you could get rid of quite a few of the jumps that aren't actually needed. The pseudo-code for your algorithm can boil down to a very simple:
if x and y are same, go to NOTDIFF.
if y and z are same, go to NOTDIFF.
DIFF:
set AX to 1
go to END
NOTDIFF:
set AX to 0
END:
return

After one call to myfun, new parametrization does not affect the result, which conforms to the first call

I am new to Octave although I can say I am an expert Matlab user. I am running Octave on a Linux server (Red Hat) remotely through PuTTY, from a windows machine.
I am observing a very strange behavior in Octave. I call myfun(a) which performs as expected giving the sought results. Now, if I run, say, myfun(b) with b!=a, I get again myfun(a). Clear -f does not solve the problem. I need to reboot octave to change the parameters.
What am I doing wrong?
Thanks a lot
Francesco
This is the code for the function I mentioned:
function [a, v, obj, infos, iter] = mle_garch( p )
#{
% this function estimates the GARCH(1,1) parameters
% it is assumed we pass the adjusted price level p
#}
global y = (diff(log(p))-mean(diff(log(p))))*100;
global h = zeros(size(y));
a0 = [var(y)*0.9; 0.8; 0.1];
[a, obj, infos, iter] = sqp(a0, #loglike_garch, [], #loglike_con, [], [], 1000);
v = sqrt(h * 260);
endfunction
function g = loglike_garch( a )
global y h
n = length(y);
h(1) = var(y);
for i = 2 : n,
h(i) = a(1) + a(2) * h(i-1) + a(3) * y(i-1)^2;
endfor
g = 0.5 * ( sum(log(h)) + sum(y.^2./h) ) / n;
endfunction
function f = loglike_con( a )
f = [1;0;0;0] + [0 -1 -1;eye(3)] * a;
endfunction
I'm assuming the myfun you mentioned is mle_garch. The problem is the way you're initializing the global h and v variables (do you really need them to be global?). When you have a piece of code like this
global y = (diff(log(p))-mean(diff(log(p))))*100;
global h = zeros(size(y));
the values of y and h are defined the first time only. You can change their values later on, but this specific lines will never be ran again. Since your code only uses the input argument to define these two variables, the value which you use to run the function the first time will be used every single other time. If you really want to keep those variables global, replace it with the following:
global y;
global h;
y = (diff(log(p))-mean(diff(log(p))))*100;
h = zeros(size(y));
But I don't see any reason to keep them global so just don't make them global.
Also, you mentioned this code worked fine in Matlab. I was under the impression that you couldn't initialize global and persistent variables in Matlab which would make your code illegal in Matlab.