Can you set x == y equal to a Boolean in any any programming languages where x and y are of the same primitive type? - boolean

This may be an odd question, and generally I would just go test it, but I'm not near a computer with any IDEs, but can you set a Boolean equal to the expression x==y? The only reason I ask this is because in an if statement you can say... if(x==y) which is asking if the two are equal then do.... And if that is true then the statement x == y is evaluating to true can you set a variable to it

Yes you can, in Java you can do:
boolean z = (x==y);

Related

How to convert numbers into boolean in Julia?

I want to convert numbers into equivalent boolean. based on the official doc:
"false is numerically equal to 0 and true is numerically equal to 1."
So I would like to convert the numeric values to the equivalent boolean. Example of expected behavior:
[1] Bool(5)
> true
But, Julia gives me:
ERROR: InexactError: Bool(5)
Stacktrace:
[1] Bool(x::Int64)
# Base .\float.jl:158
[2] top-level scope
# REPL[26]:1
But if I say:
[1] Bool(0.0)
# result
> false
It looks good on 0 and 0.0! But it doesn't work on numbers like 5 or 2.1, etc.
The quick answer is that it seems like you want to test whether a value is non-zero or not and you can test if a number x is non-zero like this: x != 0. Whether a number is considered true or false depends on what language you're in, however; more on that below.
Having gotten the quick answer out of the way, we can talk about why. The docs say that false and true are numerically equal to zero and one. We can test this out ourselves:
julia> false == 0
true
julia> true == 1.0
true
You can see that the equality holds regardless of numerical type—integers or floats or even more esoteric number types like complexes or rationals. We can also convert booleans to other types of numbers:
julia> Int(false)
0
julia> Float64(true)
1.0
We can convert those values back to booleans:
julia> Bool(0)
false
julia> Bool(1.0)
true
What you can't do is convert a number that isn't equal to zero or one to boolean:
julia> Bool(5)
ERROR: InexactError: Bool(5)
That is because the Bool type can only represent the values zero and one exactly and trying to convert any other numeric value to Bool will give an InexactError. This is the same error you get if you try to convert a float that isn't integer-valued to an integer type:
julia> Int(5.0)
5
julia> Int(5.5)
ERROR: InexactError: Int64(5.5)
Or an integer to a smaller type that isn't big enough to represent that value:
julia> Int8(123)
123
julia> Int8(1234)
ERROR: InexactError: trunc(Int8, 1234)
The exact same thing is happening here: Bool is not big enough to represent the value 5, so you get an error if you try to convert the value 5 to Bool.
The convention that many languages use for truthiness of numbers is that values that represent zero are falsey and values that represent no-zeros are truthy. Note that there is no sound mathematical reason for this: zero is not false and non-zero numbers are not true; it's just a convention that comes from the C programming language, which doesn't have a boolean type and uses this convention for treating integers as true/false in conditionals. This convention is far from universal, however, as there are popular languages that don't follow it: in Lisps and Ruby, for example, all numbers are truthy. I wrote a post recently on the Julia discourse forum about differing notions of truthiness in different languages and why Julia rejects truthiness and instead requires you to write out an explicit condition like comparison with zero for numbers, or non-emptiness for collections.
Since the condition you actually want to check is whether a number is equal to zero or not, that's just what you should do: explicitly compare the number to zero by doing x != 0. This will evaluate to a boolean value: true if x is non-zero and false if x is equal to zero. There's a predicate function that does this as well: iszero(x) checks if x is zero, which can be handy if you want to e.g. count how many zero or non-zero values there are in a collection:
julia> v = rand(-2:2, 100);
julia> count(iszero, v)
18
julia> count(!iszero, v)
82

Does mathjs have any concept of null or undefined?

