Julia报错:无法将BitArray{1}转换为Int64类型求解决
Hey there! No worries at all—we all start with basic questions, and this is a great one to clarify how Julia handles type conversions and array operations.
Let's walk through what's going on step by step:
What
a.>bactually returns
When you runa.>b, you're doing an element-wise comparison between the two arrays. For your input values, this gives you aBitArray{1}(a boolean array) like[false, true].Why
Int(a.>b)throws an error
TheInt()constructor is built to convert a single value (like a single boolean or float) to anInt64type. It doesn't have a method to convert an entire array of booleans directly into a single integer—hence theMethodErrorabout not being able to convertBitArray{1}toInt64.The correct way to get an integer array from the boolean comparison
To apply theIntconversion to every element in the array, you need to use Julia's broadcasting syntax with a dot. This tells Julia to run the conversion on each element individually:Int.(a.>b)This will turn each
falseinto0and eachtrueinto1, giving you the integer array[0, 1]you're expecting.Why
1(a.>b)works (and what it's actually doing)
Wait a second—1(a.>b)shouldn't work on its own, since1is a number, not a function. I suspect you might have meant to use broadcasting with multiplication:1 .* (a.>b)In Julia, boolean values are implicitly treated as
0(false) and1(true) in numerical operations. Multiplying each element by 1 converts the boolean array to a float array[0.0, 1.0]. If you want integer values instead,Int.(a.>b)is the cleaner, more explicit choice.
Hope that clears things up!
内容的提问来源于stack exchange,提问作者zlon

