Boolean logic Multiple choice ques - boolean

Q. Which of the following boolean expressions will evaluate to true if x is between lower and upper, inclusive, and false otherwise.
1: (x<=lower) || (x>=upper)
2: (x>=lower) || (x<=upper)
3: lower <= x <= upper
4: (x>=lower) && (x<=upper)
5: u(x<=lower) && (x>=upper)
What is the answer to this question and why? Can someone briefly explain?

The correct one is #4, why?
You can discard 1 and 2 because you need them to be between those values, so it must be over or equal to lower AND below or equal upper.
-#5 is contradictory to your statement, because it looks for values that are not in the range of lower and upper inclusive, regardless that, it might be impossible to hit, because its stating that upper should be less than lower.
It can be #3 if you are giving a mathematical expression of it, but for programming syntax you will most likely find it as #4 format.
And with the condition of being inclusive, that means that your limits are inside your range.

Related

How to determine an Overflow in a 4 bit ripple-carry adder-substractor?

What function that depends by following variablesc (First Operand's sign[0/1], Second Operand's sign[0/1], Result's sign[0/1] and Operation sign[0/1]) can identify an overflow in the 4-bit ripple-carry adder/substractor?
P.S.
An overflow occurs only if:
the sum of two positive numbers yields a negative result, the sum has overflowed.
the sum of two negative numbers yields a positive result, the sum has overflowed.
I only know the method with checking the 2 last carries but it seems that there's another method.
Your PS already contains the correct logic formula written in prose (for addition). Remember that a number is "positive" if its sign bit is zero and the number is negative if its sign bit is one.1 This means you can translate "yields a negative result" to "the operation sign is 1". You can translate the other statements about operands or results to logic conditions in the same way, to finally derive a general boolean formula.
1: I know that zero is neither positive nor negative, but treating zero as positive does no harm in this case.

How to "absolute-ly" take from a number? (How to offset a number?)

Essentially what I need to do is a - b, but I don't know what either will be and if a is positive then how can I take b from a in a "absolute" way?
What I mean is for example A = 10 and B = 5. Answer is obviously 5. If A was now -10, the answer is now -5. The answer leans towards 0 no matter what the numbers are. I heavily want to avoid using an if statement if I can.
My original idea was a - (b * (b / abs(b))). But b can be 0, and then div by 0 error occurs.
EDIT: A better way of saying it is I want to offset the result by an amount instead of math.
So do I understand correctly that whatever the value of A, you want it to bias towards zero (based on the initial value of A) by the value of B?
So given:
A=10 and B=5, the result will be 5.
A=-10 and B=5, the result will be -5.
A=-5 and B=-10, the result will be 5 (because it is offset by 10, towards zero from a starting point of -5).
Effectively the sign of B is immaterial because it specifies an offset towards zero in all cases.
What of the case where A=0 and B is non-zero? Is the result supposed to be undefined (because the appropriate direction of offset cannot be inferred), or is it supposed to be zero?
The formula for the latter case would be (ABS(A) - ABS(B)) * SIGN(A)) (assuming that the sign function returns 0 when A is zero).

Simplifying a 9 variable boolean expression

