I'm looking at some Python numpy code, which contains lines like
a = 1. # later on, `a` is multiplied by other floats
x *= -1.
(From what I hopefully correctly understand, 1.
is equivalent to 1.0
).
Is there any reason to do this over a = 1
and x *= -1
? I can understand it if I'm going to be dividing a
and x
by an integer later on, so that I don't have to worry about forgetting to cast them to a float (assuming I want a float returned as a result of the division), but are there other reasons?
For example, if I know that a
is going to end up as a float, is it better for performance reasons to just initialize it as a float from the start? Or is this just for clarity (to make it explicit that a
and x
are both meant to be floats)?
It's pretty much for clarity.
While multiplying a float by an integer may incur a small performance hit (for converting the integer to a float), this depends on the compiler and also shouldn't be a large enough penalty to worry about (unless you are doing many such operations).
However, it definitely scores points for clarity. In the end, you really are multiplying a floating-point number by a floating-point number, and there is no reason to hide this fact. If a
and x
are meant to be float values, let them be float values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With