Defining FixedPoint unary arithmetic operators

The following are the unary operator method functions:

def __abs__(self) -> 'FixedPoint':
return FixedPoint(abs(self.value), self.scale)

def __float__(self) -> float:
return self.value / self.scale

def __int__(self) -> int:
return int(self.value / self.scale)

def __trunc__(self) -> int:
return int(math.trunc(self.value / self.scale))

def __ceil__(self) -> int:
return int(math.ceil(self.value / self.scale))

def __floor__(self) -> int:
return int(math.floor(self.value / self.scale))

def __round__(self, ndigits: Optional[int] = 0) -> Any:
return FixedPoint(round(self.value / self.scale, ndigits=ndigits), self.scale)

def __neg__(self) -> 'FixedPoint':
return FixedPoint(-self.value, self.scale)

def __pos__(self) -> 'FixedPoint':
return self

For the __round__(), __trunc__(), __ceil__(), and __floor__() operators, we've delegated the work to a Python library function. There are some potential optimizations, but we've taken the lazy route of creating a float approximation and used that to create the desired result. This suite of methods ensures that our FixedPoint objects will work with a number of arithmetic functions. Yes, there are a lot of operators in Python. This isn't the entire suite. We haven't provided implementations for the comparison or bit-kicking operators. The comparisons are generally similar to arithmetic operations, and are left as an exercise for the reader. The bit-wise operators (&, |, ^, and ~) don't have a clear meaning outside the domains, like values or sets, so we shouldn't implement them.

In the next section, we'll see how to implement FixedPoint reflected operators.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset