Verilog: More efficient way to use ternary operator - conditional-statements

I have written the following assign statement:
assign F = (BCD == 4'd1 | BCD == 4'd2 | BCD == 4'd3 | BCD == 4'd4 | BCD == 4'd5) ? 1'b1 : 1'b0;
where if the BCD input (4-bits) is 1-5, the function returns a 1 and otherwise returns a 0. This works perfectly how I intended, but I'm looking for a more efficient way to write the "OR" parts. Is there a more efficient way to write this?

There's no need for the ternary operator here. The result of each equality(==) is 1-bit, and you are doing a bit-wise OR (|). You probably should be using a logical OR (||) whose result is also 1-bit.
assign F = (BCD == 4'd1 || BCD == 4'd2 || BCD == 4'd3 || BCD == 4'd4 || BCD == 4'd5);
In SystemVerilog which most tools are supporting, you can use the inside operator
assign F = BCD inside {[1:5]}; // contiguous range
assign F = BCD inside {[1:3],5, [7:10]}; // noncontiguous values

No, one should use each complete expressions separated by |. However, in this particular situation, you can use (BCD >= 4'd1) & (BCD <= 4'd5).

Since your values are in a continuous range, this can be simplified as:
assign F = ((BCD >= 4'd1) && (BCD <= 4'd5));
If your tool set supports SystemVerilog syntax, you could also use the inside operator. Refer to IEEE Std 1800-2017, section 11.4.13 Set membership operator.

There are several ways to do this:
a) Boundary check.
assign F = (BCD > 4'd0) & (BCD < 4'd6);
b) OR reduction and a high limit check.
assign F = |BCD & (BCD < 4'd6);
c) This is a behavioural hardware description, it would be optimized by the synthesis tool. It is parameterized, though.
localparam LOW = 1;
localparam HIGH = 5;
integer i;
reg F;
always # (*) begin
F = 1'b0;
for(i = LOW; i <= HIGH; i = i + 1) begin: val_check
if(BCD == i[3:0]) F = 1'b1;
end
end

Related

operators precedence and associativity in C

i would be grateful if somebody could help me with this problem. The book I am currently reading has a question
Q What will be the output?
#include <stdio.h>
void main()
{
int a = 3, b = 2;
a = a ==b==0;
printf("%d, %d",a,b);
}
The answer is given as
1,2 ( even on codeblocks got the same answers)
Now i understand that equality operator has precedence over the assignment operator.
So it must be a== b or b == 0 first
Then as both the above have the same operator, The associativity rule causes
a == b to be evaluated first.
But from here on I am lost!
How does one get to 1 and 2 as the answer?
See https://en.cppreference.com/w/cpp/language/operator_precedence
Note the line that says, "Operators that have the same precedence are bound to their arguments in the direction of their associativity." You can see the associativity for each operator on the far right column.
Note that equality operator is on line 10, with associativity left-to-right.
Note that assignment is line 16, so it has lower precedence than equality.
// original
a = a == b == 0
// precedence rule
a = (a == b == 0)
// associativity rule
a = ((a == b) == 0)
I believe that the equality operator does does not have precedence over the assignment operator. C just works itself from left to right.
in
a = a == b == 0;
a is assigned to everything on the right of the equal sign.
On the right side of the equal sign, a == b is evaluated to false. Then we compare equality of the answer to a==b with 0. In c, 0 is equal to false, so we get true. This is our answer to "everything to the right of the equal sign". So then, we assign that value(true) to a, which is an integer. Because of automatic conversion, true is converted to 1 and assigned to a. Now a equals 1.
As an equation, the above process can be represented as: a = (( a == b ) == 0)
Hope this makes sense. Tell me if I need to clarify further.

Reduction meta-operator inconsistency