I think the answer is probably 'no' as from what I can tell maths libraries don't seem to handle null, but what I'd like to have is to be handle null in these scenarios:
x=1
(y not defined)
z = sum(x, y)
with eval() ideally giving:
z=1
However, this throws an exception, as y is not defined.
In effect I'm defaulting 'y' to zero in that example, and that won't work in all scenarios.
So, what I suppose I'm asking is, is there an in-built way to define a default for a variable if it's not assigned a value?
If not, I'm assuming that this would be possible by writing a custom function. If someone could confirm this, I'd really appreciate it.
Thanks :-).
Ok - I was looking through the release notes for v4 and saw it talking about the constants 'null, undefined' (and others). So, in order to solve this I have to define a variable as undefined (probably should have known this!).
(Note: I suspect these constants are available in previous version too.)
Then combined with a 'default' custom function I can get what I wanted:
x=1
y = null
z = sum(x, def(y, 0))
z=1
where 'def' is defined and imported as below (making use of 'lodash'):
var customFunctions = {
def: function (value, defaultValue) {
return !_.isNil(value) ? value : defaultValue;
}
};
math.import(customFunctions);
BOSH!

Turn off Warning: Extension: Conversion from LOGICAL(4) to INTEGER(4) at (1) for gfortran?

I am intentionally casting an array of boolean values to integers but I get this warning:
Warning: Extension: Conversion from LOGICAL(4) to INTEGER(4) at (1)
which I don't want. Can I either
(1) Turn off that warning in the Makefile?
or (more favorably)
(2) Explicitly make this cast in the code so that the compiler doesn't need to worry?
The code will looking something like this:
A = (B.eq.0)
where A and B are both size (n,1) integer arrays. B will be filled with integers ranging from 0 to 3. I need to use this type of command again later with something like A = (B.eq.1) and I need A to be an integer array where it is 1 if and only if B is the requested integer, otherwise it should be 0. These should act as boolean values (1 for .true., 0 for .false.), but I am going to be using them in matrix operations and summations where they will be converted to floating point values (when necessary) for division, so logical values are not optimal in this circumstance.
Specifically, I am looking for the fastest, most vectorized version of this command. It is easy to write a wrapper for testing elements, but I want this to be a vectorized operation for efficiency.
I am currently compiling with gfortran, but would like whatever methods are used to also work in ifort as I will be compiling with intel compilers down the road.
update:
Both merge and where work perfectly for the example in question. I will look into performance metrics on these and select the best for vectorization. I am also interested in how this will work with matrices, not just arrays, but that was not my original question so I will post a new one unless someone wants to expand their answer to how this might be adapted for matrices.
I have not found a compiler option to solve (1).
However, the type conversion is pretty simple. The documentation for gfortran specifies that .true. is mapped to 1, and false to 0.
Note that the conversion is not specified by the standard, and different values could be used by other compilers. Specifically, you should not depend on the exact values.
A simple merge will do the trick for scalars and arrays:
program test
integer :: int_sca, int_vec(3)
logical :: log_sca, log_vec(3)
log_sca = .true.
log_vec = [ .true., .false., .true. ]
int_sca = merge( 1, 0, log_sca )
int_vec = merge( 1, 0, log_vec )
print *, int_sca
print *, int_vec
end program
To address your updated question, this is trivial to do with merge:
A = merge(1, 0, B == 0)
This can be performed on scalars and arrays of arbitrary dimensions. For the latter, this can easily be vectorized be the compiler. You should consult the manual of your compiler for that, though.
The where statement in Casey's answer can be extended in the same way.
Since you convert them to floats later on, why not assign them as floats right away? Assuming that A is real, this could look like:
A = merge(1., 0., B == 0)
Another method to compliment #AlexanderVogt is to use the where construct.
program test
implicit none
integer :: int_vec(5)
logical :: log_vec(5)
log_vec = [ .true., .true., .false., .true., .false. ]
where (log_vec)
int_vec = 1
elsewhere
int_vec = 0
end where
print *, log_vec
print *, int_vec
end program test
This will assign 1 to the elements of int_vec that correspond to true elements of log_vec and 0 to the others.
The where construct will work for any rank array.
For this particular example you could avoid the logical all together:
A=1-(3-B)/3
Of course not so good for readability, but it might be ok performance-wise.
Edit, running performance tests this is 2-3 x faster than the where construct, and of course absolutely standards conforming. In fact you can throw in an absolute value and generalize as:
integer,parameter :: h=huge(1)
A=1-(h-abs(B))/h
and still beat the where loop.

