Add some more python features.

save digits as an array and not as a string anymore
This commit is contained in:
Beat Jäckle 2022-08-07 21:01:57 +02:00
parent 08c4a8e832
commit c26239ffa5
2 changed files with 141 additions and 41 deletions

View file

@ -1,4 +1,9 @@
# p-adic-numbers # p-adic-numbers
class for p-adic number fields class for p-adic number fields
fork from https://github.com/meagtan/p-adic-numbers fork from https://github.com/meagtan/p-adic-numbers
Thank you meagtan. He told me by mail, that I can release this project as GPL3+.
This repository is hosted and maintained on https://git.jdmweb2.ch/beat/p-adic-numbers
If you have questions feel free to send me an Email. My address is in the commits.

171
padic.py
View file

@ -1,46 +1,122 @@
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
#
# License: GLP3+
# Copyright 2017 meagtan
# Copyright 2022 Beat Jäckle <beat@git.jdmweb2.ch>
from fractions import Fraction from fractions import Fraction
from sys import maxsize from sys import maxsize
from modp import ModP from modp import ModP
class PAdic: class PAdic:
def __init__(self, p): def __init__(self, p, printInvers=False):
self.p = p self.p = p
self.val = '' # current known value
# current known value
self.digitP = [] # digitP[0]=c_0; digitP[i]=c_i
self.digitN = [] # digitN[0]=c_-1; digitN[i]=c_-1-i
self.prec = 0 # current known precision, not containing trailing zeros self.prec = 0 # current known precision, not containing trailing zeros
self.order = 0 # order/valuation of number self.order = 0 # order/valuation of number
pass # initialize object as subclass perhaps self.printInvers = printInvers
return None
def calc(self, prec):
# First calculation
if len(self.digitN) + len(self.digitP) == 0:
if self.value == 0:
self.zero = True
self.digitP = [0]
return None
if self.order < 0:
absorder = abs(self.order)
self.digitN = [None]*absorder
for i in range(absorder):
self.digitN[absorder-i-1] = self._nextdigit()
if absorder >= prec:
self.prec = absorder
self.digitP.append(self._nextdigit())
elif self.order > 0:
self.digitP = [0]*self.order
while len(self.digitN) + len(self.digitP) < prec:
if self.value == 0:
break
self.digitP.append(self._nextdigit())
return None
def get(self, prec, decimal=True): def get(self, prec, decimal=True):
self.calc(prec)
'Return value of number with given precision.' 'Return value of number with given precision.'
while self.prec < prec: s = ''
# update val based on value for d in self.digitP[::-1]:
self.val = str(int(self._nextdigit())) + self.val s += str(d)
self.prec += 1 if self.digitN:
if self.order < 0: if decimal:
return ( s += '.'
self.val[:self.order] + ('.' if decimal else '') + for d in self.digitN:
self.val[self.order:])[-prec-1:] s += str(d)
return (self.val + self.order * '0')[-prec:] return s
def _nextdigit(self): def _nextdigit(self):
'Calculate next digit of p-adic number.' 'Calculate next digit of p-adic number.'
raise NotImplementedError raise NotImplementedError
def getdigit(self, index): def getdigit(self, index):
'Return digit at given index.' if index < self.order:
return int(self.get(index + 1, False)[0]) # print('not relevant 0')
# int( return 0
# self.get(index+1+int(index < -self.order)
# )[-int(index < -self.order)]) # be sure to calculate the digits
prec = index+1
if self.order < 0:
prec += abs(self.order)
self.calc(prec)
# negative index
if index < 0:
try:
return self.digitN[abs(index)-1]
except IndexError:
print('Should not happen', index)
print('__dict__', self.__dict__())
raise IndexError(
f"Digit not Found\n"
f"index: {index}\n"
f"dict: {self.__dict__()}"
)
# positive index
else:
try:
return self.digitP[index]
except IndexError:
if self.value == 0:
# print('not significant',0)
return 0
else:
print('Logical Error')
print(f'Index = {index}')
print(f'pAdic = {self.__dict__()}')
raise ValueError('Logical Error')
# return value with precision up to 32 bits # return value with precision up to 32 bits
def __int__(self): def __int__(self):
return int(self.get(32), self.p) return int(self.get(32), self.p)
def __getitem__(self, index):
return self.getdigit(index)
def __str__(self): def __str__(self):
if self.printInvers:
return self.get(32)[::-1]
return self.get(32) return self.get(32)
def __repr__(self):
return str(self)
# arithmetic operations # arithmetic operations
def __neg__(self): def __neg__(self):
return PAdicNeg(self.p, self) return PAdicNeg(self.p, self)
@ -74,20 +150,36 @@ class PAdic:
denom = self.p ** self.order denom = self.p ** self.order
return Fraction(numer, denom) return Fraction(numer, denom)
# determines the p-value of an p-adic number
def pValue(self):
return self.order
def fractionvalue(self):
self.calc(1)
s = Fraction(0)
for (i, d) in enumerate([self.digitP[0]]+self.digitN):
s += Fraction(d, self.p**i)
return s
def getOffset(self):
if self.order >= 0:
return 0
else:
return -self.order
class PAdicConst(PAdic): class PAdicConst(PAdic):
def __init__(self, p, value): def __init__(self, p, value, printInvers=False):
PAdic.__init__(self, p) super().__init__(p, printInvers)
value = Fraction(value) value = Fraction(value)
# calculate valuation # calculate valuation
if value == 0: if value == 0:
self.value = value self.value = value
self.val = '0' self.order = float('inf')
self.order = maxsize self.zero = True
return return None
self.order = 0
while not value.numerator % self.p: while not value.numerator % self.p:
self.order += 1 self.order += 1
value /= self.p value /= self.p
@ -95,8 +187,7 @@ class PAdicConst(PAdic):
self.order -= 1 self.order -= 1
value *= self.p value *= self.p
self.value = value self.value = value
return None
self.zero = not value
def get(self, prec, decimal=True): def get(self, prec, decimal=True):
if self.zero: if self.zero:
@ -105,18 +196,21 @@ class PAdicConst(PAdic):
def _nextdigit(self): def _nextdigit(self):
'Calculate next digit of p-adic number.' 'Calculate next digit of p-adic number.'
rem = ModP(self.p, self.value.numerator) /\ rem = int(
ModP(self.p, self.value.denominator) ModP(self.p, self.value.numerator) *
self.value -= int(rem) ModP(self.p, self.value.denominator)._inv()
)
self.value -= rem
self.value /= self.p self.value /= self.p
return rem return rem
class PAdicAdd(PAdic): class PAdicAdd(PAdic):
'Sum of two p-adic numbers.' 'Sum of two p-adic numbers.'
def __init__(self, p, arg1, arg2): def __init__(self, p, arg1, arg2, printInvers=False):
PAdic.__init__(self, p) super.__init__(self, p, printInvers)
self.carry = 0 self.carry = 0
_nextdigitCache = []
self.arg1 = arg1 self.arg1 = arg1
self.arg2 = arg2 self.arg2 = arg2
# might be larger than this # might be larger than this
@ -124,16 +218,17 @@ class PAdicAdd(PAdic):
arg1.order -= self.order arg1.order -= self.order
arg2.order -= self.order arg2.order -= self.order
# loop until first nonzero digit is found # loop until first nonzero digit is found
self.index = 0 self.index = self.order
digit = self._nextdigit() digit = self._nextdigit()
while digit == 0: while digit == 0:
self.index += 1 self.index += 1
self.order += 1
digit = self._nextdigit() digit = self._nextdigit()
self.val += str(int(digit)) self.order = self.index
self.prec = 1 _nextdigitCache.append(digit)
def _nextdigit(self): def _nextdigit(self):
if _nextdigitCache:
return _nextdigitCache.pop()
s = self.arg1.getdigit(self.index) + \ s = self.arg1.getdigit(self.index) + \
self.arg2.getdigit(self.index) + self.carry self.arg2.getdigit(self.index) + self.carry
self.carry = s // self.p self.carry = s // self.p
@ -143,16 +238,16 @@ class PAdicAdd(PAdic):
class PAdicNeg(PAdic): class PAdicNeg(PAdic):
'Negation of a p-adic number.' 'Negation of a p-adic number.'
def __init__(self, p, arg): def __init__(self, p, arg, printInvers=False):
PAdic.__init__(self, p) super.__init__(self, p, printInvers)
self.arg = arg self.arg = arg
self.order = arg.order self.order = arg.order
def _nextdigit(self): def _nextdigit(self):
if self.prec == 0: if self.prec == 0:
# cannot be p, 0th digit of arg must be nonzero # cannot be p, 0th digit of arg must be nonzero
return self.p - self.arg.getdigit(0) return self.p - self.arg.getdigit(0 - self.getOffset())
return self.p - 1 - self.arg.getdigit(self.prec) return self.p - 1 - self.arg.getdigit(self.prec - self.getOffset())
class PAdicMul(PAdic): class PAdicMul(PAdic):