# 1.0 vs Float64(1) versus const rone = 1.0

Hi all;

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.000000e+00`.

3 Likes

`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.

Just writing `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.

1 Like

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 `1` or `oneunit`, depending on the application. I rarely ever write out either `0.0` or `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 `1` and `0` and let Julia promote. For the cases you want to avoid (and possible fixes), see Avoid changing the type of a variable.

7 Likes