How do I determine if *exactly* one boolean is true, without type conversion?

Given an arbitrary list of booleans, what is the most elegant way of determining that exactly one of them is true?
The most obvious hack is type conversion: converting them to 0 for false and 1 for true and then summing them, and returning sum == 1.
I'd like to know if there is a way to do this without converting them to ints, actually using boolean logic.
(This seems like it should be trivial, idk, long week)
Edit: In case it wasn't obvious, this is more of a code-golf / theoretical question. I'm not fussed about using type conversion / int addition in PROD code, I'm just interested if there is way of doing it without that.
Edit2: Sorry folks it's a long week and I'm not explaining myself well. Let me try this:
In boolean logic, ANDing a collection of booleans is true if all of the booleans are true, ORing the collection is true if least one of them is true. Is there a logical construct that will be true if exactly one boolean is true? XOR is this for a collection of two booleans for example, but any more than that and it falls over.
You can actually accomplish this using only boolean logic, although there's perhaps no practical value of that in your example. The boolean version is much more involved than simply counting the number of true values.
Anyway, for the sake of satisfying intellectual curiosity, here goes. First, the idea of using a series of XORs is good, but it only gets us half way. For any two variables x and y,
x ⊻ y
is true whenever exactly one of them is true. However, this does not continue to be true if you add a third variable z,
x ⊻ y ⊻ z
The first part, x ⊻ y, is still true if exactly one of x and y is true. If either x or y is true, then z needs to be false for the whole expression to be true, which is what we want. But consider what happens if both x and y are true. Then x ⊻ y is false, yet the whole expression can become true if z is true as well. So either one variable or all three must be true. In general, if you have a statement that is a chain of XORs, it will be true if an uneven number of variables are true.
Since one is an uneven number, this might prove useful. Of course, checking for an uneven number of truths is not enough. We additionally need to ensure that no more than one variable is true. This can be done in a pairwise fashion by taking all pairs of two variables and checking that they are not both true. Taken together these two conditions ensure that exactly one if the variables are true.
Below is a small Python script to illustrate the approach.
from itertools import product
print("x|y|z|only_one_is_true")
print("======================")
for x, y, z in product([True, False], repeat=3):
uneven_number_is_true = x ^ y ^ z
max_one_is_true = (not (x and y)) and (not (x and z)) and (not (y and z))
only_one_is_true = uneven_number_is_true and max_one_is_true
print(int(x), int(y), int(z), only_one_is_true)
And here's the output.
x|y|z|only_one_is_true
======================
1 1 1 False
1 1 0 False
1 0 1 False
1 0 0 True
0 1 1 False
0 1 0 True
0 0 1 True
0 0 0 False
Sure, you could do something like this (pseudocode, since you didn't mention language):
found = false;
alreadyFound = false;
for (boolean in booleans):
if (boolean):
found = true;
if (alreadyFound):
found = false;
break;
else:
alreadyFound = true;
return found;
After your clarification, here it is with no integers.
bool IsExactlyOneBooleanTrue( bool *boolAry, int size )
{
bool areAnyTrue = false;
bool areTwoTrue = false;
for(int i = 0; (!areTwoTrue) && (i < size); i++) {
areTwoTrue = (areAnyTrue && boolAry[i]);
areAnyTrue |= boolAry[i];
}
return ((areAnyTrue) && (!areTwoTrue));
}
No-one mentioned that this "operation" we're looking for is shortcut-able similarly to boolean AND and OR in most languages. Here's an implementation in Java:
public static boolean exactlyOneOf(boolean... inputs) {
boolean foundAtLeastOne = false;
for (boolean bool : inputs) {
if (bool) {
if (foundAtLeastOne) {
// found a second one that's also true, shortcut like && and ||
return false;
}
foundAtLeastOne = true;
}
}
// we're happy if we found one, but if none found that's less than one
return foundAtLeastOne;
}
With plain boolean logic, it may not be possible to achieve what you want. Because what you are asking for is a truth evaluation not just based on the truth values but also on additional information(count in this case). But boolean evaluation is binary logic, it cannot depend on anything else but on the operands themselves. And there is no way to reverse engineer to find the operands given a truth value because there can be four possible combinations of operands but only two results. Given a false, can you tell if it is because of F ^ F or T ^ T in your case, so that the next evaluation can be determined based on that?.
booleanList.Where(y => y).Count() == 1;
Due to the large number of reads by now, here comes a quick clean up and additional information.
Option 1:
Ask if only the first variable is true, or only the second one, ..., or only the n-th variable.
x1 & !x2 & ... & !xn |
!x1 & x2 & ... & !xn |
...
!x1 & !x2 & ... & xn
This approach scales in O(n^2), the evaluation stops after the first positive match is found. Hence, preferred if it is likely that there is a positive match.
Option 2:
Ask if there is at least one variable true in total. Additionally check every pair to contain at most one true variable (Anders Johannsen's answer)
(x1 | x2 | ... | xn) &
(!x1 | !x2) &
...
(!x1 | !xn) &
(!x2 | !x3) &
...
(!x2 | !xn) &
...
This option also scales in O(n^2) due to the number of possible pairs. Lazy evaluation stops the formula after the first counter example. Hence, it is preferred if its likely there is a negative match.
(Option 3):
This option involves a subtraction and is thus no valid answer for the restricted setting. Nevertheless, it argues how looping the values might not be the most beneficial solution in an unrestricted stetting.
Treat x1 ... xn as a binary number x. Subtract one, then AND the results. The output is zero <=> x1 ... xn contains at most one true value. (the old "check power of two" algorithm)
x 00010000
x-1 00001111
AND 00000000
If the bits are already stored in such a bitboard, this might be beneficial over looping. Though, keep in mind this kills the readability and is limited by the available board length.
A last note to raise awareness: by now there exists a stack exchange called computer science which is exactly intended for this type of algorithmic questions
It can be done quite nicely with recursion, e.g. in Haskell
-- there isn't exactly one true element in the empty list
oneTrue [] = False
-- if the list starts with False, discard it
oneTrue (False : xs) = oneTrue xs
-- if the list starts with True, all other elements must be False
oneTrue (True : xs) = not (or xs)
// Javascript
Use .filter() on array and check the length of the new array.
// Example using array
isExactly1BooleanTrue(boolean:boolean[]) {
return booleans.filter(value => value === true).length === 1;
}
// Example using ...booleans
isExactly1BooleanTrue(...booleans) {
return booleans.filter(value => value === true).length === 1;
}
One way to do it is to perform pairwise AND and then check if any of the pairwise comparisons returned true with chained OR. In python I would implement it using
from itertools import combinations
def one_true(bools):
pairwise_comp = [comb[0] and comb[1] for comb in combinations(bools, 2)]
return not any(pairwise_comp)
This approach easily generalizes to lists of arbitrary length, although for very long lists, the number of possible pairs grows very quickly.
Python:
boolean_list.count(True) == 1
OK, another try. Call the different booleans b[i], and call a slice of them (a range of the array) b[i .. j]. Define functions none(b[i .. j]) and just_one(b[i .. j]) (can substitute the recursive definitions to get explicit formulas if required). We have, using C notation for logical operations (&& is and, || is or, ^ for xor (not really in C), ! is not):
none(b[i .. i + 1]) ~~> !b[i] && !b[i + 1]
just_one(b[i .. i + 1]) ~~> b[i] ^ b[i + 1]
And then recursively:
none(b[i .. j + 1]) ~~> none(b[i .. j]) && !b[j + 1]
just_one(b[i .. j + 1] ~~> (just_one(b[i .. j]) && !b[j + 1]) ^ (none(b[i .. j]) && b[j + 1])
And you are interested in just_one(b[1 .. n]).
The expressions will turn out horrible.
Have fun!
That python script does the job nicely. Here's the one-liner it uses:
((x ∨ (y ∨ z)) ∧ (¬(x ∧ y) ∧ (¬(z ∧ x) ∧ ¬(y ∧ z))))
Retracted for Privacy and Anders Johannsen provided already correct and simple answers. But both solutions do not scale very well (O(n^2)). If performance is important you can stick to the following solution, which performs in O(n):
def exact_one_of(array_of_bool):
exact_one = more_than_one = False
for array_elem in array_of_bool:
more_than_one = (exact_one and array_elem) or more_than_one
exact_one = (exact_one ^ array_elem) and (not more_than_one)
return exact_one
(I used python and a for loop for simplicity. But of course this loop could be unrolled to a sequence of NOT, AND, OR and XOR operations)
It works by tracking two states per boolean variable/list entry:
is there exactly one "True" from the beginning of the list until this entry?
are there more than one "True" from the beginning of the list until this entry?
The states of a list entry can be simply derived from the previous states and corresponding list entry/boolean variable.
Python:
let see using example...
steps:
below function exactly_one_topping takes three parameter
stores their values in the list as True, False
Check whether there exists only one true value by checking the count to be exact 1.
def exactly_one_topping(ketchup, mustard, onion):
args = [ketchup,mustard,onion]
if args.count(True) == 1: # check if Exactly one value is True
return True
else:
return False
How do you want to count how many are true without, you know, counting? Sure, you could do something messy like (C syntax, my Python is horrible):
for(i = 0; i < last && !booleans[i]; i++)
;
if(i == last)
return 0; /* No true one found */
/* We have a true one, check there isn't another */
for(i++; i < last && !booleans[i]; i++)
;
if(i == last)
return 1; /* No more true ones */
else
return 0; /* Found another true */
I'm sure you'll agree that the win (if any) is slight, and the readability is bad.
It is not possible without looping. Check BitSet cardinality() in java implementation.
http://fuseyism.com/classpath/doc/java/util/BitSet-source.html
We can do it this way:-
if (A=true or B=true)and(not(A=true and B=true)) then
<enter statements>
end if

What's the difference between XOR and NOT-EQUAL-TO?

My question uses Java as an example, but I guess it applies to probably all.
Is there any practical difference between the XOR operator (^ in Java) and the not-equal-to operator (!= in Java), when comparing booleans?
I evaluated things here, but I just kept wondering (seems weird, two things equal)... and didn't find anything on the net. Just one discussion in some forum that ended quickly without any result.
For Boolean values, they mean the same thing - although there's a compound assignment operator for XOR:
x ^= y;
There's no equivalent compound assignment operator for inequality.
As for why they're both available - it would be odd for XOR not to be available just because it works the same way as inequality. It should logically be there, so it is. For non-Boolean types the result is different because it's a different result type, but that doesn't mean it would make sense to remove XOR for boolean.
As stated in the Java Language Specification:
The result of != is false if the operands are both true or both false; otherwise, the result is true. Thus != behaves the same as ^ (§15.22.2) when applied to boolean operands.
In addition if you try looking at bytecode of a simple snippet:
void test(boolean b1, boolean b2) {
boolean res1 = b1^b2;
boolean res2 = b1!=b2;
}
you obtain:
test(ZZ)V
L0
LINENUMBER 45 L0
ILOAD 1
ILOAD 2
IXOR
ISTORE 3
L1
LINENUMBER 46 L1
ILOAD 1
ILOAD 2
IXOR
ISTORE 4
L2
LINENUMBER 47 L2
RETURN
L3
This assures that, in addition to the same semantics, there's no any actual practical difference in implementation. (you can also see that internally ints are used to store boolean values)
Yes, you can use XOR to test booleans for (in)equality, although the code is less intuitive: if (x ^ y) versus if (x != y).
With boolean values, there should be no difference. You should choose whichever is more appropriate for your sense of operation.
Example:
bool oldChoice = ...;
bool newChoice = ...;
if (oldChoice != newChoice)
...
Here XOR would give the same result, but will not reflect the real code intention.
They should be essentially the same in this case.
There's a big difference, XOR works at bit-level, keeping differences as ones,
so 0b0011 xor 0b1101 => 0b1110
regards,
//t