3

I coded a custom class IntegerMod for integers modulo a prime number. Everything works fine. Then used them as coefficients of polynomials built with numpy.poly1d, and managed to implement enough methods in IntegerMod so that operations with those polynomials work as I needed (for instance, finding interpolating polynomials given a bunch of points).

Just a little detail remains, it is that print(pol) for those polynomials actually fails, because Python tries to use string formating %g for the coefficents, and that fails saying IntegerMod should be a string or a number. In fact IntegerMod inherits from numbers.Number, but it seems not enough. My question is, can I implement in my class the behaviour for string formatting? If not, how should I deal with this issue?

A MWE producing the error:

import numbers
import numpy as np


class IntegerMod(numbers.Number):
    def __init__(self, k, p):
        self.k = k % p
        self.p = p

    def __repr__(self):
        return "<%d (%d)>" % (self.k, self.p)

if __name__ == "__main__":
    p = 13
    coef1 = IntegerMod(2, p)
    coef2 = IntegerMod(4, p)
    print(coef1)  # Works as expected
    pol = np.poly1d([coef1, coef2])
    print(pol)
    """ # error:
        s = '%.4g' % q
        TypeError: float() argument must be a string or a number, not 'IntegerMod'
    """
2
  • Why don't you implement str method (keep in mind that when str_ is missing, then print and any function using str() invokes __repr__()) Commented Feb 1, 2019 at 12:57
  • Change to np.poly1d([repr(coef1), repr(coef2)]) to get your __repr__. Commented Feb 1, 2019 at 13:09

1 Answer 1

3

Maybe you should implement the __float__ method, since poly1d formatting expects floats.

Something like this

    def __float__(self):
        return float(self.k)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.