Dividing Fractions in Python 3 [duplicate] - python

The tuples represent fractions. I'm trying to divide the fractions by multiplying by the reciprical
class Test():
def __init__(self):
self._x=(1,2)
def __div__(self,div_fraction):
return (self._x[0]*div_fraction[1],self._x[1]*div_fraction[0])
y=Test()
z=y/(1,3)
print(z)
Gives me:
Traceback (most recent call last):
File "E:/test.py", line 8, in <module>
z=y/(1,3)
TypeError: unsupported operand type(s) for /: 'Test' and 'tuple'
Yet when I change the __div__ to __mul__ and use * instead of / it does what it should.
How do I fix the exception I'm getting?

Python 3.x uses __truediv__ and __floordiv__. __div__ is 2.x-only.

had the same problem the other day.
see if __future__.division is active in your environment. if so, you need to define __truediv__ as well.
http://docs.python.org/2/library/operator.html#mapping-operators-to-functions

Related

Unable to make built-in function 'sum' work for an array of objects of my class [duplicate]

In the sum function, the prototype is sum(iterable[,start]), which sums everything in the iterable object plus the start value. I wonder why there is a start value in here? Is there nay particular use case this value is needed?
Please don't give any more examples how start is used. I am wondering why it exist in this function. If the prototype of sum function is only sum(iterable), and return None if iterable is empty, everything will just work. So why we need start in here?
If you are summing things that aren't integers you may need to provide a start value to avoid an error.
>>> from datetime import timedelta
>>> timedeltas = [timedelta(1), timedelta(2)]
>>> sum(timedeltas)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'datetime.timedelta'
>>> sum(timedeltas, timedelta())
datetime.timedelta(3)

Why does int.__eq__ seem to be not implemented in python2 [duplicate]

This question already has answers here:
How int() object uses "==" operator without __eq__() method in python2?
(3 answers)
Closed 2 years ago.
I've got a head scratchier and it seems I'm not the only one, but is there really no solution? I find that hard to believe!
So the question is why can't I call int.__eq__ with 2 operators or i.__eq__ with one? How can I use __eq__ (and the other comparison operators) for a per item comparison for a sequence of ints?
Here's a dump from python2.7.17:
>>> i = 0
>>> type(i)
<type 'int'>
>>> i.__eq__(0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute '__eq__'
>>> type(i).__eq__(i, 0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: expected 1 arguments, got 2
>>> type(i).__eq__(0)
NotImplemented
But my dumo from python3.6.9 behaves itself:
>>> i = 0
>>> type(i)
<class 'int'>
>>> i.__eq__(0)
True
>>> type(i).__eq__(i, 0)
True
>>> type(i).__eq__(0) # this is not expected to work, but just for the sake of voodoo.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: expected 1 arguments, got 0
I know python2 is no longer supported but there are a few applications that only use python2 and I would like to make my code backwards compatible anyway.
So anyone out there have a solutuon for hacking the comparison magic operator methods as function calls in python2? I am sure there must be some work around.
It seems there is some information on this. I just read that python2 falls back to using cmp in some cases, while in python3 there is no cmp (or so I read). So I guess the thing to do is not use eq and ne but instead use cmp but I love some additional perspective on this
The general rule is: don't touch dunderscore methods, use functions and operators instead and those will delegate to dunderscore implementation as necessary. In your case you're looking for the == operator or the functional equivalent operator.eq.
from operator import eq
from functools import partial
print eq(1, 2)
f = partial(eq, 1)
print f(2)

In Python 3.x, TypeError: unsupported operand type(s) for /: 'complex' and 'complex' [duplicate]

The tuples represent fractions. I'm trying to divide the fractions by multiplying by the reciprical
class Test():
def __init__(self):
self._x=(1,2)
def __div__(self,div_fraction):
return (self._x[0]*div_fraction[1],self._x[1]*div_fraction[0])
y=Test()
z=y/(1,3)
print(z)
Gives me:
Traceback (most recent call last):
File "E:/test.py", line 8, in <module>
z=y/(1,3)
TypeError: unsupported operand type(s) for /: 'Test' and 'tuple'
Yet when I change the __div__ to __mul__ and use * instead of / it does what it should.
How do I fix the exception I'm getting?
Python 3.x uses __truediv__ and __floordiv__. __div__ is 2.x-only.
had the same problem the other day.
see if __future__.division is active in your environment. if so, you need to define __truediv__ as well.
http://docs.python.org/2/library/operator.html#mapping-operators-to-functions

When does python raise a FloatingPointError?

Python documentation says that FloatingPointError is raised when a float calculation fails. But what is exactly meant here by "a float calculation"?
I tried adding, multiplying and dividing with floats but never managed to raise this specific error. Instead, i got a TypeError:
10/'a'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'int' and 'str'
Can someone help me understand when a FloatingPointError is raised in python?
It is part of the fpectl module. The FloatingPointError shouldn't be raised if you don't explicitly turn it on (fpectl.turnon_sigfpe()).
However mind the note:
The fpectl module is not built by default, and its usage is discouraged and may be dangerous except in the hands of experts. See also the section fpectl-limitations on limitations for more details.
Update: The fpectl module has been removed as of Python 3.7.
Even with FloatingPointErrors turned on, 10/'a' will never raise one. It will always raise a TypeError. A FloatingPointError will only be raised for operations that reach the point of actually performing floating-point math, like 1.0/0.0. 10/'a' doesn't get that far.
You can also trigger a FloatingPointError within numpy, by setting the appropriate numpy.seterr (or numpy.errstate context manager) flag. For an example taken from the documentation:
>>> np.sqrt(-1)
nan
>>> with np.errstate(invalid='raise'):
... np.sqrt(-1)
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
FloatingPointError: invalid value encountered in sqrt
Interestingly, it also raises FloatingPointError when all operands are integers:
>>> old_settings = np.seterr(all='warn', over='raise')
>>> np.int16(32000) * np.int16(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FloatingPointError: overflow encountered in short_scalars
The documentation notes the conditions under which the FloatingPointError will be raised:
The floating-point exceptions are defined in the IEEE 754 standard [1]:
Division by zero: infinite result obtained from finite numbers.
Overflow: result too large to be expressed.
Underflow: result so close to zero that some precision was lost.
Invalid operation: result is not an expressible number, typically indicates that a NaN was produced.

Python Class __div__ issue

The tuples represent fractions. I'm trying to divide the fractions by multiplying by the reciprical
class Test():
def __init__(self):
self._x=(1,2)
def __div__(self,div_fraction):
return (self._x[0]*div_fraction[1],self._x[1]*div_fraction[0])
y=Test()
z=y/(1,3)
print(z)
Gives me:
Traceback (most recent call last):
File "E:/test.py", line 8, in <module>
z=y/(1,3)
TypeError: unsupported operand type(s) for /: 'Test' and 'tuple'
Yet when I change the __div__ to __mul__ and use * instead of / it does what it should.
How do I fix the exception I'm getting?
Python 3.x uses __truediv__ and __floordiv__. __div__ is 2.x-only.
had the same problem the other day.
see if __future__.division is active in your environment. if so, you need to define __truediv__ as well.
http://docs.python.org/2/library/operator.html#mapping-operators-to-functions

Categories