473,403 Members | 2,071 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,403 software developers and data experts.

Addition and multiplication puzzle

Can anyone either reproduce or explain the following
apparently inconsistent behaviours of __add__ and
__mul__? The class Gaussian provides a sub-bare-bones
implementation of Gaussian integers (a Gaussian
integer is a complex number x+yi for which both x and
y are
integers):

class Gaussian(object):
"""class representing Gaussian integers"""

def __init__(self, x, y = 0):
self.real, self.imag = x, y

def __repr__(self):
return repr(self.real) + "+" + repr(self.imag)
+ "*i"

def __add__(self, other):
if type(other) != Gaussian:
other = Gaussian(other)
return Gaussian(self.real + other.real,
self.imag + other.imag)

def __mul__(self, other):
if type(other) != Gaussian:
other = Gaussian(other)
return Gaussian(self.real * other.real -
self.imag * other.imag, \
self.real * other.imag +
self.imag * other.real)

Under Python 2.3.2 I get:
i = Gaussian(0, 1)
i * 3 0+3*i 3 * i # surprise! 0+3*i i + 3 3+1*i 3 + i

Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for +: 'int'
and 'Gaussian'

In other words, I can *multiply* an int by a Gaussian
in either order, but I can only *add* a Gaussian to an
int, not the other way around. The surprise is that
multiplying an int by a Gaussian works---I'd expect it
to complain since there's no __rmul__ method defined,
in just the same way that 3+i produced an exception
above. Why do addition and multiplication behave
differently?

Yours hoping for enlightenment,

Mark
__________________________________
Do you Yahoo!?
The New Yahoo! Shopping - with improved product search
http://shopping.yahoo.com

Jul 18 '05 #1
3 3419

"Mark Dickinson" <ma*************@yahoo.com> wrote in message
news:ma***********************************@python. org...
Can anyone either reproduce or explain the following
apparently inconsistent behaviours of __add__ and
__mul__? The class Gaussian provides a sub-bare-bones
implementation of Gaussian integers (a Gaussian
integer is a complex number x+yi for which both x and
y are
integers):

class Gaussian(object):
"""class representing Gaussian integers"""

def __init__(self, x, y = 0):
self.real, self.imag = x, y

def __repr__(self):
return repr(self.real) + "+" + repr(self.imag)
+ "*i"

def __add__(self, other):
if type(other) != Gaussian:
other = Gaussian(other)
return Gaussian(self.real + other.real,
self.imag + other.imag)

def __mul__(self, other):
if type(other) != Gaussian:
other = Gaussian(other)
return Gaussian(self.real * other.real -
self.imag * other.imag, \
self.real * other.imag +
self.imag * other.real)

Under Python 2.3.2 I get:
i = Gaussian(0, 1)
i * 3 0+3*i 3 * i # surprise! 0+3*i i + 3 3+1*i 3 + i

Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for +: 'int'
and 'Gaussian'

In other words, I can *multiply* an int by a Gaussian
in either order, but I can only *add* a Gaussian to an
int, not the other way around. The surprise is that
multiplying an int by a Gaussian works---I'd expect it
to complain since there's no __rmul__ method defined,
in just the same way that 3+i produced an exception
above. Why do addition and multiplication behave
differently?


I think new style classes create this, as old style classes exhibit the same
behaviour for multiplication and division:

class Test:
def __init__(self, val):
self.val = val
def __add__(self, other):
return self.val + other
def __mul__(self, other):
return self.val * other

In typeobject.c, I find:

SQSLOT("__add__", sq_concat, slot_sq_concat, wrap_binaryfunc,
"x.__add__(y) <==> x+y"),
SQSLOT("__mul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
"x.__mul__(n) <==> x*n"),
SQSLOT("__rmul__", sq_repeat, slot_sq_repeat, wrap_intargfunc,
"x.__rmul__(n) <==> n*x"),

My guess is that this explains why multiplication works and addition
doesn't, as there is no corresponding SQSLOT("__radd__"... but adding

SQSLOT("__radd__", sq_concat, slot_sq_concat, wrap_binaryfunc,
"x.__radd__(y) <==> y+x"),

and recompiling didn't fix the problem, so I'm either on the wrong track or
missed a connection along the way.

Emile van Sebille
em***@fenx.com


Jul 18 '05 #2
Mark Dickinson wrote:
Can anyone either reproduce or explain the following
apparently inconsistent behaviours of __add__ and
__mul__? The class Gaussian provides a sub-bare-bones
implementation of Gaussian integers (a Gaussian
integer is a complex number x+yi for which both x and
y are
integers):

class Gaussian(object):
"""class representing Gaussian integers"""

def __init__(self, x, y = 0):
self.real, self.imag = x, y

def __repr__(self):
return repr(self.real) + "+" + repr(self.imag)
+ "*i"

def __add__(self, other):
if type(other) != Gaussian:
other = Gaussian(other)
return Gaussian(self.real + other.real,
self.imag + other.imag)

