Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: difference between 1. and 1

I came across some code:

dz3 = 1./m * (a3 - Y)

Why is 1. used here instead of simply 1?

Both seem equivalent:

>>> 1 / 4
0.25
>>> 1. / 4
0.25

Are there any cases where they are not equivalent?

like image 749
Tom Hale Avatar asked Oct 15 '25 14:10

Tom Hale


2 Answers

That kind of thing would be used for Python 2 compatibility, where division with two int operands was integer division by default. 1. is a float instead of an int, so will result in float division regardless of the Python version and whether m is an int.

like image 197
Ry- Avatar answered Oct 17 '25 04:10

Ry-


In Python2

>>> 3/2 # returns 1

Whereas in Python3

>>> 3/2 # returns 1.5

As you can see one makes integer division and other makes float division.

If I were to write

>>> 3./2 # returns 1.5

It performs float division no matter of the Python version I choose. Because float / integer can only result in float.

Also to make integer division in Python 3, you just write

>>> 3//2

See for further info

like image 20
Computa Avatar answered Oct 17 '25 04:10

Computa