Booleans in Julia, when used in calculations, have numeric values (false
= 0
, true
= 1
).
All of the following have expected results:
true + false # 1
false - true # -1
false / true # 0.0
true ÷ false # DivideError: integer division error
0 ÷ 1 # 0
Except for:
false ÷ true # false
So why does false ÷ true
evaluate to false
, instead of 0
like 0 ÷ 1
does?
Update: it appears multiplication has the same behavior:
false * true # false
I can understand that there may different behavior for type Bool
than other numeric types, but it's strange that addition and subtraction behave differently than multiplication and division.
The Mathematical Operations documentation states:
Note that Bool is an integer type and all the usual promotion rules and numeric operators are also defined on it.
so it's a little surprising that it doesn't treat booleans as integers in all arithmetic contexts.
Base.div()
function. I am not sure and have never used Julia, but I guess that the div function always tries to return something of the same type as the operands, therefore a boolean. Guess: div internally does bool->int conversion, does the int division and then casts back to boolean. For false÷true that works, for true÷false the integer division step fails. – Blobdiv(false, true)
docs.julialang.org/en/v1/manual/mathematical-operations/… – Amburdiv(x::Bool, y::Bool) = y ? x : throw(DivideError())
– Starlike