python - Sympy classes Zero, One and NegativeOne, why they exist? -
today found this
>>> type(1) <class 'sympy.core.numbers.one'> >>> type(0) <class 'sympy.core.numbers.zero'> >>> type(-1) <class 'sympy.core.numbers.negativeone'> >>> type(2) <class 'sympy.core.numbers.integer'> i looked documentation sympy types, doesn't why exist. there reason have 3 special singleton classes -1, 0 , 1?
edit: saw @ sympy online shell
every number in sympy represented instance of the class number. floats, integers , rationals subclasses of number. zero subclass of integer.
you can inspect full class lineage of object calling class's mro (method resolution order) method:
in [34]: sympy import s in [38]: type(s.zero).mro() out[38]: [sympy.core.numbers.zero, sympy.core.numbers.integerconstant, sympy.core.numbers.integer, <-- 0 kind of integer sympy.core.numbers.rational, sympy.core.numbers.number, sympy.core.expr.atomicexpr, sympy.core.basic.atom, sympy.core.expr.expr, sympy.core.basic.basic, sympy.core.evalf.evalfmixin, object] these subclasses "teach" sympy how manipulate , simplify expressions symbolically. example, instances of rational class negated way:
def __neg__(self): return rational(-self.p, self.q) that say, if x instance of rational, -x causes x.__neg__() called. meanwhile, instances of integer class, negated by
def __neg__(self): return integer(-self.p) and if object is, in particular, instance of zero, its negation defined by:
@staticmethod def __neg__(): return s.zero # negation of 0 still 0 zero, one , minusone implement _eval_power method "teaches" these objects how evaluate x raised power (where x zero, one or minusone). example, zero raised positive expression equals itself:
def _eval_power(self, expt): if expt.is_positive: return self ... one raised anything equals itself:
def _eval_power(self, expt): return self if peruse the source code sympy.core.numbers module, you'll find loads of definitions in effect teaching sympy how symbolic arithmetic. it's not different children taught in math class, except expressed in computer-ese.
you might wondering why there isn't special class every integer. integers besides zero, one , minusone treated instances of general integer class. rules of addition , multiplication , on laid out there. unlike zero, one , minusone instantated when module loaded, other integers cached only needed:
def __new__(cls, i): ... try: return _intcache[ival] # <-- return cached integer if seen before except keyerror: obj = expr.__new__(cls) # <-- create new integer if ival not in _intcache obj.p = ival _intcache[ival] = obj return obj
Comments
Post a Comment