So I am trying to design a 4-bit carry select adder in verilog, and am using the following code for the design:
module fullAdder (S,Cout,P,G,A,B,Cin);
// Define all inputs and outputs for single bit Fulll Adder
output S;
output Cout;
output P;
output G;
input A;
input B;
input Cin;
// Full Adder body, define structure and internal wiring
wire t1, t2, t3;
xor xor1 (t1, A, B);
xor xor2 (S, t1, Cin);
or or1 (P, A, B);
and and1 (G, A, B);
and and2 (t2, P, Cin);
or or2 (Cout, t2, G);
endmodule
module carrySelect (sum, cout, a, b, cin);
output [3:0] sum; //sum output of the adder, 4 bits wide
output cout; //carry out of the adder
input [3:0] a; //input a, 4 bits wide
input [3:0] b; //input b, 4 bits wide
input cin; //carry in of the adder
reg ch, cl; //temporary variables to define cases that previous carry is high or low
wire [3:0] C; //carry bus
wire [3:0] P,G; //buses for P and G outputs of fullAdder
wire [1:0] s0, s1, s2, s3; //temporary buses for cases of sums
wire [1:0] c0, c1, c2, c3; //temporary buses for cases of carries
assign ch = 1; //assign ch to high and cl to low
assign cl = 0;
//least significant full adder computation
fullAdder f0_h (s0[0],c0[0],p0[0], g0[0], a[0], b[0], ch);
fullAdder f0_l (s0[1],c0[1],p0[1], g0[1], a[0], b[0], cl);
fullAdder f1_h (s1[0],c1[0],p1[0], g1[0], a[0], b[0], ch);
fullAdder f1_l(s1[1],c1[1],p1[1], g1[1], a[0], b[0], cl);
fullAdder f2_h (s2[0],c2[0],p2[0], g2[0], a[0], b[0], ch);
fullAdder f2_l (s2[1],c2[1],p2[1], g2[1], a[0], b[0], cl);
//most significant full adder computation
fullAdder f3_h (s3[0],c3[0],p3[0], g3[0], a[0], b[0], ch);
fullAdder f3_l (s3[1],c3[1],p3[1], g3[1], a[0], b[0], cl);
//select output depending on values of carries
if (cin == 1) begin
assign sum[0] = s0[0];
assign C[0] = c0[0];
end else begin
assign sum[0] = s0[1];
assign C[0] = c0[1];
end
if(C[0] == 1) begin
assign sum[1] = s1[0];
assign C[1] = c1[0];
end else begin
assign sum[1] = s1[1];
assign C[1] = c1[1];
end
if(C[1]) begin
assign sum[2] = s2[0];
assign C[2] = c2[0];
end else begin
assign sum[2] = s2[1];
assign C[2] = c2[1];
end
if(C[2]) begin
assign sum[3] = s3[0];
assign C[3] = c3[0];
end else begin
assign sum[3] = s3[1];
assign C[3] = c3[1];
end
//assign carry out
assign cout = C[3];
endmodule
where the full adder is completely functional, so there are no problems there. I get errors from the if statements when I try to compile the code, and get the warning about implicit definitions and error of not being able to evaluate genvar of the conditional in the ifs. I am fairly new to verilog, so I apologize if this is a trivial fix. Any help is appreciated.
EDIT1:Error/warning message thrown
design.sv:57: warning: implicit definition of wire fullAdderTest.UUT.cin.
design.sv:57: error: Cannot evaluate genvar conditional expression: (cin)==('sd1)
design.sv:57: error: Cannot evaluate genvar conditional expression: (cin)==('sd1)
design.sv:65: warning: implicit definition of wire fullAdderTest.UUT.C.
design.sv:65: error: Cannot evaluate genvar conditional expression: (C['sd0])==('sd1)
design.sv:65: error: Cannot evaluate genvar conditional expression: (C['sd0])==('sd1)
design.sv:73: warning: Constant bit select [1] is after vector C[0:0].
design.sv:73: : Replacing select with a constant 1'bx.
design.sv:73: warning: Constant bit select [1] is after vector C[0:0].
design.sv:73: : Replacing select with a constant 1'bx.
design.sv:81: warning: Constant bit select [2] is after vector C[0:0].
design.sv:81: : Replacing select with a constant 1'bx.
design.sv:81: warning: Constant bit select [2] is after vector C[0:0].
design.sv:81: : Replacing select with a constant 1'bx.
4 error(s) during elaboration.
An if statement outside of an always or initial block is treated as a if it was inside an generate block. A generate's if statement will accepts literal constants (hard coded values), parameters, and genvars. It will not accept net or register types (i.e: wire, reg, integer, etc). Generate blocks are evaluated during elaboration and therefore cannot depend on simulation variables with dynamic values.
You want conditionally select the values for sum and C based on input values. There are a few options to do this:
One option is to make an inline condition statement:
assign sum[0] = cin ? s0[0] : s0[1];
assign C[0] = cin ? c0[0] : c0[1];
// ...
Or you can select the index (same effect):
assign sum[0] = s0[!cin];
assign C[0] = c0[!cin];
assign sum[1] = s1[!C[0]];
assign C[1] = c1[!C[0]];
// ...
Or make sum and C reg types and put all the if statements inside an always block (remove the assigns):
always #* begin
if (cin == 1) begin
sum[0] = s0[0];
C[0] = c0[0];
end
else begin
sum[0] = s0[1];
C[0] = c0[1];
end
// ...
end
Related
I got the js code below from an archive of hackers delight (view the source)
The code takes in a value (such as 7) and spits out a magic number to multiply with. Then you bitshift to get the results. I don't remember assembly or any math so I'm sure I'm wrong but I can't find the reason why I'm wrong
From my understanding you could get a magic number by writing ceil(1/divide * 1<<32) (or <<64 for 64bit values, but you'd need bigger ints). If you multiple an integer with imul you'd get the result in one register and the remainder in another. The result register is magically the correct result of a division with this magic number from my formula
I wrote some C++ code to show what I mean. However I only tested with the values below. It seems correct. The JS code has a loop and more and I was wondering, why? Am I missing something? What values can I use to get an incorrect result that the JS code would get correctly? I'm not very good at math so I didn't understand any of the comments
#include <cstdio>
#include <cassert>
int main(int argc, char *argv[])
{
auto test_divisor = 7;
auto test_value = 43;
auto a = test_value*test_divisor;
auto b = a-1; //One less test
auto magic = (1ULL<<32)/test_divisor;
if (((1ULL<<32)%test_divisor) != 0) {
magic++; //Round up
}
auto answer1 = (a*magic) >> 32;
auto answer2 = (b*magic) >> 32;
assert(answer1 == test_value);
assert(answer2 == test_value-1);
printf("%lld %lld\n", answer1, answer2);
}
JS code from hackers delight
var two31 = 0x80000000
var two32 = 0x100000000
function magic_signed(d) { with(Math) {
if (d >= two31) d = d - two32// Treat large positive as short for negative.
var ad = abs(d)
var t = two31 + (d >>> 31)
var anc = t - 1 - t%ad // Absolute value of nc.
var p = 31 // Init p.
var q1 = floor(two31/anc) // Init q1 = 2**p/|nc|.
var r1 = two31 - q1*anc // Init r1 = rem(2**p, |nc|).
var q2 = floor(two31/ad) // Init q2 = 2**p/|d|.
var r2 = two31 - q2*ad // Init r2 = rem(2**p, |d|).
do {
p = p + 1;
q1 = 2*q1; // Update q1 = 2**p/|nc|.
r1 = 2*r1; // Update r1 = rem(2**p, |nc|.
if (r1 >= anc) { // (Must be an unsigned
q1 = q1 + 1; // comparison here).
r1 = r1 - anc;}
q2 = 2*q2; // Update q2 = 2**p/|d|.
r2 = 2*r2; // Update r2 = rem(2**p, |d|.
if (r2 >= ad) { // (Must be an unsigned
q2 = q2 + 1; // comparison here).
r2 = r2 - ad;}
var delta = ad - r2;
} while (q1 < delta || (q1 == delta && r1 == 0))
var mag = q2 + 1
if (d < 0) mag = two32 - mag // Magic number and
shift = p - 32 // shift amount to return.
return mag
}}
In the C CODE:
auto magic = (1ULL<<32)/test_divisor;
We get Integer Value in magic because both (1ULL<<32) & test_divisor are Integers.
The Algorithms requires incrementing magic on certain conditions, which is the next conditional statement.
Now, multiplication also gives Integers:
auto answer1 = (a*magic) >> 32;
auto answer2 = (b*magic) >> 32;
C CODE is DONE !
In the JS CODE:
All Variables are var ; no Data types !
No Integer Division ; No Integer Multiplication !
Bitwise Operations are not easy and not suitable to use in this Algorithm.
Numeric Data is via Number & BigInt which are not like "C Int" or "C Unsigned Long Long".
Hence the Algorithm is using loops to Iteratively add and compare whether "Division & Multiplication" has occurred to within the nearest Integer.
Both versions try to Implement the same Algorithm ; Both "should" give same answer, but JS Version is "buggy" & non-standard.
While there are many Issues with the JS version, I will highlight only 3:
(1) In the loop, while trying to get the best Power of 2, we have these two statements :
p = p + 1;
q1 = 2*q1; // Update q1 = 2**p/|nc|.
It is basically incrementing a counter & multiplying a number by 2, which is a left shift in C++.
The C++ version will not require this rigmarole.
(2) The while Condition has 2 Equality comparisons on RHS of || :
while (q1 < delta || (q1 == delta && r1 == 0))
But both these will be false in floating Point Calculations [[ eg check "Math.sqrt(2)*Math.sqrt(0.5) == 1" : even though this must be true, it will almost always be false ]] hence the while Condition is basically the LHS of || , because RHS will always be false.
(3) The JS version returns only one variable mag but user is supposed to get (& use) even variable shift which is given by global variable access. Inconsistent & BAD !
Comparing , we see that the C Version is more Standard, but Point is to not use auto but use int64_t with known number of bits.
First I think ceil(1/divide * 1<<32) can, depending on the divide, have cases where the result is off by one. So you don't need a loop but sometimes you need a corrective factor.
Secondly the JS code seems to allow for other shifts than 32: shift = p - 32 // shift amount to return. But then it never returns that. So not sure what is going on there.
Why not implement the JS code in C++ as well and then run a loop over all int32_t and see if they give the same result? That shouldn't take too long.
And when you find a d where they differ you can then test a / d for all int32_t a using both magic numbers and compare a / d, a * m_ceil and a * m_js.
I am trying to create multiple adders via Verilog to compare the speed of each adder.
I am getting the following error Unable to bind parameter WIDTH in arith_unit
This is my code so far:
module arith_unit
#(
parameter ADDER_TYPE = 0,
parameter WIDTH = 8)
(input [WIDTH-1:0] a,
input [WIDTH-1:0] b,
output [WIDTH-1:0] sum,
);
////////////////////////////////////////////////////////////////
if (ADDER_TYPE == 0)
begin
ripple_carry rc1 (a, b, cin, sum, cout);
end
////////////////////////////////////////////////////////////////
else if (ADDER_TYPE == 1)
begin
carry_bypass cb1 (a, b, cin, sum, cout);
end
//// more else statment for ADDER_TYPE...
endmodule
//////////////////////////////////////////////////////////////////
module ripple_carry_4_bit(a, b, cin, sum, cout);
input [3:0] a,b;
input cin;
wire c1,c2,c3;
output [3:0] sum;
output cout;
full_adder fa0(.a(a[0]), .b(b[0]),.cin(cin), .sum(sum[0]),.cout(c1));
full_adder fa1(.a(a[1]), .b(b[1]), .cin(c1), .sum(sum[1]),.cout(c2));
full_adder fa2(.a(a[2]), .b(b[2]), .cin(c2), .sum(sum[2]),.cout(c3));
full_adder fa3(.a(a[3]), .b(b[3]), .cin(c3), .sum(sum[3]),.cout(cout));
endmodule
////////////////////////////////////////////////////////////////
module ripple_carry (a, b, cin, sum, cout);
input [WIDTH-1:0] a,b;
input cin;
wire c1,c2,c3, c4, c5, c6, c7;
output [WIDTH-1:0] sum;
output cout;
if (WIDTH == 8) begin //<-------- compiler is pointing here as the problem
ripple_carry_4_bit rca1 (.a(a[3:0]),.b(b[3:0]),.cin(cin), .sum(sum[3:0]),.cout(c1));
ripple_carry_4_bit rca2 (.a(a[7:4]),.b(b[7:4]),.cin(c1), .sum(sum[7:4]),.cout(cout));
end
else if (WIDTH == 16) begin
ripple_carry_4_bit rca1 (.a(a[3:0]),.b(b[3:0]),.cin(cin), .sum(sum[3:0]),.cout(c1));
ripple_carry_4_bit rca2 (.a(a[7:4]),.b(b[7:4]),.cin(c1), .sum(sum[7:4]),.cout(c2));
ripple_carry_4_bit rca3 (.a(a[11:8]),.b(b[11:8]),.cin(c2), .sum(sum[11:8]),.cout(c3));
ripple_carry_4_bit rca4 (.a(a[15:12]),.b(b[15:12]),.cin(c3), .sum(sum[15:12]),.cout(cout));
end
//// more else statment for 32 & 64 bits...
endmodule
I looked online and it seems that my if and else statements are correct. So I am assuming that my WIDTH is declared wrong? I tried passing in WIDTH via module ripple_carry (a, b, cin, sum, cout, WIDTH); kind of how you would do it with C++, but I still get the same error.
I've tested the ripple_carry on its own (no if statements, no parameter) with 8 bits, 16 bits, etc. and it works fine. So I know that my logic for the ripple_carry is fine.
Please help me, thank you.
It would have helped to show the exact error message with the line number, but you are missing a WIDTH parameter declaration in the module ripple_carry.
module ripple_carry #(parameter WIDTH=8)(...
And add it when instantiating it inside the generate block.
ripple_carry #(WIDTH) (a, b, cin, sum, cout);
Consider the problem of examining a string x = x1x2 ...xn from an
alphabet of k symbols, and a multiplication table over this alphabet.
Decide whether or not it is possible to parenthesize x in such a way
that the value of the resulting expression is a, where a belongs to
the alphabet. The multiplication table is neither commutative or
associative, so the order of multiplication matters.
Write the below in matrix table form for understanding : a,b,c along x and y axis.
(a,a)=a;
(a,b)=c (a,c)=c
(b,a)=a (b,b)=a (b,c)=b
(c,a)=c (c,b)=c (c,c)=c
For example, consider the above multiplication table and the
string bbbba. Parenthesizing it (b(bb))(ba) gives a, but ((((bb)b)b)a)
gives c. Give an algorithm, with time polynomial in n and k, to decide
whether such a parenthesization exists for a given string,
multiplication table, and goal element.
I unserstood the ques but i donot understand how to start with this.
i am required to solve the following in C, C++ . Python etc are not allowed.
Iam guessing a boolean approach might work.
Here is a suggestion for how the problem can be solved.
Basically, the code is testing all cases from the multiplication table that yields the desired result and checks whether any of them can be achieved:
char alphabet[] = "abc";
char multiplicationTable[][] = { { 'a', 'c', 'c' },
{ 'a', 'a', 'b' },
{ 'c', 'c', 'c' } }; // Dimensions are k*k.
int N = strlen(s);
int k = strlen(alphabet);
char *s = "bbbba"; // The string
/* Recursive function that returns 1 if it is
* possible to get symbol from
* string s of length n.
*/
int isSymbolPossible(char *s, char symbol, int n) {
int i, j1, j2;
if (n == 1) {
return *s == symbol;
}
/* Loop over all possible ways to split the string in two. */
for (i=0; i < n - 1; i++) {
/* For each such subdivision, find all the multiplications that yield the desired symbol */
for (j1 = 0; j1 < k; j1++) {
for (j2=0; j2 < k; j2++) {
if (multiplication_table[j1][j2] == symbol) {
/* Check if it is possible to get the required left and right symbols for this multiplication */
if (isSymbolPossible(s, alphabet[j1], i+1) &&
isSymbolPossible(s+i+1, alphabet[j2], n - i - 1) {
return 1;
}
}
}
}
}
return 0;
}
int main() {
if (isSymbolPossible(s,'a',N) {
printf("Yes\n");
} else {
printf("No\n");
}
return 0;
}
I haven't calculated the complexity of the solution, so I'm not sure if it fullfills the requirement. You would probably have to add memoization to reduce the complexity further.
Further explanation:
There are 3 multiplications that yield a: a*a, b*a and b*b. So the last multiplication must be one of those. The algorithm starts by placing parenthesis for the last multiplication,
It checks all possible placements: (b)(bbba), (bb)(bba), (bbb)(ba), and last (bbbb)(a).
For each placement it checks to see if it is possible to match it to one of the multiplications that yield a.
So let's see how it would match (bbb)(ba) against the multiplication a*a:
It then need to check if it is possbile to get an a from the left expression and an a from the right expression.
So it calls itself:
isSymbolPossible("bbb", 'a', 3); // Is it possible to get an 'a' for the string "bbb"
isSymbolPossible("ba", 'a', 2); // Is it possible to get an 'a' for the string "ba"
Let's see what happens in the last of these two, the string "ba":
It will check if it is possible to get an a, so again there are 3 possibles. There is only one way to divide "ba", so the two subexpressions are "b" and "a".
It first checks the multiplication a*a.
isSymbolPossible("b", 'a', 1); // Is it possible to get an 'a' for the string "b" - no it isn't! - skip this multiplication
It then checks the multiplication b*a.
isSymbolPossible("b", 'b', 1); // Is it possible to get a 'b' for the string "b" - yes, so check the right expression too
isSymbolPossible("a", 'a', 1); // Is it possible to get an 'a' for the string "a" - yes
You can see that it solves the problem by breaking it down into smaller parts and checking all routes that can lead to the desired end and skipping other routes as soon as it discovers that they are dead ends.
Might be a very basic question but I just got stuck with it. I am trying to run the following recursive function:
//If a is 0 then return b, if b is 0 then return a,
//otherwise return myRec(a/2, 2*b) + myRec(2*a, b/2)
but it just gets stuck in infinite loop. Can anybody help me to run that code and explain how exactly that function works? I built various recursive functions with no problems but this one just drilled a hole in my head.
Thanks.
Here is what I tried to do:
#include<iostream>
int myRec(int a, int b){
if (a==0){
return b;
}
if (b==0){
return a;
}
else return myRec(a/2, 2*b) + myRec(2*a, b/2);
}
int main()
{
if (46 == myRec(100, 100)) {
std::cout << "It works!";
}
}
Well, let us mentally trace it a bit:
Starting with a, b (a >= 2 and b >= 2)
myRec(a/2, 2*b) + something
something + myRec(2*a', b'/2)
Substituting for a/2 for a' and 2*b for b', we get myRec(2*(a/2), (b*2)/2), which is exactly where we started.
Therefore we will never get anywhere.
(Note that I have left out some rounding here, but you should easily see that with this kind of rounding you will only round down a to the nearest even number, at which point it will be forever alternating between that number and half that number)
I think you are missing on some case logic. I last program in C ages ago so correct my syntax if wrong. Assuming numbers less than 1 will be converted to zero automatically...
#include<iostream>
int myRec(int a, int b){
// Recurse only if both a and b are not zero
if (a!=0 && b!=0) {
return myRec(a/2, 2*b) + myRec(2*a, b/2);
}
// Otherwise check for any zero for a or b.
else {
if (a==0){
return b;
}
if (b==0){
return a;
}
}
}
UPDATE:
I have almost forgot how C works on return...
int myRec(int a, int b){
if (a==0){
return b;
}
if (b==0){
return a;
}
return myRec(a/2, 2*b) + myRec(2*a, b/2);
}
VBA equivalent with some changes for displaying variable states
Private Function myRec(a As Integer, b As Integer, s As String) As Integer
Debug.Print s & vbTab & a & vbTab & b
If a = 0 Then
myRec = b
End If
If b = 0 Then
myRec = a
End If
If a <> 0 And b <> 0 Then
myRec = myRec(a / 2, 2 * b, s & "L") + myRec(2 * a, b / 2, s & "R")
End If
End Function
Sub test()
Debug.Print myRec(100, 100, "T")
End Sub
Running the test in Excel gives this (a fraction of it as it overstacks Excel):
T: Top | L: Left branch in myRec | R: Right branch in myRec
The root cause will be the sum of the return which triggers more recursive calls.
Repeating of the original values of a and b on each branch from level 2 of the recursive tree...
So MyRec(2,2) = MyRec(1,4) + MyRec(4,1)
And MyRec(1,4) = MyRec(.5,8) + MyRec(2,2)
So MyRec(2,2) = MyRec(.5,8) + MyRec(2,2) + MyRec(4,1)
Oops.
(The .5's will actually be zeroes. But it doesn't matter. The point is that the function won't terminate for a large range of possible inputs.)
Expanding on gha.st's answer, consider the function's return value as a sum of expressions without having to worry about any code.
Firstly, we start with myRec(a,b). Let's just express that as (a,b) to make this easier to read.
As I go down each line, each expression is equivalent, disregarding the cases where a=0 or b=0.
(a,b) =
(a/2, 2b) + (2a, b/2) =
(a/4, 4b) + (a, b) + (a, b) + (4a, b/4)
Now, we see that at a non-terminating point in the expression, calculating (a,b) requires first calculating (a,b).
Recursion on a problem like this works because the arguments typically tend toward a 'base case' at which the recursion stops. A great example is sorting a list; you can recursively sort halves of the list until a list given as input has <= 2 elements, which is trivial without recursion. This is called mergesort.
However, your myRec function does not have a base case, since for non-zero a or b, the same arguments must be passed into the function at some point. That's like trying to sort a list, in which half of the list has as many elements as the entire list.
Try replacing the recursion call with:
return myRec(a/2, b/3) + myRec(a/3, b/2);
I need help with this problem POUR1. I think
it can be solved with bruteforce approach, but I read that it is a graph problem (BFS). I solved problems like ABCPATH, LABYR1, PT07Y, PT07Z, BITMAP, ...
But I don't know how to approach POUR1 in BFS manner.
Can someone give me some advice?
Problem statement:
Given two vessels, one of which can accommodate a litres of water and the other - b litres of water, determine the number of steps required to obtain exactly c litres of water in one of the vessels.
At the beginning both vessels are empty. The following operations are counted as 'steps':
emptying a vessel,
filling a vessel,
pouring water from one vessel to the other, without spilling, until one of the vessels is either full or empty.
Input:
An integer t, 1<=t<=100, denoting the number of testcases, followed by t sets of input data, each consisting of three positive integers a, b, c, not larger than 40000, given in separate lines.
Output:
For each set of input data, output the minimum number of steps required to obtain c litres, or -1 if this is impossible.
Example:
Sample input:
2
5
2
3
2
3
4
Sample output:
2
-1
This question has a simpler solution. No need for BFS. Ad-hoc would do good.
method 1 - fill A, empty it into B. whenever A becomes empty fill it back, whenever B becomes full empty it. (all the above-mentioned actions count as individual moves). Continue this process until you arrive at the required amount of water in any one of the vessels. Get the number of moves here. (say C1).
method 2 - fill B, empty it into A. whenever B becomes empty fill it back, whenever A becomes full empty it. Continue this until you arrive at the required amount. Get the number of moves say C2).
The answer is min(C1,C2).
Source code in C++:
#include < cstdio >
#include < algorithm >
using namespace std;
int pour(int A, int B, int C) {
int move = 1, a = A, b = 0, tfr;
while (a != C && b != C) {
tfr = min(a, B - b);
b += tfr;
a -= tfr;
move++;
if (a == C || b == C)
break;
if (a == 0) {
a = A;
move++;
}
if (b == B) {
b = 0;
move++;
}
}
return move;
}
/** Reason for calculating GCD of a,b is to check whether an integral solution of
* equation of form ax + by = c exist or not, to dig deeper read Diophantine Equations
*/
int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
int main() {
int t, a, b, c;
scanf("%d", & t);
while (t--) {
scanf("%d%d%d", & a, & b, & c);
if (c > a && c > b)
printf("-1\n");
else if (c % gcd(a, b) != 0)
printf("-1\n");
else if (c == a || c == b)
printf("1\n");
else
printf("%d\n", min(pour(a, b, c), pour(b, a, c)));
}
return 0;
}
Consider the set of all a priori possibles states (eg [3, 7] meaning Vessel1 contains 3 litters and vessel2 contains 7 litters). You have a directed graph whose vertices are those states and whose edges are the possible moves. The question is to find a path in the graph joining the state [0, 0] to either a state of type [c, ?] or a state of type [?, c]. Such a path is typically searched by a BFS.