Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

julia @printf changes my variable

Tags:

julia

I find difficult to format numbers with Julia :

b = 1.111111
bb = @printf "test : %5.2f" b
bb

test :  1.11

That is fine.

using PyPlot 
annotate(@printf "test : %5.2f" b, xy=[1;1])

test : 
type: non-boolean (Array{Bool,1}) used in boolean context
while loading In[16], in expression starting on line 2

That I don't understand since I expect the result of @printf to be a String. So if someone can explain me how I should do what would be

"test : %5.2f" % b

in Python.

And to conclude, here is the weird thing :

b
1

b has been cast to an Int. Would you call that a bug?

I use Julia 0.3.2 with Jupyter 3.1

like image 228
Olric Avatar asked May 21 '15 15:05

Olric


1 Answers

Macro parsing (particularly within the context of a function call) is a little finicky. You can see how Julia parsed this simply by quoting it:

julia> :(annotate(@printf "test : %5.2f" b, xy=[1;1]))
:(annotate(@printf "test : %5.2f" (b,xy) = [1,1]))

As you can see, the macro is "greedier" than function arguments. The entire b, xy=[1;1] part is taken as the only argument to the @printf macro. This explains why the value of b changes — the = has changed contexts from denoting a keyword argument to being a general tuple assignment!

I highly recommend using the function-like syntax for macros when using them within more complicated expressions like this:

annotate(@sprintf("test : %5.2f", b), xy=[1;1])

And, finally, note that I've changed @printf to @sprintf. The former returns nothing and simply prints the value out, whereas the latter returns a string that you can pass to functions.

like image 176
mbauman Avatar answered Oct 13 '22 12:10

mbauman