What does "&&" do? - math

I can't seem to find the resource I need. What does && do in a code that is comparing variables to determine if they are true? If there is a link with a list of the symbol comparisons that would be greatly appreciated.
example: Expresssion 1: r = !z && (x % 2);

In most programming languages that use &&, it's the boolean "and" operator. For example, the pseudocode if (x && y) means "if x is true and y is true."
In the example you gave, it's not clear what language you're using, but
r = !z && (x % 2);
probably means this:
r = (not z) and (x mod 2)
= (z is not true) and (x mod 2 is true)
= (z is not true) and (x mod 2 is not zero)
= (z is not true) and (x is odd)

In most programming languages, the operator && is the logical AND operator. It connects to boolean expressions and returns true only when both sides are true.
Here is an example:
int var1 = 0;
int var2 = 1;
if (var1 == 0 && var2 == 0) {
// This won't get executed.
} else if (var1 == 0 && var2 == 1) {
// This piece will, however.
}
Although var1 == 0 evaluates to true, var2 is not equals to 0. Therefore, because we are using the && operator, the program won't go inside the first block.
Another operator you will see ofter is || representing the OR. It will evaluate true if at least one of the two statements are true. In the code example from above, using the OR operator would look like this:
int var1 = 0;
int var2 = 1;
if (var1 == 0 || var2 == 0) {
// This will get executed.
}
I hope you now understand what these do and how to use them!
PS: Some languages have the same functionality, but are using other keywords. Python, e.g. has the keyword and instead of &&.

It is the logical AND operator
(&&) returns the boolean value true if both operands are true and returns false otherwise.
boolean a=true;
boolean b=true;
if(a && b){
System.out.println("Both are true"); // Both condition are satisfied
}
Output
Both are true

The exact answer to your question depends on the which language your are coding in. In R, the & operator does the AND operation pairwise over two vectors, as in:
c(T,F,T,F) & c(T,T,F,F)
#> TRUE FALSE FALSE FALSE
whereas the && operator operated only on the first element of each vector, as in:
c(T,F,T,F) && c(T,T,F,F)
#> TRUE
The OR operators (| and ||) behave similarly. Different languages will have different meanings for these operators.

In C && works like a logical and, but it only operates on bool types which are true unless they are 0.
In contrast, & is a bitwise and, which returns the bits that are the same.
Ie. 1 && 2 and 1 && 3 are true.
But 1 & 2 is false and 1 & 3 is true.

Let's imagine the situation:
a = 1
b = 2
if a = 1 && b = 2
return "a is 1 and b is 2"
if a = 1 && b = 3
return "a is 1 and b is 3"
In this situation, because a equals 1 AND b = 2, the top if block would return true and "a is 1 and b is 2" would be printed. However, in the second if block, a = 1, but b does not equal 3, so because only one statement is true, the second result would not be printed. && Is the exact same as just saying and, "if a is 1 and b is 1".

Related

How to handle (x,1) base case for is_power(x,y) function, where x != 1?

Title says most of it. Here is a related thread, but I do not have enough reputation to comment.
Here is the prompt:
A number, a, is a power of b if it is divisible by b and a/b is a power of b. Write a function called is_power that takes parameters a and b and returns True if a is a power of b.
In the archived post, the most upvoted answer was to address the trivial base cases of (x,x) and (1,x). Then, determine if (a % b == 0) and then recursively call to find (a/b is a power of b).
Here is the code I've written in Julia:
function ispower(a,b)
if a == 0 && b != 0
return false
elseif a == b
return true
elseif a % b == 0 && ispower(a/b, b)
return true
else
return false
end
end
As I wrote in the comment if you multiply 1 by 1 you can only get 1, so the only number that is a power of 1 is 1 and no other number. Therefore, your function should return false for an input (x,1), whenever x is not 1.
Then you should also consider the case where b==0. Then the only number that is a power of b is 0.
So, I would write you function like this:
function ispower(a::Integer,b::Integer)
if (a==b)
return true
elseif (a==0 || b==0 || b==1)
return false
elseif (a % b) == 0
return ispower(div(a,b), b)
else
return false
end
end

