Go Back   DaemonForums > Miscellaneous > Programming

Programming C, bash, Python, Perl, PHP, Java, you name it.

Thread Tools Display Modes
  #1   (View Single Post)  
Old 22nd December 2019
victorvas victorvas is offline
Real Name: Victor
Join Date: May 2019
Posts: 147
Default Python 3 strange behavior

Hello! I've got a strange situation with python 3.8 where
>>> -10 % 3
-10 % 3 returns 2 instead of 1. Is this a bug?
Reply With Quote
  #2   (View Single Post)  
Old 22nd December 2019
Beastie Beastie is offline
Daemonology student
Join Date: Jan 2009
Location: /dev/earth0
Posts: 335

Python 2 or 3, it's normal. When dividing, positive numbers round towards zero while negative numbers round away from zero:
>>> 10 // 3
>>> -10 // 3
Resulting in the numbers you've been getting since 10/3=3.33333333333 and 10-3*3=1 while -10/3=-3.33333333333 and -10-(-4*3)=2.

Perl does the same:
print 10 % 3;
print -10 % 3;
Check this blog post to see Guido van Rossum's explanation.

If you need the more usual Euclidean division method you've been used to since school (also used in C), use math.fmod instead of the % operator:
>>> import math
>>> math.fmod(10,3)
>>> math.fmod(-10,3)
As you can also notice, now the sign follows the dividend while it followed the divisor when using the % operator.
May the source be with you!
Reply With Quote

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
apropos(1) behavior beavers OpenBSD General 10 23rd September 2019 07:35 AM
strange behavior of PF majkelos OpenBSD Security 2 23rd October 2011 06:23 PM
Python 2.7 released J65nko News 0 6th July 2010 07:24 PM
Terminal display behavior 18Googol2 FreeBSD General 8 26th September 2008 02:05 PM
Strange network behavior Weaseal Off-Topic 4 27th May 2008 05:34 PM

All times are GMT. The time now is 06:31 AM.

Powered by vBulletin® Version 3.8.4
Copyright ©2000 - 2023, Jelsoft Enterprises Ltd.
Content copyright © 2007-2010, the authors
Daemon image copyright ©1988, Marshall Kirk McKusick