def zeta(self, n=2): """ Return a root of unity in ``self``. INPUT: - ``n`` -- integer (default: 2) order of the root of unity EXAMPLES:: sage: QQ.zeta() -1 sage: QQ.zeta(2) -1 sage: QQ.zeta(1) 1 sage: QQ.zeta(3) Traceback (most recent call last): ... ValueError: no n-th root of unity in rational field """ if n == 1: return rational.Rational(1) elif n == 2: return rational.Rational(-1) else: raise ValueError, "no n-th root of unity in rational field"
def frac(n, d): """ Return the fraction ``n/d``. EXAMPLES:: sage: from sage.rings.rational_field import frac sage: frac(1,2) 1/2 """ return rational.Rational(n) / rational.Rational(d)
def some_elements(self): r""" Return some elements of `\QQ`. See :func:`TestSuite` for a typical use case. OUTPUT: An iterator over 100 elements of `\QQ`. EXAMPLES:: sage: tuple(QQ.some_elements()) (1/2, -1/2, 2, -2, 0, 1, -1, 42, 2/3, -2/3, 3/2, -3/2, 4/5, -4/5, 5/4, -5/4, 6/7, -6/7, 7/6, -7/6, 8/9, -8/9, 9/8, -9/8, 10/11, -10/11, 11/10, -11/10, 12/13, -12/13, 13/12, -13/12, 14/15, -14/15, 15/14, -15/14, 16/17, -16/17, 17/16, -17/16, 18/19, -18/19, 19/18, -19/18, 20/441, -20/441, 441/20, -441/20, 22/529, -22/529, 529/22, -529/22, 24/625, -24/625, 625/24, -625/24, ...) """ yield self.an_element() yield -self.an_element() yield 1 / self.an_element() yield -1 / self.an_element() yield self(0) yield self(1) yield self(-1) yield self(42) for n in range(1, 24): a = 2 * n b = (2 * n + 1)**(n // 10 + 1) yield rational.Rational((a, b)) yield rational.Rational((-a, b)) yield rational.Rational((b, a)) yield rational.Rational((-b, a))
def _an_element_(self): r""" Return an element of `\QQ`. EXAMPLES:: sage: QQ.an_element() # indirect doctest 1/2 """ return rational.Rational((1, 2))
def getEquilibrium(t, p1SCount): """Returns the equilibrium from the given tableaux. The returned result might contain mixed strategies like (1/3, 0/1), so normalization is need to be performed on the result. t - tableaux (Matrix) p1SCount - number of strategies of player 1 (number) Preconditions: - 0 < p1SCount < t.getNumRows() - first column of the matrix must contain each number from 1 to t.getNumRows (inclusive, in absolute value) Raises ValueError if some of the preconditions are not met. """ # 1st precondition if p1SCount < 0 or t.getNumRows() <= p1SCount: raise ValueError('Invalid number of strategies of player 1.') # 2nd precondition firstColNums = [] for i in range(1, t.getNumRows() + 1): firstColNums.append(abs(t.getItem(i, 1))) for i in range(1, t.getNumRows() + 1): if not i in firstColNums: raise ValueError( 'Invalid indices in the first column of the tableaux.') # I decided to use a list instead of a tuple, because I need # to modify it (tuples are immutable) eqs = t.getNumRows() * [0] # Equilibrium is in the second column of the tableaux for i in range(1, t.getNumRows() + 1): # Strategy strat = t.getItem(i, 1) # Strategy probability prob = t.getItem(i, 2) # If the strategy index or the probability is lower than zero, # set it to zero instead eqs[abs(strat) - 1] = rational.Rational(0) if (strat < 0 or prob < 0) else prob # Convert the found equilibrium into a tuple return (tuple(eqs[0:p1SCount]), tuple(eqs[p1SCount:]))
for elem in diff(a): print('%6.2f' % elem, end=' '.ljust(4)) print(' ') print('Dif of Dif :', end=' '.ljust(10)) for elem in diff(diff(a)): print('%6.2f' % elem, end=' '.ljust(4)) print('\n' * 2, "--------" * 9) ########################### ## Operation on Mixed ########################### an = nom(o) ad = denom(o) frac = vstack((an, ad)) a = [rational.Rational(frac[0][i], frac[1][i]).mixedp() for i in arange(n)] al = [rational.Rational(frac[0][i], frac[1][i]).mixed() for i in arange(n)] print('Num Fract :', end="") for elem in a: print(' %s' % elem, end=' '.ljust(7)) a = [al[i][0] for i in arange(n)] print(' ') print('Whole-Whole:', end=' '.ljust(7)) for elem in diff(a): print('%3.f' % elem, end=' '.ljust(8)) a = [al[i][1] for i in arange(n)] print(' ') print('Num-Num rel:', end=' '.ljust(7))
def makePivotingStep(t, p1SCount, ebVar): """Makes a single pivoting step in the selected tableaux by bringing the selected variable into the basis. All changes are done in the original tableaux. Returns the variable that left the basis. t - tableaux (Matrix) p1SCount - number of strategies of player 1 (number) ebVar - variable that will enter the basis (number) Preconditions: - 0 < abs(ebVar) <= t.getNumRows() - 0 < p1SCount < t.getNumRows() Raises ValueError if some of the preconditions are not met. """ # 1st precondition if abs(ebVar) <= 0 or abs(ebVar) > t.getNumRows(): raise ValueError, 'Selected variable index is invalid.' # 2nd precondition if p1SCount < 0 or t.getNumRows() <= p1SCount: raise ValueError, 'Invalid number of strategies of player 1.' # Returns the column corresponding to the selected variable def varToCol(var): # Apart from players matrices values, there are 2 additional # columns in the tableaux return 2 + abs(var) # Returns the list of row numbers which corresponds # to the selected variable def getRowNums(var): # Example (for a game 3x3): # -1,-2,-3,4,5,6 corresponds to the first part of the tableaux # 1,2,3,-4,-5,-6 corresponds to the second part of the tableaux if -p1SCount <= var < 0 or var > p1SCount: return xrange(1, p1SCount + 1) else: return xrange(p1SCount + 1, t.getNumRows() + 1) # Check which variable should leave the basis using the min-ratio rule # (it will have the lowest ratio) lbVar = None minRatio = None # Check only rows in the appropriate part of the tableaux for i in getRowNums(ebVar): if t.getItem(i, varToCol(ebVar)) < 0: ratio = -rational.Rational(t.getItem(i, 2)) /\ t.getItem(i, varToCol(ebVar)) if minRatio == None or ratio < minRatio: minRatio = ratio lbVar = t.getItem(i, 1) lbVarRow = i lbVarCoeff = t.getItem(i, varToCol(ebVar)) # Update the row in which the variable that will leave the basis was # found in the previous step t.setItem(lbVarRow, 1, ebVar) t.setItem(lbVarRow, varToCol(ebVar), 0) t.setItem(lbVarRow, varToCol(lbVar), -1) for j in xrange(2, t.getNumCols() + 1): newVal = rational.Rational(t.getItem(lbVarRow, j)) / abs(lbVarCoeff) t.setItem(lbVarRow, j, newVal) # Update other rows in the appropriate part of the tableaux for i in getRowNums(ebVar): if t.getItem(i, varToCol(ebVar)) != 0: for j in xrange(2, t.getNumCols() + 1): newVal = t.getItem(i, j) + t.getItem(i, varToCol(ebVar)) *\ t.getItem(lbVarRow, j) t.setItem(i, j, newVal) t.setItem(i, varToCol(ebVar), 0) return lbVar
def main(): """Test the rational.Rational class methods.""" print('This program tests the Rational class.\n') print('Read the output of this program CAREFULLY!\n') number0 = rational.Rational() print('Testing the existence of certain methods...') if hasattr(number0, 'get_numerator'): print('Correct: Has a get_numerator method') else: print('ERROR: Does not have a get_numerator method') if hasattr(number0, 'get_denominator'): print('Correct: Has a get_denominator method') else: print('ERROR: Does not have a get_denominator method') if hasattr(number0, 'set_value'): print('Correct: Has a set_value method') else: print('ERROR: Does not have a set_value method') if hasattr(number0, '__float__'): print('Correct: Has a __float__ method') else: print('ERROR: Does not have a __float__ method') if hasattr(number0, '__add__'): print('Correct: Has a __add__ method') else: print('ERROR: Does not have a __add__ method') if hasattr(number0, '__iadd__'): print('Correct: Has an __iadd__ method') else: print('ERROR: Does not have an __iadd__ method') if hasattr(number0, '__mul__'): print('Correct: Has a __mul__ method') else: print('ERROR: Does not have a __mul__ method') if hasattr(number0, '__imul__'): print('Correct: Has an __imul__ method') else: print('ERROR: Does not have an __imul__ method') if hasattr(number0, '__eq__'): print('Correct: Has an __eq__ method') else: print('ERROR: Does not have an __eq__ method') if hasattr(number0, '__str__'): print('Correct: Has a __str__ method') else: print('ERROR: Does not have a __str__ method') print('\nTesting the constructor and __str__ method:\n') # Created number0 = rational.Rational() above if str(number0) == '0/1': print('Correct: default object = 0/1') else: print('ERROR: default object should be 0/1 but is %s' % number0) number1 = rational.Rational(3) if str(number1) == '3/1': print('Correct: 3 is represented as 3/1') else: print('ERROR: 3 should be represented as 3/1 but is %s' % number1) number2 = rational.Rational(2, 3) if str(number2) == '2/3': print('Correct: 2/3 is represented as 2/3') else: print('ERROR: 2/3 should be 2/3 but is %s' % number2) number3 = rational.Rational(2, 6) if str(number3) == '1/3': print('Correct: 2/6 reduces to 1/3') else: print('ERROR: 2/6 should reduce to 1/3 but is %s' % number3) number4 = rational.Rational(12, 9) if str(number4) == '4/3': print('Correct: 12/9 reduces to 4/3') else: print('ERROR: 12/9 should reduce to 4/3 but is %s' % number4) number5 = rational.Rational(1, -6) if str(number5) == '-1/6': print('Correct: 1/-6 reduces to -1/6') else: print('ERROR: 1/-6 should reduce to -1/6 but is %s' % number5) number6 = rational.Rational(-5, -9) if str(number6) == '5/9': print('Correct: -5/-9 reduces to 5/9') else: print('ERROR: -5/-9 should reduce to 5/9 but is %s' % number6) print('\nAttempting to create a rational number with 0 denominator...') print('Expecting a ValueError...') try: dummy = rational.Rational(5, 0) print('ERROR -- No exception was thrown from the constructor!') except ValueError: print('Correct: Caught a ValueError from the constructor') except Exception: print('ERROR: Wrong type of exception thrown from the constructor') print('\nTesting the accessor and mutator methods:\n') numerator = number1.get_numerator() denominator = number1.get_denominator() if numerator == 3 and denominator == 1: print('Correct: 3/1 has numerator 3 and denominator 1') else: print('ERROR: %s has numerator %d and denominator %d' \ % (number1, numerator, denominator)) numerator = number2.get_numerator() denominator = number2.get_denominator() if numerator == 2 and denominator == 3: print('Correct: 2/3 has numerator 2 and denominator 3') else: print('ERROR: %s has numerator %d and denominator %d' \ % (number2, numerator, denominator)) print('\nChanging 2/3 to 5/4...') number2.set_value(5, 4) if str(number2) == '5/4': print('Correct: 2/3 has been changed to 5/4') else: print('ERROR: 2/3 should have been changed to 5/4 but is %s' \ % number2) print('\nChanging 5/4 to 4/12 = 1/3...') number2.set_value(4, 12) if str(number2) == '1/3': print('Correct: 5/4 has been changed to 1/3') else: print('ERROR: 5/4 should have been changed to 1/3 but is %s' \ % number2) print('\nChanging 1/3 to 4 = 4/1...') number2.set_value(4) if str(number2) == '4/1': print('Correct: 1/3 has been changed to 4/1') else: print('ERROR: 1/3 should have been changed to 4/1 but is %s' \ % number2) print('\nAttempting to set a rational number with 0 denominator...') print('Expecting a ValueError...') dummy = rational.Rational(10) try: dummy.set_value(8, 0) print('ERROR -- No exception was thrown from set_value!') except ValueError: print('Correct: Caught a ValueError from set_value') except Exception: print('ERROR: Wrong type of exception thrown from set_value') print('\nTesting the __float__ method:\n') if float(number1) == 3.0: print('Correct: 3/1 == 3.0') else: print('ERROR: 3/1 = %.6f' % float(number1)) number2 = rational.Rational(2, 3) if float(number2) == 2.0 / 3: print('Correct: 2/3 == 0.6666667') else: print('ERROR: 2/3 = %f' % float(number2)) print('\nTesting the __add__ and __mul__ methods:\n') number1.set_value(1, 3) number2.set_value(1, 6) number3 = number1 + number2 if str(number3) == '1/2': print('Correct: 1/3 + 1/6 = 1/2') else: print('ERROR: 1/3 + 1/6 should be 1/2 but is %s' % number3) number1.set_value(3, 4) number3 = number1 + number2 if str(number3) == '11/12': print('Correct: 3/4 + 1/6 = 11/12') else: print('ERROR: 3/4 + 1/6 should be 11/12 but is %s' % number3) number1.set_value(-5, 4) number2.set_value(6, -8) number3 = number1 + number2 if str(number3) == '-2/1': print('Correct: -5/4 + 6/-8 = -2/1\n') else: print('ERROR: -5/4 + 6/-8 should be -2/1 but is %s\n' % number3) number1.set_value(2, 3) number2.set_value(3, 2) number3 = number1 * number2 if str(number3) == '1/1': print('Correct: 2/3 * 3/2 = 1/1') else: print('ERROR: 2/3 * 3/2 should be 1/1 but is %s' % number3) number2.set_value(1, 2) number3 = number1 * number2 if str(number3) == '1/3': print('Correct: 2/3 * 1/2 = 1/3') else: print('ERROR: 2/3 * 1/2 should be 1/3 but is %s' % number3) number1.set_value(-1, 6) number2.set_value(2, 1) number3 = number1 * number2 if str(number3) == '-1/3': print('Correct: -1/6 * 2/1 = -1/3') else: print('ERROR: -1/5 * 2/1 should be -1/3 but is %s' % number3) print('\nTesting the __iadd__ and __imul__ methods:\n') number1.set_value(1, 3) number2.set_value(1, 6) number1 += number2 if str(number1) == '1/2': print('Correct: 1/3 += 1/6 is 1/2') else: print('ERROR: 1/3 += 1/6 should be 1/2 but is %s' % number1) number1.set_value(3, 4) number1 += number2 if str(number1) == '11/12': print('Correct: 3/4 += 1/6 is 11/12') else: print('ERROR: 3/4 += 1/6 should be 11/12 but is %s' % number1) number1.set_value(-5, 4) number2.set_value(6, -8) number1 += number2 if str(number1) == '-2/1': print('Correct: -5/4 += 6/-8 is -2/1\n') else: print('ERROR: -5/4 += 6/-8 should be -2/1 but is %s\n' % number1) number1.set_value(2, 3) number2.set_value(3, 2) number1 *= number2 if str(number1) == '1/1': print('Correct: 2/3 *= 3/2 is 1/1') else: print('ERROR: 2/3 *= 3/2 should be 1/1 but is %s' % number1) number1.set_value(2, 3) number2.set_value(1, 2) number1 *= number2 if str(number1) == '1/3': print('Correct: 2/3 *= 1/2 is 1/3') else: print('ERROR: 2/3 *= 1/2 should be 1/3 but is %s' % number1) number1.set_value(-1, 6) number2.set_value(2, 1) number1 *= number2 if str(number1) == '-1/3': print('Correct: -1/6 *= 2/1 is -1/3') else: print('ERROR: -1/5 *= 2/1 should be -1/3 but is %s' % number1) print('\nTesting the __eq__ method:\n') number1.set_value(4, 9) number2.set_value(4, 9) if number1 == number2: print('Correct: 4/9 == 4/9') else: print('ERROR: 4/9 != 4/9') number1.set_value(4, 9) number2.set_value(4, 8) if number1 != number2: print('Correct: 4/9 != 4/8') else: print('ERROR: 4/9 == 4/8') number1.set_value(3, 4) number2.set_value(3, 5) if number1 != number2: print('Correct: 3/4 != 3/5') else: print('ERROR: 3/4 == 3/5') number1.set_value(2, 5) number2.set_value(3, 5) if number1 != number2: print('Correct: 2/5 != 3/5') else: print('ERROR: 2/5 == 3/5') print('\n*** End of testing for the Rational class ***\n') print('Note that passing all of these tests provides some confidence') print('but does not necessarily guarantee that all the code is correct.')
def frac(n, d): return rational.Rational(n) / rational.Rational(d)
def _an_element_(self): return rational.Rational((1, 2))
""" 350112 a2 3.py MICHAEL MAGAISA [email protected] """ import rational r1 = rational.Rational(1, 2) print("Initializing 1/2") r2 = rational.Rational(1, 8) print("Initializing 1/8") res = r1 + r2 print(r1, "+", r2, "=", res)