I am trying to create a tic-tac-toe program as a mental exercise and I have the board states stored as booleans like so:
http://i.imgur.com/xBiuoAO.png
I would like to simplify this boolean expression...
(a&b&c) | (d&e&f) | (g&h&i) | (a&d&g) | (b&e&h) | (c&f&i) | (a&e&i) | (g&e&c)
My first thoughts were to use a Karnaugh Map but there were no solvers online that supported 9 variables.
and heres the question:
First of all, how would I know if a boolean condition is already as simple as possible?
and second: What is the above boolean condition simplified?
2. Simplified condition:
The original expression
a&b&c|d&e&f|g&h&i|a&d&g|b&e&h|c&f&i|a&e&i|g&e&c
can be simplified to the following, knowing that & is more prioritary than |
e&(d&f|b&h|a&i|g&c)|a&(b&c|d&g)|i&(g&h|c&f)
which is 4 chars shorter, performs in the worst case 18 & and | evaluations (the original one counted 23)
There is no shorter boolean formula (see point below). If you switch to matrices, maybe you can find another solution.
1. Making sure we got the smallest formula
Normally, it is very hard to find the smallest formula. See this recent paper if you are more interested. But in our case, there is a simple proof.
We will reason about a formula being the smallest with respect to the formula size, where for a variable a, size(a)=1, for a boolean operation size(A&B) = size(A|B) = size(A) + 1 + size(B), and for negation size(!A) = size(A) (thus we can suppose that we have Negation Normal Form at no cost).
With respect to that size, our formula has size 37.
The proof that you cannot do better consists in first remarking that there are 8 rows to check, and that there is always a pair of letter distinguishing 2 different rows. Since we can regroup these 8 checks in no less than 3 conjuncts with the remaining variable, the number of variables in the final formula should be at least 8*2+3 = 19, from which we can deduce the minimal tree size.
Detailed proof
Let us suppose that a given formula F is the smallest and in NNF format.
F cannot contain negated variables like !a. For that, remark that F should be monotonic, that is, if it returns "true" (there is a winning row), then changing one of the variables from false to true should not change that result. According to Wikipedia, F can be written without negation. Even better, we can prove that we can remove the negation. Following this answer, we could convert back and from DNF format, removing negated variables in the middle or replacing them by true.
F cannot contain a sub-tree like a disjunction of two variables a|b.
For this formula to be useful and not exchangeable with either a or b, it would mean that there are contradicting assignments such that for example
F[a|b] = true and F[a] = false, therefore that a = false and b = true because of monotonicity. Also, in this case, turning b to false makes the whole formula false because false = F[a] = F[a|false] >= F[a|b](b = false).
Therefore there is a row passing by b which is the cause of the truth, and it cannot go through a, hence for example e = true and h = true.
And the checking of this row passes by the expression a|b for testing b. However, it means that with a,e,h being true and all other set to false, F is still true, which contradicts the purpose of the formula.
Every subtree looking like a&b checks a unique row. So the last letter should appear just above the corresponding disjunction (a&b|...)&{c somewhere for sure here}, or this leaf is useless and either a or b can be removed safely. Indeed, suppose that c does not appear above, and the game is where a&b&c is true and all other variables are false. Then the expression where c is supposed to be above returns false, so a&b will be always useless. So there is a shorter expression by removing a&b.
There are 8 independent branches, so there is at least 8 subtrees of type a&b. We cannot regroup them using a disjunction of 2 conjunctions since a, f and h never share the same rows, so there must be 3 outer variables. 8*2+3 makes 19 variables appear in the final formula.
A tree with 19 variables cannot have less than 18 operators, so in total the size have to be at least 19+18 = 37.
You can have variants of the above formula.
QED.
One option is doing the Karnaugh map manually. Since you have 9 variables, that makes for a 2^4 by 2^5 grid, which is rather large, and by the looks of the equation, probably not very interesting either.
By inspection, it doesn't look like a Karnaugh map will give you any useful information (Karnaugh maps basically reduce expressions such as ((!a)&b) | (a&b) into b), so in that sense of simplification, your expression is already as simple as it can get. But if you want to reduce the number of computations, you can factor out a few variables using the distributivity of the AND operators over ORs.
The best way to think of this is how a person would think of it. No person would say to themselves, "a and b and c, or if d and e and f," etc. They would say "Any three in a row, horizontally, vertically, or diagonally."
Also, instead of doing eight checks (3 rows, 3 columns, and 2 diagonals), you can do just four checks (three rows and one diagonal), then rotate the board 90 degrees, then do the same checks again.
Here's what you end up with. These functions all assume that the board is a three-by-three matrix of booleans, where true represents a winning symbol, and false represents a not-winning symbol.
def win?(board)
winning_row_or_diagonal?(board) ||
winning_row_or_diagonal?(rotate_90(board))
end
def winning_row_or_diagonal?(board)
winning_row?(board) || winning_diagonal?(board)
end
def winning_row?(board)
3.times.any? do |row_number|
three_in_a_row?(board, row_number, 0, 1, 0)
end
end
def winning_diagonal?(board)
three_in_a_row?(board, 0, 0, 1, 1)
end
def three_in_a_row?(board, x, y, delta_x, delta_y)
3.times.all? do |i|
board[x + i * delta_x][y + i * deltay]
end
end
def rotate_90(board)
board.transpose.map(&:reverse)
end
The matrix rotate is from here: https://stackoverflow.com/a/3571501/238886
Although this code is quite a bit more verbose, each function is clear in its intent. Rather than a long boolean expresion, the code now expresses the rules of tic-tac-toe.
You know it's a simple as possible when there are no common sub-terms to extract (e.g. if you had "a&b" in two different trios).
You know your tic tac toe solution must already be as simple as possible because any pair of boxes can belong to at most only one winning line (only one straight line can pass through two given points), so (a & b) can't be reused in any other win you're checking for.
(Also, "simple" can mean a lot of things; specifying what you mean may help you answer your own question. )

how to threshold/filter a vector? [duplicate]

This question already has an answer here:
Operands to the || and && operators must be convertible to logical scalar values
(1 answer)
Closed 9 years ago.
I have a vector containing a list of data (X and Y coords) which i want to compare to an array of 100 vectors (each with similar but not the same XY Coords) in order to find a match.
Each vector ranges in data size (between 10 and 20 cords) which causes issues when matching matrices of different sizes.
so in order to match i have used the matchfeatures which matches exact data which is no use as vectors different sizes.
so i made
(using pdist to turn cords into distances)
threshigh = (vector1/100) * 110;
threslow = (vector1/100) * 90;
if (Vector2 <= threshigh)&&(vector2 >= threslow)
disp its a match
else
not a match
end
this is perfect! but.. I cannot use operators on vectors as they only apply to scalar quantities.
how do i get around this?
it has also occurred to me even if this works and some values in the vector fall between this range it will not match unless they all do? how do i just take majority of results?
The link of the duplicate question should solve your first problem. As for your second issue:
... even if this works and some values in the vector fall between this range it will not match unless they all do? how do i just take majority of results?
Once you have a logical array (with 1's at the positions corresponding to elements that fall within the specified range, and 0's elsewhere), you can manipulate it to your liking.
In its current form, the if statement branches only if all elements are true (logical '1'). If you know that the tested expression might be a vector (that is, an array), you can do the following:
Use the any command to check if at least one element in the array is true:
if any(...)
%// Do something...
end
Use the all command to check if all elements are true:
if all(...)
%// Do something...
end
(using all here is superfluous, but it does enhance readability...)
Check for a majority of '1's by using mode:
if mode(double(...))
%// Do something...
end
mode returns the most frequent element in the array, so if it's '1' the if statement will branch.