def __mul__(self, other):
if type(other) != Gaussian:
other = Gaussian(other)
return Gaussian(self.real * other.real -
self.imag * other.imag, \
self.real * other.imag +
self.imag * other.real)

Under Python 2.3.2 I get:

i = Gaussian(0, 1)
i * 3
0+3*i
3 * i # surprise!
0+3*i
i + 3
3+1*i
3 + i


Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for +: 'int'
and 'Gaussian'

In other words, I can *multiply* an int by a Gaussian
in either order, but I can only *add* a Gaussian to an
int, not the other way around. The surprise is that
multiplying an int by a Gaussian works---I'd expect it
to complain since there's no __rmul__ method defined,
in just the same way that 3+i produced an exception
above. Why do addition and multiplication behave
differently?

Yours hoping for enlightenment,

Mark
__________________________________
Do you Yahoo!?
The New Yahoo! Shopping - with improved product search
http://shopping.yahoo.com

3*i gives the expected error under Python 2.2.2. Curious indeed.

Jul 18 '05 #3

"Mark Dickinson" <ma*************@yahoo.com> wrote in message
news:ma***********************************@python. org...
Can anyone either reproduce or explain the following
apparently inconsistent behaviours of __add__ and
__mul__? The class Gaussian provides a sub-bare-bones
implementation of Gaussian integers (a Gaussian
integer is a complex number x+yi for which both x and
y are
integers):

class Gaussian(object):
"""class representing Gaussian integers"""

def __init__(self, x, y = 0):
self.real, self.imag = x, y

def __repr__(self):
return repr(self.real) + "+" + repr(self.imag)
+ "*i"

def __add__(self, other):
if type(other) != Gaussian:
other = Gaussian(other)
return Gaussian(self.real + other.real,
self.imag + other.imag)

def __mul__(self, other):
if type(other) != Gaussian:
other = Gaussian(other)
return Gaussian(self.real * other.real -
self.imag * other.imag, \
self.real * other.imag +
self.imag * other.real)

Under Python 2.3.2 I get:
i = Gaussian(0, 1)
i * 3 0+3*i 3 * i # surprise! 0+3*i i + 3 3+1*i 3 + i
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for +: 'int'
and 'Gaussian'

In other words, I can *multiply* an int by a Gaussian
in either order, but I can only *add* a Gaussian to an
int, not the other way around. The surprise is that
multiplying an int by a Gaussian works---I'd expect it
to complain since there's no __rmul__ method defined,
in just the same way that 3+i produced an exception
above. Why do addition and multiplication behave
differently?

Yours hoping for enlightenment,

Mark


I vaguely remember a discussion a while back about
getting rid of the 'r' operators. I don't remember what
ever came of it, though, and I agree that the inconsistent
treatment of __mul__ and __add__ is strange. I suspect
something may have gotten lost in the boolean implementation.

The Python Reference Manual doesn't say anything
about it, though.

John Roth


__________________________________
Do you Yahoo!?
The New Yahoo! Shopping - with improved product search
http://shopping.yahoo.com

Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: jeffbernstein | last post by:
Greetings. I'm reading "How to think like a computer scientist: Learning with Python" and there's a question regarding string operations. The question is, "Can you think of a property that...
9
by: Ralf Hildebrandt | last post by:
Hi all! First of all: I am a C-newbie. I have noticed a "strange" behavior with the standart integer multiplication. The code is: void main(void)
1
by: xavier vazquez | last post by:
I have a problem with a program that does not working properly...when the program run is suppose to generate a cross word puzzle , when the outcome show the letter of the words overlap one intop of...
0
by: xavier vazquez | last post by:
have a problem with a program that does not working properly...when the program run is suppose to generate a cross word puzzle , when the outcome show the letter of the words overlap one intop of the...
2
by: confusedKaran | last post by:
Hi, I am currently making a program which can add and multiply two numbers with infinite amount of digits. The addition part of it I did by taking the input as a string and then one by one addiing...
3
by: oncue01 | last post by:
Word Puzzle Task You are going to search M words in an N × N puzzle. The words may have been placed in one of the four directions as from (i) left to right (E), (ii) right to left (W), (iii) up...
5
by: robin | last post by:
write a c++ program to Add two integer numbers without using any arithmetic ,bitwise operator , printf,no loop no recursion nothing.
1
by: Braulio | last post by:
Helo! I'm Having A Big Time Trying To Solve This Puzzle, Hope Somebody Could Help Me: I Need To Be Able To Make An Addition Of Hours And Minutes, But When I Try To Add 20:50 Plus 10:45, I Don't...
4
by: honey777 | last post by:
Problem: 15 Puzzle This is a common puzzle with a 4x4 playing space with 15 tiles, numbered 1 through 15. One "spot" is always left blank. Here is an example of the puzzle: The goal is to...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.