For the longest time, I wondered about something extremely basic. In my code where execution time is really important, I always wondered what is the best way to handle real number like 1.0 or 0.0.
What is the fastest way to use them within a code
i) just use them as 1.0
ii) or as Float64(1)
iii) define them at the beginning of the code const rone = 1.0 and then use rone when you need them
Apologies if this is trivial but I am curious whether it makes any difference for execution time.
I really can’t see a situation, where these wouldn’t produce the same code, so I really wouldn’t worry about this. If you want to be absolutely sure, you can check if
@code_llvm of your function contains the literal
1.0 is a literal. It’s type is
Float64, which is exactly the same as
Float64(1). Defining it as a
const would make sense if it were something that you would at some point consider changing, or if it were something that was tedious to write out (like π) or remember, or you want the meaning of the variable to be explicit in the code.
1.0 is what I would do. There is no performance cost to this.
There’s an exception, though. Sometimes it’s better to just write
1. For example, if your code says
x + 1.0 then if
x is an integer, the result becomes a float. That is something to consider. Also,
x^1 is faster than
x^1.0 (this is more relevant for numbers greater than 1, though.) I prefer to write
x + 1 or
1 * x or
x < 1 or
x^1 etc. etc. in many situations, because integers are more versatile and sometimes faster than floats.
Thank you both! You just freed some space in my brain to focus on other things
Some context on what “handle” means would be useful. Eg to avoid overly specific types, I would try to go with
oneunit, depending on the application. I rarely ever write out either
1.0 in actual code.
I do a lot of numerical calculations in my code and 1.0 and 0.0 are on the right hand side of my equations very frequently. I hope this clarifies what I meant.
It would be better to have some example code, but in 99% of cases I would just use
0 and let Julia promote. For the cases you want to avoid (and possible fixes), see Avoid changing the type of a variable.