DaemonForums  

Go Back   DaemonForums > Miscellaneous > Programming

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

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

Hello! I've got a strange situation with python 3.8 where
Code:
>>> -10 % 3
2
-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: 334
Default

Python 2 or 3, it's normal. When dividing, positive numbers round towards zero while negative numbers round away from zero:
Code:
>>> 10 // 3
3
>>> -10 // 3
-4
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:
Code:
print 10 % 3;
1
print -10 % 3;
2
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:
Code:
>>> import math
>>> math.fmod(10,3)
1.0
>>> math.fmod(-10,3)
-1.0
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
Reply

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 12:23 PM.


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