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.
Any self respecting compiler will promote constants to the appropriate type. The difference is only cosmetic.
There are no differences in the output that I can detect.
>>> float(1.*-5.*0.*-1.).hex()
'0x0.0p+0'
>>> float(1.*-5.*0.*-1).hex()
'0x0.0p+0'
>>> float(1.*5.*0.*-1.).hex()
'-0x0.0p+0'
>>> float(1.*5.*0.*-1).hex()
'-0x0.0p+0'
>>>
精彩评论