What's the difference between & vs && and | vs || in R? [duplicate]

According to the R language definition, the difference between & and && (correspondingly | and ||) is that the former is vectorized while the latter is not.
According to the help text, I read the difference akin to the difference between an "And" and "AndAlso" (correspondingly "Or" and "OrElse")...
Meaning:
That not all evaluations if they don't have to be (i.e. A or B or C is always true if A is true, so stop evaluating if A is true)
Could someone shed light here?
Also, is there an AndAlso and OrElse in R?
The shorter ones are vectorized, meaning they can return a vector, like this:
((-2:2) >= 0) & ((-2:2) <= 0)
# [1] FALSE FALSE TRUE FALSE FALSE
The longer form evaluates left to right examining only the first element of each vector, so the above gives
((-2:2) >= 0) && ((-2:2) <= 0)
# [1] FALSE
As the help page says, this makes the longer form "appropriate for programming control-flow and [is] typically preferred in if clauses."
So you want to use the long forms only when you are certain the vectors are length one.
You should be absolutely certain your vectors are only length 1, such as in cases where they are functions that return only length 1 booleans. You want to use the short forms if the vectors are length possibly >1. So if you're not absolutely sure, you should either check first, or use the short form and then use all and any to reduce it to length one for use in control flow statements, like if.
The functions all and any are often used on the result of a vectorized comparison to see if all or any of the comparisons are true, respectively. The results from these functions are sure to be length 1 so they are appropriate for use in if clauses, while the results from the vectorized comparison are not. (Though those results would be appropriate for use in ifelse.
One final difference: the && and || only evaluate as many terms as they need to (which seems to be what is meant by short-circuiting). For example, here's a comparison using an undefined value a; if it didn't short-circuit, as & and | don't, it would give an error.
a
# Error: object 'a' not found
TRUE || a
# [1] TRUE
FALSE && a
# [1] FALSE
TRUE | a
# Error: object 'a' not found
FALSE & a
# Error: object 'a' not found
Finally, see section 8.2.17 in The R Inferno, titled "and and andand".
The answer about "short-circuiting" is potentially misleading, but has some truth (see below). In the R/S language, && and || only evaluate the first element in the first argument. All other elements in a vector or list are ignored regardless of the first ones value. Those operators are designed to work with the if (cond) {} else{} construction and to direct program control rather than construct new vectors.. The & and the | operators are designed to work on vectors, so they will be applied "in parallel", so to speak, along the length of the longest argument. Both vectors need to be evaluated before the comparisons are made. If the vectors are not the same length, then recycling of the shorter argument is performed.
When the arguments to && or || are evaluated, there is "short-circuiting" in that if any of the values in succession from left to right are determinative, then evaluations cease and the final value is returned.
> if( print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(FALSE && print(1) ) {print(2)} else {print(3)} # `print(1)` not evaluated
[1] 3
> if(TRUE && print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(TRUE && !print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 3
> if(FALSE && !print(1) ) {print(2)} else {print(3)}
[1] 3
The advantage of short-circuiting will only appear when the arguments take a long time to evaluate. That will typically occur when the arguments are functions that either process larger objects or have mathematical operations that are more complex.
Update: The most recent edition of news(“R”) says that supplying vectors of length greater than 1 to && or || is deprecated with a warning and the intent of RCore is to make it an error in a subsequent version of R.
&& and || are what is called "short circuiting". That means that they will not evaluate the second operand if the first operand is enough to determine the value of the expression.
For example if the first operand to && is false then there is no point in evaluating the second operand, since it can't change the value of the expression (false && true and false && false are both false). The same goes for || when the first operand is true.
You can read more about this here: http://en.wikipedia.org/wiki/Short-circuit_evaluation From the table on that page you can see that && is equivalent to AndAlso in VB.NET, which I assume you are referring to.
There are three relevant differences between the operators &&/|| and &/|, which are explained in the official documentation. Here’s a summary:
1. & and | are vectorised
This means that if you want to perform element-wise logical operations on vectors you should use & and |:
a = c(TRUE, TRUE, FALSE, FALSE)
b = c(TRUE, FALSE, TRUE, FALSE)
a | b
# [1] TRUE TRUE TRUE FALSE
a || b
# [1] TRUE
For &&/|| all elements after the first are discarded. Recent versions of R generate a helpful warning when using &&/|| on vectors longer than 1:
In a || b : 'length(x) = 4 > 1' in coercion to 'logical(1)'
2. && and || are short-circuited
Short-circuiting means that the right-hand side of the expression is only evaluated if the left-hand side does not already determine the outcome. Pretty much every programming language does this for conditional operations, since it leads to handy idioms when writing if conditions, e.g.:
if (length(x) > 0L && x[1L] == 42) …
This code relies on short-circuiting: without it, the code would fail if x is empty, since the right-hand side attempts to access a non-existent element. Without short-circuiting, we would have to use nested if blocks, leading to more verbose code:
if (length(x) > 0L) {
if (x[1L] == 42) …
}
As a general rule, inside a conditional expression (if, while) you should always use && and ||, even if short-circuiting isn’t required: it’s more idiomatic, and leads to more uniform code.
3. & and | can perform bitwise arithmetic
In many (most?) programming languages, & and | actually perform bitwise arithmetic instead of Boolean arithmetic. That is, for two integers a and b, a & b calculates the bitwise and, and a | b calculates the bitwise or. For Boolean values there’s no difference between bitwise and logical operations; but for arbitrary integers, the result differs. For instance, 1 | 2 == 3 in most programming languages.
However, this is not true for R: R coerces numeric arguments of & and | to logical values and performs Boolean arithmetic.
… except when both arguments are of type raw:
c(1, 3) | c(2, 4)
# [1] TRUE TRUE
as.raw(c(1, 3)) | as.raw(c(2, 4))
# [1] 03 07
It is worth noting that the operations ! (logical negation) and xor also perform bitwise arithmetic when called with raw arguments.

Simplifying the boolean expression (A && B) || (A && !B && C)

I'm so confused currently while trying to simplify a boolean expression. I know the solution but not the correct way to achieve it.
What law makes (A && B) || (A && !B && C) the same as (A && B) || (A && C)
Why can i leave the !B?
Since (in simplified notation):
B+B'C = B+B+B'C = B(C+C')+B(C'+C)+B'C = BC+BC'+BC'+BC+B'C = BC+BC'+BC'+(B+B')C = BC+BC'+1C = B(C+C')+C = B+C
we have
AB + AB'C = A (B + B'C) = A(B+C) = AB + AC
I don't know of any law, but I will try to explain it.
For us to reach the check of !B we must acknowledge two things:
A must be TRUE
B must be FALSE
If A is false we can short-circuit out of both checks (A && B) and (A && !B && C) because A is evaluated first and we are only comparing with &&.
If A is true and B is true, the second condition is not evaluated.
Therefore, to reach !B, A must be true and B must be false as stated above. If that's the case then !B will always evaluate to TRUE in the second condition, and can be removed.

if else statement concatenation - R

This is a very common question: 1, 2, 3, 4, 5, and still I cannot find even an answer to my problem.
If a == 1, then do X.
If a == 0, then do Y.
If a == 0 and b == 1, then do Z.
Just to explain: the if else statements has to do Y if a==0 no matter the value of b. But if b == 1 and a == 0, Z will do additional changes to those already done by Y.
My current code and its error:
if (a == 1){
X
} else if(a == 0){
Y
} else if (a == 0 & b == 1){
Z}
Error in !criterion : invalid argument type
An else only happens if a previous if hasn't happened.
When you say
But if b == 1 and a == 0, Z will do additional changes to those already done by Y
Then you have two options:
## Option 1: nest Z inside Y
if (a == 1){
X
} else if(a == 0){
Y
if (b == 1){
Z
}
}
## Option 2: just use `if` again (not `else if`):
if (a == 1) {
X
} else if(a == 0) {
Y
}
if (a == 0 & b == 1) {
Z
}
Really, you don't need any else here at all.
## This will work just as well
## (assuming that `X` can't change the value of a from 1 to 0
if (a == 1) {
X
}
if (a == 0) {
Y
if (b == 1){
Z
}
}
Typically else is needed when you want to have a "final" action that is done only if none of the previous if options were used, for example:
# try to guess my number between 1 and 10
if (your_guess == 8) {
print("Congratulations, you guessed my number!")
} else if (your_guess == 7 | your_guess = 9) {
print("Close, but not quite")
} else {
print("Wrong. Not even close!")
}
In the above, else is useful because I don't want to have enumerate all the other possible guesses (or even bad inputs) that a user might enter. If they guess 8, they win. If they guess 7 or 9, I tell them they were close. Anything else, no matter what it is, I just say "wrong".
Note: this is true for programming languages in general. It is not unique to R.
However, since this is in the R tag, I should mention that R has if{}else{} and ifelse(), and they are different.
if{} (and optionally else{}) evaluates a single condition, and you can run code to do anything in {} depending on that condition.
ifelse() is a vectorized function, it's arguments are test, yes, no. The test evaluates to a boolean vector of TRUE and FALSE values. The yes and no arguments must be vectors of the same length as test. The result will be a vector of the same length as test, with the corresponding values of yes (when test is TRUE) and no (when test is FALSE).
I believe you want to include Z in the second condition like this:
if (a == 1){X}
else if(a == 0){
Y
if (b == 1){Z}
}

Merge conditions in if statement

I have two conditions for if statement. I found that those are different, but I don't know the reason.
1: if ((local != -1) || (fall_back == 1))
2. if ((local != -1) || ((local != -1) && (fall_back == 1)))
Those two are different. But in Math, we have A V (B ^ C) = (A V B) ^ (A V C). If I use this equation and reorganize statement 2, it seems to be the same as 1. Is there anything fundamental I am missing?
How can I simplify statement 2? It doesn't look good.
Short circuit evaluation is done in order to optimize.
So in an expression like (A!=B) || (A!=C), if A!=B turns out to be true the second part A!=C is not evaluated at all, because independent of the second part, the expression will turn out to be true.
Consider
A -> local != -1
B -> fall_back == 1
Your first condition reduces to
A V B
And second statement reduces to
A V (A ^ B) => A ^ (1 V B) => A
So your first statement requires either condition A or B to be true
And second statement tests only if A is true
Consider test case where local = 0 and fall_back = 1
Statement 1 => True as fall_back == 1
Statement 2 => False as local != 0
Hence conditions are not the same
This is Simple, If you Take local != -1 = true and fall_back == 1 = false
Then in Both case result will be true because the value of local != -1 = true
but if take local != -1 = false and fall_back == 1 = true
then in first case result will be true and in second case result will be false.
In Logical OR if the first condition is true means it wont evaluate the second one! But in Logical AND first condition false means it wont evaluate the second one!
if ((local != -1) || (fall_back == 1))
In this if any one of the condition is true, local != -1 or fall_back == 1 it will evaluate the body of the if.
if ((local != -1) || ((local != -1) && (fall_back == 1)))
But here both should be true, Then only it will evaluate the expression. else local != -1 fails means, Both conditions will fails. Because Logical AND(&&) both should be true!
Consider- local != -1 is false and fall_back == 1 is true
if ( false || true ) -> if(0 || 1) -->true
if ( false || (false && true)) -> if(0 || (0 && 1)) -> if(0 || 0) --> false

Resources