I’m using PyCall to interact with a python package which returns integers as a Vector{Bool}, e.g. [true, true, false, true, true, true, false, true]. How can I easily convert this to an integer?
In a previous question it’s shown how to convert from a bool Str to Int
The base for loop performs even better if it specializes in the specific case of base 2 numbers
julia> function poly_2_eval(p)
ex = 0
for e in p
ex *= 2
ex+=e
end
ex
end
poly_2_eval (generic function with 1 method)
julia> @btime poly_2_eval(v)
15.030 ns (0 allocations: 0 bytes)
221
It’s fun to play the benchmarks game, but let’s step back here and remember the context — this Vector{Bool} is coming from a Python function. Performance of a linear-time conversion is unlikely to matter in this context, so I would just go with any solution that is clear and requires little code, e.g. evalpoly(2, reverse(v)).
@rocco_sprmnt21 Its not the fastest because you are not using $ in your benchmarks, so most of the time is in how the type instability is handled, in polyeval it just quickly hits a function barrier.
@stevengj I mostly posted my solution for the simplicity. evalpoly is less clear to me than << because I have to think more about about what evalpoly is doing behind the scenes - it’s not a function I use much, where as reduce and << are generic. Of course that will vary person to person.
The loop I proposed is exactly the one (with a few modifications) with which the evalpoly function is built.
I did not know of this function (and I think it is not very well known in general).
This is why I believe that @Raf’s solution with reduce is preferable.
On the other hand, I believe that the two functions reduce (…) and poly_2_eval are, in a sense, isomorphic.
They probably have the same lowered code.
In fact, in terms of performance they are practically the same …
julia> v = [true, true, false, true, true, true, false, true]
8-element Vector{Bool}:
1
1
0
1
1
1
0
1
julia> function poly_2_eval(p)
ex = 0
for e in p
ex *= 2
ex+=e
end
ex
end
poly_2_eval (generic function with 1 method)
julia> @btime reduce((x,y)->x<<1+y, $v; init=0)
4.600 ns (0 allocations: 0 bytes)
221
julia> @btime reduce((x,y)->x*2+y, $v; init=0)
4.600 ns (0 allocations: 0 bytes)
221
julia> @btime poly_2_eval($v)
4.200 ns (0 allocations: 0 bytes)
221