Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Integer division
#1
Hi all. I am new to python and was hoping to get some help. I understand that // is used to do integer division but I'm confused about certain outcomes. Eg: 10//2.5 results in 4.0, 9//1.6 results 5.0 (rounded down), 9//1.8 results in 4.0 !! I don't understand why the last two have different results. Can someone please explain (remembering that I am new to this lol)?

Thanks,
plozaq
Reply
#2
It's the integer floor of a division, but it may not be the one you expect. You might want to review https://docs.python.org/3/tutorial/floatingpoint.html.

1.8 can't be exactly represented in a binary floating point, so math using that value will tend to have small errors.

>>> format(1.8, ".20f")
'1.80000000000000004441'
Since the representation is slightly larger than 1.8, the division doesn't work out exactly and it can't complete 5 full divisions.
>>> divmod(9,1.8)
(4.0, 1.7999999999999998)
So the integer division result is only 4, not 5 due to inaccuracies in the floating point. Whereas 1.799999999 would give a different number.

>>> 9 // 1.8
4.0
>>> 9 // 1.79999999999
5.0
Reply
#3
Thankyou so much for the answer. It was confusing the hell out of me but now it makes sense lol.

plozaq
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Division questions Dionysis 5 992 Feb-14-2023, 02:02 PM
Last Post: Dionysis
  Division by zero and value of argument Lawu 5 2,970 Jul-01-2022, 02:28 PM
Last Post: Lawu
  Floor division problem with plotting x-axis tick labels Mark17 5 2,047 Apr-03-2022, 01:48 PM
Last Post: Mark17
  Division calcuation with answers to 1decimal place. sik 3 2,091 Jul-15-2021, 08:15 AM
Last Post: DeaD_EyE
  Floor division return value Chirumer 8 3,697 Nov-26-2020, 02:34 PM
Last Post: DeaD_EyE
  Overcoming ZeroDivisionError: division by zero Error dgrunwal 8 4,877 Jun-12-2020, 01:52 PM
Last Post: dgrunwal
  Division of an integer into sub-numbers Richard_SS 4 2,884 Jun-14-2019, 11:47 AM
Last Post: DeaD_EyE
  Logic of using floor division and modulus for a different variable at different time SB_J 2 2,462 Nov-01-2018, 07:25 PM
Last Post: SB_J

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020