Test if a floating point number is an integer in Matlab

My Question - part 1: What is the best way to test if a floating point number is an "integer" (in Matlab)?
My current solution for part 1: Obviously, isinteger is out, since this tests the type of an element, rather than the value, so currently, I solve the problem like this:
abs(round(X) - X) <= sqrt(eps(X))
But perhaps there is a more native Matlab method?
My Question - part 2: If my current solution really is the best way, then I was wondering if there is a general tolerance that is recommended? As you can see from above, I use sqrt(eps(X)), but I don't really have any good reason for this. Perhaps I should just use eps(X), or maybe 5 * eps(X)? Any suggestions would be most welcome.
An Example: In Matlab, sqrt(2)^2 == 2 returns False. But in practice, we might want that logical condition to return True. One can achieve this using the method described above, since sqrt(2)^2 actually equals 2 + eps(2) (ie well within the tolerance of sqrt(eps(2)). But does this mean I should always use eps(X) as my tolerance, or is there good reason to use a larger tolerance, such as 5 * eps(X), or sqrt(eps(X))?
UPDATE (2012-10-31): #FakeDIY pointed out that my question is partially a duplicate of this SO question (apologies, not sure how I missed it in my initial search). Given this I'd like to emphasize the "tolerance" part of the question (which is not covered in that link), ie is eps(X) a sensible tolerance, or should I use something larger, like 5 * eps(X), and if so, why?
UPDATE (2012-11-01): Thanks everyone for the responses. I've +1'ed all three answers as I feel they all contribute meaningfully to various aspects of the question. I'm giving the answer tick to Eric Postpischil as that answer really nailed the tolerance part of the question well (and it has the most upvotes at this point in time).
No, there is no general tolerance that is recommended, and there cannot be.
The difference between a computed result and a mathematically ideal result is a function of the operations that produced the computed result. Because those operations are specific to each application, there is no general rule for testing any property of a computed result.
To design a proper test, you must determine what errors may have occurred during computation, determine bounds on the resulting error in the computed result, and test whether the computed result differs from the ideal result (perhaps the nearest integer) by less than those bounds. You must also decide whether those bounds are sufficiently small to satisfy your application’s requirements. (Using a relaxed test that accepts as an integer something that is not an integer decreases false negatives [incorrect rejections of a result as an integer where the ideal result would be an integer] but increases false positives [incorrect acceptances of a result as an integer where the ideal result would not be an integer].)
(Note that it can even be the case the testing as if the error bounds were zero can produce false negatives: It is possible a computation produces a result that is exactly an integer when the ideal result is not an integer, so any error tolerance, even zero, will falsely report this result is an integer. If this is unacceptable for your application, then, in such a case, the computations must be redesigned.)
It is not only not possible to state, without specific knowledge of the application, a numerical tolerance that may be used, it is impossible to state whether the tolerance should be absolute, should be relative to the computed value or to a target value, should be measured in ULPs (units of least precision), or should be set in some other manner. This is because errors may be introduced into computations in a variety of ways. For example, if there is a small relative error in a and a and b are close in value, then a-b has a large relative error. Additionally, if c is large, then (a-b)*c has a large absolute error.
Its probably not the most efficient method but I would use mod for this:
a = 15.0000000000;
b = mod(a,1.0)
c = 15.0000000001;
d = mod(c,1.0)
returns b = 0 and d = 1.0000e-010
There are a number of other alternatives suggested here:
How do I test for integers in MATLAB?
I like the idea of comparing (x == floor(x)) too.
1) I have historically used your method with a simple tolerance, eps(X). The mod methods interested me though, so I benchmarked a couple using Steve Eddins timeit function.
f = #() abs(X - round(X)) <= eps(X);
g = #() X == round(X);
h = #() ~mod(X,1);
For single values, like X=1.0, yours appears to fastest:
timeit(f) = 7.3635e-006
timeit(g) = 9.9677e-006
timeit(h) = 9.9214e-006
For vectors though, like X = 1:0.01:100, the other methods are faster (though round still beats mod):
timeit(f) = 0.00076636
timeit(g) = 0.00028182
timeit(h) = 0.00040539
2) The error bound is really problem dependent. Other answers cover this much better than I am able to.