Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantage of using "x *= -1." over "x *= -1"?

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)?

like image 903
grautur Avatar asked Jul 11 '11 19:07

grautur


1 Answers

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.

like image 95
Ken Wayne VanderLinde Avatar answered Sep 21 '22 06:09

Ken Wayne VanderLinde