def test_generator(self): appear = {'Tzmin' : fr(1,3), 'Tzmax' : fr(2,3)} process = {'Tzmin' : fr(1,1), 'Tzmax' : fr(6,1)} testing_subject = cs.generate_programm(appear, process) while(): print(testing_subject())
def lagrangePolySpecialised(xs,ys): ''' Lagrange interpolating polynomial, restricted to points on the integers 1,...,n. I.e. the xs argument is assumed to represent the integers 1 to n and the ys are assumed to be integer values. ''' if len(xs) == 1: return [ fr(ys[0],1) ] a,b = 0, len(xs)-1 aa, bb = math.factorial(a), math.factorial(b) denom = pow(-1L, len(xs)-1)*aa*bb # lagrange poly is a sum of products. Each one has a denominator of the form # m! n! (-1)^n where m+n+1 = no of points. (I think) # Accumulate the coefficients as fractions. fracSum = [ fr(0,1) ] * len(xs) for k in range(len(xs)): # Find numerator term, this is a polynomial whose roots are the x values # except for one (the k index one). xx = xs[:k] + xs[k+1:] p = np.poly1d(xx,True) pCoeffs = map(long, p.coeffs) coeffFracs = map(lambda u: fr(u*ys[k], denom) , pCoeffs) summands = zip(fracSum, coeffFracs) fracSum = [x + y for (x,y) in summands] a = a + 1 denom = -1L * denom * a / b b = max(1, b - 1) return fracSum
def q(i): a=fr(4,1) b=fr(425,100) for j in range(i): c=fr(108,1)-(fr(815,1)-fr(1500,1)/a)/b a,b=b,c a=a.limit_denominator() print('предел последовательности', a)
def backward_substitution(U, y): n = np.shape(y)[0] x = np.zeros([n, 1], fr) for i in reversed(range(n)): temp = 0 for j in reversed(range(i + 1, n)): temp += U[i, j] * x[j, 0] x[i, 0] = fr(y[i, 0] - temp) / fr(U[i, i]) return x
def divide_pie(groups): quantity = sum(abs(x) for x in groups) results = [fr(1)] for g in groups: if g < 0: results.append(results[-1] * fr(quantity + g, quantity)) else: results.append(results[-1] - fr(g, quantity)) return [[f.numerator, f.denominator] for f in results]
def lagrange(xl, yl): k = len(xl) L = P([fr(0, 1)]) for j in range(k): lj = P([fr(1, 1)]) xj = xl[j] for i in range(k): xi = xl[i] if i != j: lj = lj * P([fr(- xi, xj - xi), fr(1, xj - xi)]) L = L + fr(yl[j], 1) * lj return L
def mean_mode(): a=[12,15,10,3,5] print (st.mean(a)) #mean tính giá trị trung bình a=[fr(12.35),fr(1.54),fr(2,17),fr()] print (st.mean(a)) data_points = [ ran.randint(1, 100) for x in range(1,1001) ] print (st.mean(data_points)) data_points = [ ran.triangular(1, 100, 80) for x in range(1,1001) ] print (st.mean(data_points)) print(st.mode(["cat", "dog", "dog", "cat", "monkey", "monkey", "dog"]))
def expression(): #随机生成表达式 symbol = ['+', '-', '*', '/'] brackets = ['(', '', ')'] # 随机产生计算符 s1 = randint(0, 2) s2 = randint(0, 3) s3 = randint(0, 3) #随机产生括号bt表示左括号,br表示右括号 bt1 = randint(0, 1) bt2 = randint(0, 1) bt3 = randint(0, 1) br1 = randint(1, 2) br2 = randint(1, 2) br3 = randint(1, 2) if bt1 == 0: bt2 = 1 bt3 = 1 if br1 == 2: br2 = 1 br3 = 1 else: br2 = 2 br3 = 1 else: if bt2 == 0: bt3 = 1 br1 = 1 if (br2 == 2): br3 = 1 else: br3 = 2 else: bt3 = 0 br1 = 1 br2 = 1 br3 = 2 num1 = uf(0, 1) # 对随机产生的分子分母做最大限制 num1 = fr(num1).limit_denominator(10) num2 = uf(0, 1) num2 = fr(num2).limit_denominator(10) num3 = randint(1, 10) num4 = randint(1, 10) # 产生随机表达式 ran_exp = brackets[bt1] + str(num1) + symbol[s1] + brackets[bt2] + str(num2) + brackets[br1] + \ symbol[s2] + brackets[bt3] + str(num3) + brackets[br2] + symbol[s3] + str(num4) + brackets[br3] ran_exp = str(ran_exp) return ran_exp
def inverse(material): tmat = transposition(material) mat_inv = [] for i in range(len(tmat)): values = [fr(int(i == j), 1) for j in range(len(material))] mat_inv.append(gauss_theme(tmat, values)) return mat_inv
def _calc_quantity(self, e): day = self.days.Value dosage = self.dosage_per.Value time = self.times.Value drug = self.drugpicker.drugWH try: assert day != 0 assert dosage != '' assert time != '' assert drug is not None day = int(day) time = int(time) if "/" in dosage: dosage = fr(dosage) elif "." in dosage: dosage = float(dosage) else: dosage = int(dosage) if drug.sale_unit == 'chai': qty = '1' else: qty = math.ceil(dosage * time * day) self.quantity.ChangeValue(str(qty)) self.usage.ChangeValue("Ngày {} {} lần, lần {} {}".format( drug.usage, time, dosage, drug.usage_unit)) except AssertionError: pass
def form_change(material): new_list = list(map(sum, material)) boolean_indices = list(map(lambda x: x == 0, new_list)) indices = set([i for i, x in enumerate(boolean_indices) if x]) new_material = [] for i in range(len(material)): new_material.append( list( map( lambda x: fr(0, 1) if (new_list[i] == 0) else observe(x, new_list[i]), material[i]))) transform_material = [] zeros_mat = [] for i in range(len(new_material)): if i not in indices: transform_material.append(new_material[i]) else: zeros_mat.append(new_material[i]) transform_material.extend(zeros_mat) tmat = [] for i in range(len(transform_material)): tmat.append([]) extend_mat = [] for j in range(len(transform_material)): if j not in indices: tmat[i].append(transform_material[i][j]) else: extend_mat.append(transform_material[i][j]) tmat[i].extend(extend_mat) return [tmat, len(zeros_mat)]
def PageRank(input_network, d=fr(17,20), iter_limit=1000, p=1000000000): '''1/p is proportional difference threshold between iterations i.e. |old-new|/old. iteration stops when iter_limit is reached or the largest proportional difference is less than 1/p.''' #First we check out input, make sure it's well-formed if d<=0 or d>1: raise ValueError('invalid value "'+str(d)+'" for d; must be in (0,1]') if p!=int(p) or p<1: raise ValueError(p,'must be a natural number (ideally a large one).') net = open(input_network,'r').read().splitlines() n = len(net) if any([len(row)!=n or any([char!='1' and char!='0' for char in row]) for row in net]): raise TypeError('PageRank input must be a square of 1\'s and 0\'s.') if any([net[i][i]!='0' for i in range(n)]): raise TypeError('Pages can\'t link to themselves.') #Next, we set up the initial state, in the form of dictionaries #vertex to outgoing link count first outgoing = dict([(i,sum([int(char) for char in net[i]])) for i in range(n)]) old = dict([(i,fr(1,n)) for i in range(n)])#vertex to current value new = dict()#vertex to new value D = fr(1-d,n) #Finally, the core of the algorithm i = 0 while i < iter_limit: new = dict([ (i, D+d*sum([int(net[j][i])*old[j]/outgoing[j] for j in range(n)]) ) for i in range(n) ]) if p==0 and new==old: break elif all([ abs((old[i]-new[i])/old[i]) < fr(1,p) for i in range(n) ]): break old = copy(new) i += 1 if i==iter_limit: print('Warning: iter_limit reached. Series did not converge.') else: print('Iteration count:',i) for i in range(n): print('PR('+str(i)+') = '+str(round(float(new[i]),4))) return new
def copy_material(material): c_material = [] for i in range(len(material)): c_material.append([]) for j in range(len(material[i])): c_material[i].append( fr(material[i][j].numerator, material[i][j].denominator)) return c_material
def forward_substitution(L, b): n = np.shape(b)[0] y = np.zeros([n, 1], fr) for i in range(n): temp = 0 for j in range(i): temp += L[i, j] * y[j, 0] y[i, 0] = fr(b[i, 0] - temp) return y
def material_multiplication(mat1, mat2): res = [] for i in range(len(mat1)): res.append([]) for j in range(len(mat2[0])): res[i].append(fr(0, 1)) for k in range(len(mat1[0])): res[i][j] += mat1[i][k] * mat2[k][j] return res
def lu_factor(A): [n, n1] = np.shape(A) if n != n1: print("Error: Squared matrix needed") L = np.eye(n, n, 0, fr) U = np.zeros([n, n], fr) for i in range(n): for j in range(i, n): temp = fr(0) for k in range(i): temp += L[i, k] * U[k, j] U[i, j] = A[i, j] - temp for j in range(i + 1, n): temp = fr(0) for k in range(i): temp += L[j, k] * U[k, i] L[j, i] = A[j, i] - temp L[j, i] = L[j, i] / U[i, i] return [L, U]
def hilbert(n): hilber_fr = np.ones([n, n], fr) for i in range(n): for j in range(n): hilber_fr[i, j] = 1 / fr(i + j + 1) hilbert_float = np.ones([n, n], float) for i in range(n): for j in range(n): hilbert_float[i, j] = 1 / (i + j + 1) print("H * myinverse(H): ") printFractionMatrix(np.dot(hilber_fr, myinverse(hilber_fr))) print("H * inv(H): ") hinv = np.linalg.inv(hilbert_float) printFractionMatrix(np.dot(hilbert_float, hinv))
def interpolate(pointList): size = len(pointList) if len(pointList) == 1: return (fr(pointList[0][1]),) result = [fr(0)] for index_i in range(0, size): x_i = fr(pointList[index_i][0]) y_i = fr(pointList[index_i][1]) member = [y_i] for index_j in range(0, size): if index_i == index_j: continue x_j = fr(pointList[index_j][0]) member = polymul(member, [-x_j, fr(1)]) multiplier = [fr(1, x_i - x_j)] member = polymul(member, multiplier) result = polyadd(result, member) return result
def random_linedrug(k=10): li = [] for i in range(k): for j in sample(list(range(15)), k=choices([1, 2, 3])[0]): a = choices(['1/3', '0.5', '2'])[0] b = choices([1, 2, 3])[0] try: quantity = float(a) * b except ValueError: quantity = fr(a) * b if sample_drugs[j][3] == "chai": quantity = 1 li.append( LineDrug( drug_id=j + 1, dosage_per=a, times=b, quantity=math.ceil(quantity), usage= f"Ngày {sample_drugs[j][5]} {b} lần, lần {a} {sample_drugs[j][2]}", visit_id=i + 1)) return li
def fraccionmulti(): num1 = fr(simpledialog.askstring("FRACCIONES", "Ingresa el primer numero")) num2 = fr(simpledialog.askstring("FRACCIONES", "Ingresa el segundo numero")) output = num1*num2
""" This module defines the way expressions are built, relative to the syntax of the C operators. You can modify then to change the way expressions are created. However, do not change their names, since a naming convention is used (i.e., reflection). """ from fractions import Fraction as fr ### # Lvalue operators ### array_lvalue_operators = { ('*', 1): fr('1/4'), ('->', 1): fr('1/4'), ('.', 1): fr('1/4'), ('[]', 2): fr('1/4') } if array_lvalue_operators: assert sum(array_lvalue_operators.values()) == 1 bool_lvalue_operators = { ('*', 1): fr('1/4'), ('->', 1): fr('1/4'), ('.', 1): fr('1/4'), ('[]', 2): fr('1/4') } if bool_lvalue_operators: assert sum(bool_lvalue_operators.values()) == 1
generation = 1 timeOfLastUpdate = time.process_time() endAfter = time.process_time( ) + allowedTime #marks the point when this should stop, by taking the process clock startTime = endAfter - allowedTime lastImprovement = 0.0 #before the loop, and adding the number of seconds allowed bestOf = [parents[0]] #saves the best of each generation for later display while time.process_time() < endAfter: #has the clock hit the ending yet? kids = parents[:preserve] #keep the top however many #culling step parents = parents[:-1 * cull] #big change to this version: make it so the actual cost of the parents is used in generating rank, #not just their position. invertedCost = [] #takes the "fitness" function role totalInvertedCost = fr() #makes the starting total inverted cost be zero for par in parents: temp = fr( 1, int(par.getCost()) ) #the int is just so that I'm sure the fraction class won't complain invertedCost.append(temp) totalInvertedCost += temp while len(kids) < populationSize and time.process_time( ) < endAfter: #makes sure to break out if spent too much time #get the parent IDs #first parent parentIndex1 = 0 #make a random fraction between 0 and just less than the total inverted cost generatingNumber = fr(RNG.randrange(totalInvertedCost.numerator), totalInvertedCost.denominator)
def Maximizar(self): self.ids.generarTabla.disabled = True newfMap = self.fMap #Numero de filas y columnas de la tabla Nfilas = self.restricciones+3 Ncolumnas = self.restricciones + self.variables + 2 #escogemos la ultima fila codeUfila = newfMap[Nfilas] #escoger al mayor de la ultima fila UfilaArr =[] for i in codeUfila: uf = fr(i.text) UfilaArr.append(uf) #se le suma uno mas por que los demas arrays tiene en la posicion 0 el numero que se cambia al final UfMayor = np.argmax(UfilaArr) +1 #escoger los pivotes que dependen del el valor mayor de la ultima fila en la posicion UfMayor #pivotes va a contener la colunma de posicion UfMayor pivotes = [] #reccoro cada fila sin tomar en cuenta las 2 primeras y las dos ultimas for i in newfMap: if i>1 and i<Nfilas-1: #reccoro cada columna escogiendo solo la de la posicion UfMayor que es el mayor for idx,j in enumerate(newfMap[i]): if idx==UfMayor: frac = fr(j.text) pivotes.append(frac) #con los pivotes optenidos se pasa a dividir todas las filas # y guardarlos en un array para saber la columna Bi menor MapBiMenor={} for i in newfMap: if i>1 and i<Nfilas-1: ArrBiMenor=[] for idx,j in enumerate(newfMap[i]): col = fr(j.text) division = col/pivotes[i-2] ArrBiMenor.append(division) MapBiMenor[i-2]=ArrBiMenor #una ves separado y dividio cada fila para su pivote #tengo que buscar el menor de la ultima columna Ncolumnas o Bi guardandolo en un arreglo ArrBiMenor2 = [] for i in MapBiMenor: for idx,j in enumerate(MapBiMenor[i]): #restamos 1 a las columnas por que hay una colunma que no esta incluida if idx == Ncolumnas-1: ArrBiMenor2.append(j) #obtengo la posicion del menor pero como estamos trabajando en la tabla necesito aumentar las # dos filas iniciales idxBiMenor= np.argmin(ArrBiMenor2)+2 #ahora cambiamos los valores toda la fila por la fila de la posicion idxBiMenor #reccoremos cada fila del mapa princial excepto las 2 primeras y 2 ultimas # crear una arreglo para guardar la fila de Bi menor filaBiMenor =[] for i in self.fMap: if i>1 and i<Nfilas-1: if idxBiMenor == i: for idx,j in enumerate(self.fMap[i]): if idx ==0: #reemplazamos el valor de la fila 0 con la columna mayor a la fila menor fraction = fr(self.fMap[0][UfMayor-1].text) numerador = fraction.numerator denomina = fraction.denominator value = numerador if denomina == 1 else fraction j.text= str(value) filaBiMenor.append(value) else: fraction = MapBiMenor[i-2][idx] numerador = fraction.numerator denomina = fraction.denominator value = numerador if denomina == 1 else f'{numerador}/{denomina}' j.text= str(value) filaBiMenor.append(fraction) #ahora vamos a recorrer todas las filas para las iteracciones sin toca la fila que ya se cambio for i in self.fMap: if i>1 and i<Nfilas-1: if idxBiMenor != i: for idx,j in enumerate(self.fMap[i]): if idx !=0: pivoNeg = -pivotes[i-2] multBiPivo = filaBiMenor[idx]*pivoNeg colIter= fr(j.text) suma = multBiPivo + colIter j.text= str(suma) #una vez calculado las filas se pasa a calcular Zj #zj es la multiplicacion de la columa 0 para sus filas y el resultado de cada columna se suma columna0=[] for i in self.fMap: if i>1 and i<Nfilas-1: for idx,j in enumerate(self.fMap[i]): #print(filas) if idx==0: #este es el valor de la columna 0 fract = fr(j.text) columna0.append(fract) filasmultiplicadas ={} for i in self.fMap: if i>1 and i<Nfilas-1: arrfilasMul=[] for idx,j in enumerate(self.fMap[i]): #print(filas) if idx!=0: fi = columna0[i-2] fc = fr(j.text) mult = fi*fc arrfilasMul.append(mult) else: frac = fr(j.text) arrfilasMul.append(frac) filasmultiplicadas[i-2]=arrfilasMul nZj=0 for i in filasmultiplicadas: nZj+=np.array(filasmultiplicadas[i]) Zj =nZj.tolist() #reeplazar en la tabla for i in self.fMap: if i==Nfilas-1: for idx,j in enumerate(self.fMap[i]): #print(Zj,Zj[idx+1],j) fraction =Zj[idx+1] numerador = fraction.numerator denomina = fraction.denominator value = numerador if denomina ==1 else f'{numerador}/{denomina}' j.text = str(value) if i== Nfilas: for idx,j in enumerate(self.fMap[i]): c0 = fr(self.fMap[0][idx].text) filantepe = fr(self.fMap[i-1][idx].text) resta = c0-filantepe numerador = resta.numerator denomina = resta.denominator value = numerador if denomina ==1 else f'{numerador}/{denomina}' j.text=str(value) CjZj = self.fMap[Nfilas] arrCjZj = [] for i in CjZj: fraction = fr(i.text) arrCjZj.append(fraction) a = np.array(arrCjZj) termina = (a<=0).all() if termina: self.show_alert_dialog()
def observe(x, y): g = gcd(x, y) return fr(long(x / g), long(y / g))
for index_i in range(0, size): x_i = fr(pointList[index_i][0]) y_i = fr(pointList[index_i][1]) member = [y_i] for index_j in range(0, size): if index_i == index_j: continue x_j = fr(pointList[index_j][0]) member = polymul(member, [-x_j, fr(1)]) multiplier = [fr(1, x_i - x_j)] member = polymul(member, multiplier) result = polyadd(result, member) return result polynom = map(lambda e: {True: 1, False: -1}[e%2 == 0], range(0, 11)) result = 0 length = len(polynom) valueList = map(lambda e: (fr(e), polyval(fr(e), polynom)), range(1, length+1)) #print valueList for i in range(0, len(polynom)): pointList = valueList[:i+1] #print pointList interpolation = interpolate(pointList) for (x, y) in valueList: interpolated = polyval(x, interpolation) if (interpolated != y): result += interpolated break print result
from fractions import Fraction as fr import cs #вывести сюда все константы из условия appear = {'Tzmin': fr(1, 3), 'Tzmax': fr(2, 3)} process = {'Tzmin': fr(1, 1), 'Tzmax': fr(6, 1)} def main(): now = cs.generate_programm() while cs.time <= 3600: pass print(now) if __name__ == '__main__': main()
"""Square root convergents Problem 57 It is possible to show that the square root of two can be expressed as an infinite continued fraction. 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213... By expanding this for the first four iterations, we get: 1 + 1/2 = 3/2 = 1.5 1 + 1/(2 + 1/2) = 7/5 = 1.4 1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666... 1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379... The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion, 1393/985, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator. In the first one-thousand expansions, how many fractions contain a numerator with more digits than denominator?""" from fractions import Fraction as fr count = 0 x = fr(3, 2) y = fr(7, 5) for i in range(3, 1000): temp = y new_number = fr(x.numerator + y.numerator + y.numerator, x.denominator + 2 * y.denominator) x = temp y = new_number if len(str(x.numerator)) > len(str(x.denominator)): count += 1 print count
def simplify(txt): return str(fr(txt))
# Start of list for returned values returned values val = [cs[0]] * nx # Iteratively calculate polynomial values for c in cs[1::]: for i in range(nx): val[i] = val[i] * x[i] + c return val ################################################## coeffs = np.ones((1,11), dtype=np.longlong)[0] coeffs[1::2] = -1L p = np.poly1d(coeffs) x = map(lambda x: fr(x), range(1,12)) y = p(x) print 'degree 10 polynomial' print p print 'x locations (integers)' print x print 'Values of degree 10 polynomial ' print y sumFITs = 0L for n in range(1,len(x)): p2 = lagrangePolySpecialised(x[0:n],y[0:n]) print 'degree :' , n-1
# m is remainder now, process # same as Euclid's algo m = a % m a = t t = y # Update x and y y = x - q * y x = t # Make x positive if (x < 0): x = x + m0 return x for i in range(int(input())): n, k, m = [int(j) for j in input().split()] sum = fr(1) / fr(n) mult = fr(n - 1) / fr(n) n += k for j in range(m - 1): if (j < m - 2 and n > k): n -= k else: sum = fr(sum) + (fr(mult) * (fr(1) / fr(n))) mult = fr(mult) * (fr(n - 1) / fr(n)) n += k print(round((sum.numerator * modi(sum.denominator, l)) % l))
p = power(x, y // 2, m) % m p = (p * p) % m if (y % 2 == 0): return p else: return ((x * p) % m) # Function to return gcd of a and b def gcd(a, b): if (a == 0): return b return gcd(b % a, a) # This code is contributed by Nikita Tiwari. for i in range(b): q = int(input()) #ans=2**(countSetBits(q))-1 ans = 0 for jj in arr: if jj | q == q: ans += 1 new = fr(ans, a) aa = modInverse(new.denominator, m) print(aa * ans.numerator % m)
def test_fr_dec(): print (fr(1.13)) getcontext().prec = 6 #using decimal * print (dec(1)/dec(7))
def fraccionresta(): num1 = fr(simpledialog.askstring("FRACCIONES", "Ingresa el primer numero")) num2 = fr(simpledialog.askstring("FRACCIONES", "Ingresa el segundo numero")) output = num1-num2 messagebox.showinfo("Resultado",(str(output)))
from statistics import mean from fractions import Fraction as fr data1 = (11, 3, 4, 5, 7, 9, 2) data2 = (-1, -2, -4, -7, -12, -19) data3 = (-1, -13, -6, 4, 5, 19, 9) data4 = (fr(1, 2), fr(44, 12), fr(10, 3), fr(2, 3)) data5 = {1:"one", 2:"two", 3:"three"} print("Mean of data set 1 is % s" % (mean(data1))) print("Mean of data set 2 is % s" % (mean(data2))) print("Mean of data set 3 is % s" % (mean(data3))) print("Mean of data set 4 is % s" % (mean(data4))) print("Mean of data set 5 is % s" % (mean(data5))) #data = [2,3,6,4,7,5] #x = statistics.mean(data) #print("Mean is :",x)
def answer(eq): #利用eval算出表达式答案 aws = fr(eval(eq)).limit_denominator( 1000) #eval()函数用来执行一个字符串表达式,并返回表达式的值,limit_denominator求近似值 answer = str(aws) return (answer)
from puiseuxPoly import puiseux from mypoly import mypoly from expandParallel import solutionList from fractions import Fraction as fr import cPickle if __name__=='__main__': p = mypoly({0:puiseux({5:1}),1:puiseux({fr(7,2):1}),2:puiseux({1:1}),3:puiseux({-1:1}),5:puiseux({fr(-1,2):1}),6:puiseux({fr(1,2):1}),7:puiseux({fr(10,3):1}),8:puiseux({fr(5,2):1})}) p = mypoly({0:puiseux({0:(0.602188930612+0.991723585529j)}),4:puiseux({3:0.991343060948+0.811367139699j})}) p = cPickle.load(open("failurePoly.p","rb")) n=4 sols = solutionList(p,n,True) for sol in sols: expList = [p(sol.trunc(j)).order() for j in xrange(1,len(sol.internal))] print sol.trunc(1),'\r\t\t\t\t\t\t',[str(item) for item in expList]
def cfe(g): p, q, r, s = 0, 1, 1, 0 for α, b in g: p, q, r, s = r, s, r * b + p * α, s * b + q * α yield fr(r, s)