sj95126
sj95126

Reputation: 6908

Why does false ÷ true evaluate to false?

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.

Upvotes: 9

Views: 270

Answers (2)

sj95126
sj95126

Reputation: 6908

As @DNF pointed out, the div() decision is implemented in Boolean logic.

The specific method definitions are in the base code of the Julia source tree (julia/base/bool.jl).

Addition and subtraction convert Bool to Int:

+(x::Bool, y::Bool) = Int(x) + Int(y)
-(x::Bool, y::Bool) = Int(x) - Int(y)

but division does not:

div(x::Bool, y::Bool) = y ? x : throw(DivideError())

I do still find it a bit odd that not all Bool operations are treated as numeric types but clearly it's intended to be that way.

Upvotes: 2

Oscar Smith
Oscar Smith

Reputation: 6388

The reasoning is that the division of 2 bools is always a bool or error, while other arithmetic on bools can produce numbers outside the range of a bool.

Upvotes: 2

Related Questions