When we examine the reduce function:
my $result = reduce &reduction_procedure, #array;
we conclude with the following simple rules to the inner workings:
Reduction Rules
---------------
1. For the first pair of objects from our input (#array)
we apply the reduction procedure (&reduction_procedure) and we get our first result.
2. We apply the reduction procedure (&reduction_procedure) to the result (object)
of the previous rule and the next input (object) from our input (#array),
and we get an intermediate result (object).
3. We run rule.2 for every of the remaining objects from our input (#array)
This simple rules work also the same for the reduction metaoperator []. For example:
example.1
---------
say [+] [1,2,3,4]; # result : 10
For example.1 the reduction rules apply as is:
Step.1 use Rule.1 : 1 + 2 = 3 1(first value) + 2(second value) = 3
Step.2 use Rule.2 : 3 + 3 = 6 3(previous result) + 3(current value) = 6
Step.3 use Rule.2 : 6 + 4 = 10 6(previous result) + 4(current value) = 10
but NOT for the following example:
example.2
----------
say [<] 1,2,3,4; # result : True
For example.2 we observe an inconsistency:
Step.1 use Rule.1 : 1 < 2 = True 1(first value) < 2(second value) = True
Step.2 use Rule.2 : 2 < 3 = True True(previous result) && True(current result) = True
Step.3 use Rule.2 : 3 < 4 = True True(previous result) && True(current result) = True(result)
The inconsistency is that from Step.2 and onwards we can NOT use the result of the previous step as the first parameter of subsequent reduce operations,
but instead we calculate a logical intermediate result, with use of the actual values and finally we add as a final step the use of "logical AND" upon
the intermediate logical results of each step:
Reduction Result = True && True && True = True (use of logical AND as "meta-reduction" operator)
Sort of speak we have a "meta-reduction" metaoperator!
Questions:
1. Is that an inconsistency with a purpose?
2. Can we exploit this behavior? For instance instead of use of && (logical AND)
as "meta-reduction" operator can we use || (logical OR) or ?^ (logical XOR) ?
It is not an inconsistency but and example of how operator associativity works in Raku.
Writing :
[<] 1,2,3,4
Is the same as writing :
1 < 2 < 3 < 4
In most languages this wouldn't work but the < operator has chain associativity so it effectively treats this as :
(1 < 2) and (2 < 3) and (3 < 4)
Which is True.

What is the difference between == and <= in this case

I was working on making a game, and I was wondering why the construct with the == operator doesn't work while the lower one does. I used an NSLog message afterwards to test.
if (pipe.position.x == bird.position.x){ no idea why this doesn't work
if ((pipe.position.x <= bird.position.x) & (pipe.position.x > bird.position.x - 1)){
This is because one (or both) of the position.x's are a floating-point2 value with a non-zero difference1 between the two position values such that only the second condition is true.
Since p <= b is true for all values that make p == b true, to see why this works "unexpectedly" let's choose some values such that the expression p == b is false2 yet p < b is true and p > b - 1 is true.
Given p = 3.2 (pipe) and b = 3.7 (bird), as an example, then
p == b
-> 3.2 == 3.7
-> false
but
(p <= b) & (p > b - 1)
-> (3.2 <= 3.7) & (3.2 > 3.7 - 1)
-> (3.2 <= 3.7) & (3.2 > 2.7)
-> true & true
-> true
Instead, to detect when the bird "is crossing" the pipe, assuming that x increases to the right, consider
// The bird's head to the "right" of the pipe leading edge..
bird_x >= pipe_x
// ..but bird's butt is not to the "right" of the pipe trailing edge.
// (Also note use of the &&, the logical-AND operator)
&& (bird_x - bird_width <= pipe_x + pipe_width)
Of course, using a non-rectangle (or forgiving overlap) collision detection would lead to less frustrating flapping!
1 This issue occurs because there are some particular floating-point values (but there are no integer values) which can cause the observed effect.
First, reiterate the assumption that p is not equal to b, given that the first condition does not succeed. Let's suppose then that p <= b is written as p == b || p < b but since p == b is false , we can write it as p < b by tautology.
Since both clauses in the second condition are true (such that true && true -> true), we have the rules: 1) p < b is true, and 2) p > b - 1 is true.
Rewriting p < b as p - b < 0 and p > b - 1 as p - b > -1, and then replacing p - b with x yields: x < 0 and x > -1. However, there is no integer value of x which satisfies -1 < x < 0.
(In first section, where p = 3.2 and b = 3.7, x = (p - b) = 0.5 which satisfies the given constraints when x is not restricted to an integer value.)
2 With all above aside, it is possible for p and b to be "very close but different" floating-point values such that there is a non-zero difference between them - due to rounding, they may even be displayed as the same integer value! See How dangerous is it to compare floating point values? and related questions for the cause and "odd" behavior of such when using ==.
If this is the case then round to integer values and use an integer comparison, or; rely entirely on relational comparison such as shown in the proposed condition, or; use epsilon comparison for "nearly equal" of floating-point values.
if you choose abs(pipe.position.x) == abs(bird.position.x) the first condition may satisfy.

Looping until multiple conditions reached in Objective-C

So i am trying to create a program that can find a number that can be divided by numbers 1-20. I know that i will have to use the following simple code concepts:
I know how loops work and how to create a loop that runs until a condition is met. Is there a simple was to run a loop until several conditions are met?
while ( condition1 && condition2 && condition3... ) {}
or
for ( int i = 0; i < n && condition1 && condition2... ) {}
Obviously these will loop while the conditions are true, not until the conditions are met. Its a simple change in the logic though to get the result you want
EDIT
Ane example of the kind of loop youre looking for could be like:
int number = ...;//initialized somewhere, this is what we're checking
BOOL divisible = YES;
for ( int i = 1; i <= 20 && divisible; ++i )
{
if ( (number % i) != 0 )
divisible = NO;//not divisible by i
}
Good answers in play, but I think it's good to mention the break operator in this discussion. Any loop, at any time, can be terminated using this operator. This can be helpful if you do not know all of the parameters which might go out-of-bounds, and you want to have a way of breaking the loop for reasons you may not have explicitly anticipated (i.e. perhaps your connection to a resource is no longer available...)
NSError *error = nil;
while(true) {
// run your app
if(error) {
break;
}
}
If a number is divisible by all numbers from 1 to 20 then it is divisible by the LCM of 1 to 20 so divisibility test is if(!(n%232792560)).
Further if m = pq | n then p|n, q|n so to explicitly test you only need to check for divisibility by primes. i.e if the number is not even then there is no need to check for divisibility by 4, 6, 8, 10, 12, 14, 16, 18 or 20. This reduces the test to the number being congruent to the 8th primorial = 9699690
OK, perhaps on second reading not as explicit as I should like: the expanded test looks like (by de Morgan's theorem)
if(!(n%19 || n%17 || n%16 || n%13 || n%11 || n%9 || n%7 || n%5))
// number is divisible by 1..20

The while language

For my theory of computing languages class, we got a homework assignment to implement a piece of code in a language that only has while statements for flow control (no if statements). This is mainly to prove that you can write a Turing-complete language with only a while loop.
For those of you who can understand language grammars, here are the language rules:
S -> S;S | while C do S od | id := E
E -> E + T | T | E - T
T -> T * F | F | F / T
F -> id | cons | (E)
C -> E = E | E > E | E < E | E >= E | E <= E | E != E | C and C | C or C | not(C)
This is copied from my class notes, so don't blame me if something is missing or incorrect!
The piece of code to implement is this:
if d = 0 do
x := 1
else
x := a / d
At any rate, if you want to go ahead and write that using the language rules above, go ahead. Otherwise, go ahead and write it in whatever language you're most comfortable in. But there are a few caveats!
No if statements or any other kind of flow control other than while loops.
No cheating: the grammar above doesn't include any break statements, return statements, or exceptions. Don't use them.
I've got my piece of code written for this (which I'll post just to prove this isn't a show me teh codez post). I'm kinda curious what anyone else can come up with though.
It can be done with a single while loop, but it is not that clear:
while d == 0 do
d := 1;
a := 1
od
x := a / d;
Explanation, if d = 0, then d will be 1, also a will be 1. This ends the loop.
Now x is set to a / d which is fine, because if d was 0, a / d evaluates to 1.
Here's my code:
continue := True
while d = 0 and continue do
x := 1
continue := False
od
while d != 0 and continue do
x := a/d
continue := False
od
Would this work?
td := d
x := 1
while td != 0 do
x := a / d
td := 0
od
To be Turing Complete, you need to support both selection and iteration. While loops obviously iterate. Selection can be accomplished by making it go through the loop once if the condition is true, and not at all otherwise.
So worst case you can do everything you need to by applying those techniques. I'd imagine some complicated control flows would get ugly fast though. :-)
Without using details of the true or false branches, and without repeating the predicate:
statementIncomplete := True
while d = 0 and statementIncomplete do
x := 1
statementIncomplete := False
od
while statementIncomplete do
x := a/d
statementIncomplete := False
od
This is an expansion of Eamon's answer.
The semantics of if <condition> then <stmt> else <stmt> fi is the following:
evaluate <condition>;
if it was true, execute the statement between then and else;
otherwise, execute the statement between else and fi.
The semantics of while <condition> do <stmt> od is the following:
evaluate <condition>;
if false, the while statement is done executing;
otherwise, execute the statement between do and od, and execute the while statement again.
To express if A then B else C in terms of while, perform the following transformation:
Let gensymN be a name not used for any other variable; then emit the following code
gensymN := 0;
while gensymN = 0 and A do B; gensymN = 1; od;
while gensymN = 0 do C; gensymN = 1; od
The semantics of this program is:
Assign 0 to gensymN.
Evaluate gensymN = 0 and A (it's true iff A is true)
If true, then:
execute B
execute gensymN = 1
evaluate gensymN = 0 and A (it's false)
evaluate gensymN = 0 (it's false)
else (if gensymN = 0 and A was false):
evaluate gensymN = 0 (it's true)
execute C
execute gensymN := 1
evaluate gensymN = 0 (it's false)
Observe the following substructure of the above:
It (effectively) evaluates A;
If true, it executes B, otherwise C.
Apart from A, B and C, the program (fragment) only fiddles with gensymN, which is not present in the input program.
Hence this program has the same semantics as
if A then B else C fi; gensymN := 1
One footnote: if A is true when evaluated, it will be evaluated once again (unless and is short-circuiting). If the language allows storing booleans in variables, one can introduce one more dummy variable and do dummy := A; <insert the above program here, with dummy instead of A>. Then the two evaluations of dummy are essentially just a load. If evaluating boolean expressions cannot have side effects, preventing the second evaluation is not necessary for correctness; it may (or may not) be an optimization.
Take the above as a "soft proof", with the provisos of the preceding paragraph, that this is a correct fully general translation of if to while. The full generality sets this (= Eamon's) answer apart from the others, in my view.