Conversion to Boolean with fractions.Fraction and numpy integers
See original GitHub issueWhen defining a Fraction based on a numpy array of integers, the numerator is a numpy integer, which causes problems when converting to bool.
Reproducing code example:
import numpy as np
from fractions import Fraction
numerators = np.array([4, 3])
my_fraction = Fraction(numerators[0], 100)
print(repr(my_fraction))
print(bool(my_fraction))
In this example my_fraction is represented as Fraction(4, 100), and one would expect that it converts to True; but it raises an error instead.
Error message:
Traceback (most recent call last): File “main.py”, line 6, in <module> print(bool(my_fraction)) TypeError: bool should return bool, returned numpy.bool_
Numpy/Python version information:
Numpy 1.17.2 Python 3.7.4
Issue Analytics
- State:
- Created 4 years ago
- Comments:5 (4 by maintainers)
Top Results From Across the Web
Representing Rational Numbers With Python Fractions
In this tutorial, you'll learn how to: Convert between decimal and fractional notation; Perform rational number arithmetic; Approximate irrational numbers ...
Read more >converting floats to fractions - python - Stack Overflow
The problem comes up when fraction is a floating point number (for example 1/3). How can I solve this problem? Here's an example:...
Read more >Chapter 4. NumPy Basics: Arrays and Vectorized Computation
You can even mix and match boolean arrays with slices or integers (or ... of the built-in Python divmod : it returns the...
Read more >Convert bool (True, False) and other types to each ... - nkmk note
bool is a subclass of int. True and False are equivalent to 1 and 0 · Truth value testing in Python · Convert...
Read more >Rational Numbers - Standard Commutative Rings
Conversion from fractions: sage: import fractions sage: f = fractions.Fraction(1r, 2r) sage: Rational(f) 1/2. Conversion from PARI:.
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

Thanks for your answers. I opened a ticket on bugs.python.org: https://bugs.python.org/issue39274 .
I opened a PR to python to fix things there. I doubt we can change anything in NumPy in a reasonable time-frame, so closing.