Clean way to create 'n-digit precision' float child class in Python - python

I want to create a LimitedPrecisionFloat class that would allow me to store a float with n-digits (I don't want to round the number, just cut the remaining digits). This is how I would like it to behave:
a = LimitedPrecisionFloat(3.45678, ndigits=3)
print(a) # 3.456
a += 0.11199
print(a) # 3.567
a -= 0.567999
print(a) # 3 (or 3.0 or 3.000)
print(a + 1.9999) # 4.999
# same with other arithmetic operators, ie.
print(LimitedPrecisionFloat(1.11111 * 9.0, 3) # 9.999
...
What I currently have is:
def round_down(x:float, ndigits:int):
str_x = str(x)
int_part = str(int(x))
fraction_part = str_x[str_x.find('.') + 1:]
fraction_part = fraction_part[:ndigits]
return float(int_part + '.' + fraction_part)
class LimitedPrecisionFloat(float):
def __new__(cls, x, ndigits:int):
return super(LimitedPrecisionFloat, cls).__new__(cls, round_down(x, ndigits))
def __init__(self, x, ndigits: int):
super().__init__()
self.ndigits = ndigits
def __add__(self, other):
return round_down(float(self) + other, ndigits=self.ndigits)
def __sub__(self, other):
return round_down(float(self) - other, ndigits=self.ndigits)
# other operators
However, this will not work, because whenever __add__ (or any other operator) is called, it returns float and the precision is back in the number. So when I tried doing something like this:
def __add__(self, other):
return LimitedPrecisionFloat(float(self) + other, ndigits=self.ndigits)
But then I got the max recursion depth error.
Because of that, I also don't have a clue on how to implement augmented arithmetic assignments, like __iadd__.

Related

How do I implement an __add__ function in a class for n-Dimensional vectors?

I am trying to create a simple class for n-dimensional vectors, but I cannot figure out how to add 2 vectors with n arguments together. I cannot find a way to return a variable amount of arguments in the __add__ function. In specific dimensions, this isn't too hard. Here's what it would look like for 2 dimensions:
class Vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return '({:g} , {:g} )'.format(self.x, self.y)
def __add__(self, other):
return Vector2D(self.x + other.x, self.y + other.y)
v, w = Vector2D(1,2), Vector2D(1,1)
print(v+w) #this should return (2, 3 )
Now I'd like to generalize this class to include all dimensions. I would probably use *args instead of x and y. Here's what that would sort of look like:
class Vector:
def __init__(self, *args):
self.args = args
def __str__(self):#not terribly important, but this function is quite ugly
string = '( '
for i in self.args:
string += str(i)
string += ', '
string += ')'
return string
def __add__(self, other): #how would one do this?
pass
v, w = Vector(2,3,4), Vector(1,1,1)
print(v+w) #I want this to return (3, 4, 5, )
I came up with some sort of solution, but it's not terribly efficient. Instead of loose argument, this version of my class uses a single list. I find this unsatisfactory however, so I came here to ask for a better solution. I have shared my mediocre solution down below:
class Vector:
def __init__(self, list = []):
self.list = list
def __str__(self):
string = '('
for i in self.list:
string += str(i)
string += ', '
string += ')'
return string
def __add__(self, other):
if len(self.list) == len(other.list):
coordinates = []
dimension = len(self.list)
for i in range(dimension):
newcoordinate = self.list[i] + other.list[i]
coordinates.append(newcoordinate)
return Vector(coordinates)
else:
raise TypeError('Can only add vectors of the same dimension.')
v, w = Vector([2,3,4]), Vector([1,1,1])
print(v+w) #this should return (3, 4, 5, )
In summary, I don't want to have to put the coordinates of a vector in a list. I can't think of a way to implement an __add__ function though.

a python class for modular integers that supports addition and negation?

I'm trying to come up with code for the definition addition and negation in python. The most similar thing I have is for multiplication, which I've copied below. Any ideas on what should be changed to account for addition and negation of modular integers? I know subtraction is just the addition of negation in this problem. Any help would be much appreciated!!
class Zp:
p = 2 #class attribute
def __init__(self, n):
self.n = n % Zp.p #instance attribute
def __str__(self):
#msg = '[' + str(self.n) + ']'
msg = str(self.n) + ' mod ' + str(Zp.p) + ')'
return msg
def __repr__(self):
return self.__str__()
# def __add__(self, other):
# [a], [b] in Zp ([a], [b] are sets of integers)
# [a]+[b] = [a+b] e.g. a+b mod p
# def __neg__(self, other):
# def __sub__ (self, other): # the addition of negation
def __mul__(self, other): # [a]*[b] = [a*b] e.g. a*b mod p
if Zp.__instancecheck__(other):
return Zp(self.n * other.n)
elif type(other) == int:
return Zp(self.n * other)
else:
raise TypeError('multiplication a Zp with a non-Zp or non-integer')
what I have tried for addition:
def __add__(self, other): # [a]*[b] = [a*b] e.g. a*b mod p
if Zp.__instancecheck__(other):
return Zp(self.n + other.n)
elif type(other) == int:
return Zp(self.n + other)
When doing modular arithmetic on numbers, you can generally do the normal operation (adding, subtracting, multiplying), then take the answer mod your modulus.
For example,
3 * 3 mod 2 = 9 mod 2 = 1 mod 2
In order to implement the operations you're specifying, do the operation, then take the modulo. Take a look at Wikipedia's article for more information about how to do modular arithmetic: Modular Arithmetic - Wikipedia

Creating Polynomial Class in Python

I am currently working on creating a Polynomial class that includes add , mul and eval methods. I'm currently stuck on the addition portion, if someone could give me some help on how to get that figured out that would be greatly appreciated. Everything currently works without errors but when I do p3 = p1 + p2 and I print p3 I get back the two lists together. Any feedback would be greatly appreciated.
class Polynomial(object):
def __init__(self, *coeffs, num = 0):
self.coeffs = list(coeffs) # turned into a list
assert (type(num) is type(1))
self.num = num
# Needs to be operator overload
'''
def __mul__(self, other):
'''
def __eval__(self, other, coeff, x):
result = coeff[-1]
for i in range(-2, -len(coeff)-1, -1):
result = result * x + coeff[i]
return result
def __add__(self, other):
assert type(other) is Polynomial
num = self.coeffs + other.coeffs
return Polynomial(num)
def __sub__(self, other):
assert type(other) is Polynomial
num = self.coeffs - other.coeffs
return Polynomial(num)
def __represntation__(self):
return "Polynomial" + str(self.coeffs)
def __str__(self):
rep = ""
degree = len(self.coeffs) - 1
rep += str(self.coeffs[0]) + "x^" + str(degree)
for i in range(1, len(self.coeffs)-1):
coeff = self.coeffs[i]
if coeff < 0:
rep += " - " + str(-coeff) + "x^" + str(degree - i)
else:
rep += " + " + str(coeff) + "x^" + str(degree - i)
if self.coeffs[-1] < 0:
rep += " - " + str(-self.coeffs[-1])
else:
rep += " + " + str(self.coeffs[-1])
return rep
You cannot directly add two lists.
def __add__(self, other):
assert type(other) is Polynomial
assert len(self.coeffs) != len(other.coeffs)
new_ceffs = [item1 + item2 for (item1, item2) in zip(self.coeffs, other.coeffs)]
return Polynomial(new_ceffs)
The problem is here:
num = self.coeffs + other.coeffs
Adding one list to another list concatenates them. To simply add corresponding elements to each other, you'd want to do
from itertools import zip_longest
...
num = [a + b for (a, b) in zip_longest(self.coeffs, other.coeffs, fillvalue=0)]
We use zip_longest() instead of the more generic zip() because one polynomial is possibly longer than the other and we don't want to ruin it. Either one of them will group together the corresponding elements so that we can easily add them and make a list of those.
You would do something similar for subtraction.
you should reverse the order of coefficients passed to your constructor so that indexes in the self.coeffs list correspond to the exponents. This would simplify the rest of your code and allow you to use zip_longest for additions and subtractions.
When you get to other operations however, I think you will realize that your internal structure would be easier to manage if it was a dictionary. A dictionary is more permissive of missing entries thus avoiding preoccupations of allocating spaces for new indexes.
class Polynomial(object):
def __init__(self, *coeffs):
self.coeffs = {exp:c for exp,c in enumerate(coeffs[::-1])}
def __add__(self, other):
assert type(other) is Polynomial
result = Polynomial(0)
result.coeffs = {**self.coeffs}
for exp,c in other.coeffs.items():
result.coeffs[exp] = result.coeffs.get(exp,0) + c
return result
def __sub__(self, other):
assert type(other) is Polynomial
result = Polynomial(0)
result.coeffs = {**self.coeffs}
for exp,c in other.coeffs.items():
result.coeffs[exp] = result.coeffs.get(exp,0) - c
return result
def __mul__(self, other):
assert type(other) is Polynomial
result = Polynomial(0)
for exp1,c1 in self.coeffs.items():
for exp2,c2 in other.coeffs.items():
result.coeffs[exp1+exp2] = result.coeffs.get(exp1+exp2,0) + c1*c2
return result
def __representation__(self):
return "Polynomial" + str(self.coeffs)
def __str__(self):
result = [""]+[f"{c}x^{i}" for i,c in sorted(self.coeffs.items()) if c]+[""]
result = "+".join(reversed(result))
result = result.replace("+1x","+x")
result = result.replace("-1x","-x")
result = result.replace("x^0","")
result = result.replace("x^1+","x+")
result = result.replace("+-","-")
result = result.strip("+")
result = result.replace("+"," + ")
result = result[:1]+result[1:].replace("-"," - ")
return result.strip()

How to represent complex matrix from 2 real-valued matrices

I'm trying to represent a matrix of complex numbers using 2 real value matrices (in Pytorch, but using numpy here just for illustrative purposes).
Currently I'm doing it this way:
import numpy as np
# represent real
X = np.random.randn(10,10)
# represent imaginary
I = np.random.randn(10,10)
# build complex matrix using the identity
real = np.concatenate([X, -I], axis=-1)
img = np.concatenate([I, X], axis=-1)
complex_W = np.concatenate([real, img,], axis=0)
# is complex_W now correctly represented??
Could I also do it this way?
# represent real
X = np.random.randn(10,10)
# represent imaginary
I = np.random.randn(10,10)
complex_W = X + I
You can implement complex ndarray data structure using numpy arrays. You may want to store real part in one variable of the datasture and complex in anthor variable. Python provides a way to overload some operators including +, -, *, /. E.g I've the following class implements complex data structure with three operators(+, - , *)
class ComplexNDArray(object):
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
#property
def real(self):
return self.__real
#real.setter
def real(self, value):
if type(value) == np.ndarray:
self.__real = value
elif isinstance(value, (int, float, list, tuple)):
self.__real = np.array(value)
else:
raise ValueError("Unsupported type value:%s" % (str(type(value))))
#property
def imaginary(self):
return self.__imaginary
#imaginary.setter
def imaginary(self, value):
if type(value) == np.ndarray:
self.__imaginary = value
elif isinstance(value, (int, float, list, tuple)):
self.__imaginary = np.array(value)
else:
raise ValueError("Unsupported type value:%s" % (str(type(value))))
def __add__(self, other):
real = self.real + other.real
imaginary = self.imaginary + other.imaginary
return ComplexNDArray(real, imaginary)
def __sub__(self, other):
real = self.real - other.real
imaginary = self.imaginary - other.imaginary
return ComplexNDArray(real, imaginary)
def __mul__(self, other):
real = self.real * other.real - self.imaginary * other.imaginary
imaginary = self.real * other.imaginary + self.imaginary * other.real
return ComplexNDArray(real, imaginary)
def __str__(self):
return str(self.real) + "+"+str(self.imaginary)+"i"
Now you can use this data structure to do some operations.
a = np.array([1, 2,3])
b = np.array([4, 5, 1])
c = np.array([4, 7,3])
d = np.array([5, 1,7])
cmplx = ComplexNDArray(a, b)
cmplx2 = ComplexNDArray(c, d)
print(cmplx) # [1 2 3]+[4 5 1]i
print(cmplx2) # [4 7 3]+[5 1 7]i
print(cmplx+cmplx2) # [5 9 6]+[9 6 8]i
print(cmplx-cmplx2) # [-3 -5 0]+[-1 4 -6]i
print(cmplx*cmplx2) # [-16 9 2]+[21 37 24]i

nice decimal.Decimal autonormalization

This gonna be my first question here. I am trying to make a decimal.Decimal child class which mainly differs the parent by making autonormalization on itself and on the results of its callable arguments whose returns Decimal objects. The code below have the concept to
decorate all methods of Decimal to return MyDecimal instances (whose trim zeros of the end of their strings by creation) instead of decimal.Decimals. For this, metaclass was used.
However, I feel this code a bit hacky though. Moreover, according to the speed test results, it is also damn slow: 2.5 secs for the decimal.Decimal vs. 16 secs for MyDecimal on my system.
My question is: Is there a cleaner (and faster) way of doing this?
import decimal
class AutoNormalizedDecimal(type):
def __new__(cls, name, bases, local):
local_items = list(local.items())
parent_items = [i for i in bases[0].__dict__.items()
if i[0] not in local.keys()]
for a in local_items + parent_items:
attr_name, attr_value = a[0], a[1]
if callable(attr_value):
local[attr_name] = cls.decorator(attr_value)
return super(AutoNormalizedDecimal, cls).__new__(
cls, name, bases, local)
#classmethod
def decorator(cls, func):
def wrapper_for_new(*args, **kwargs):
new_string = args[1].rstrip('0').rstrip('.')
if not new_string:
new_string = '0'
newargs = (args[0], new_string)
return func(*newargs, **kwargs)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
if (isinstance(result, decimal.Decimal)
and not isinstance(result, MyDecimal)):
return MyDecimal(str(result))
return result
if func.__name__ == '__new__':
return wrapper_for_new
return wrapper
class MyDecimal(decimal.Decimal, metaclass=AutoNormalizedDecimal):
def __str__(self):
return decimal.Decimal.__str__(self).replace('.', ',')
n = MyDecimal('-5423.5420000')
def speedtest():
import time
start = time.time()
d = decimal.Decimal('6')
for i in range(1000000):
d += decimal.Decimal(str(i))
print(time.time()-start)
start = time.time()
d = MyDecimal('6')
for i in range(1000000):
d += MyDecimal(str(i))
print(time.time()-start)
Here is how this works:
>>> n
Decimal('-5423.542')
>>> type(n)
<class '__main__.MyDecimal'>
>>> str(n)
'-5423,542'
>>> x = MyDecimal('542.63') / MyDecimal('5.2331')
>>> x
Decimal('103.6918843515315969501824922')
>>> type(x)
<class '__main__.MyDecimal'>
>>> y = MyDecimal('5.5252') - MyDecimal('0.0052')
>>> y
Decimal('5.52')
>>> z = decimal.Decimal('5.5252') - decimal.Decimal('0.0052')
>>> z
Decimal('5.5200')
Thanks in advance!
PS: Credit goes to Anurag Uniyal for his code which gave me a way to start: https://stackoverflow.com/a/3468410/2334951
EDIT1: I came out to redefine as_tuple() method which I could call all the time I need the trimmed Decimal version:
class MyDecimal(decimal.Decimal):
def as_tuple(self):
sign, digits_, exponent = super().as_tuple()
digits = list(digits_)
while exponent < 0 and digits[-1] == 0:
digits.pop()
exponent += 1
while len(digits) <= abs(exponent):
digits.insert(0, 0)
return decimal.DecimalTuple(sign, tuple(digits), exponent)
def __str__(self):
as_tuple = self.as_tuple()
left = ''.join([str(d) for d in as_tuple[1][:as_tuple[2]]])
right = ''.join([str(d) for d in as_tuple[1][as_tuple[2]:]])
return ','.join((left, right))

Categories

Resources