def fraction_expansion(n): if n == 0: return _Fraction(1, 1) if n == 1: return _Fraction(3, 2) previous_fraction = fraction_expansion(n - 1) return _Fraction(2 * previous_fraction.numerator + fraction_expansion(n - 2).numerator, previous_fraction.numerator + previous_fraction.denominator)
def bernoulli_number(n): ''' this function returns a bernoulli (B_n) number given n ''' if n == 1: return _Fraction(-1, 2) A = [0] * (n + 1) for m in range(n + 1): A[m] = _Fraction(1, m + 1) for j in range(m, 0, -1): A[j - 1] = j * (A[j - 1] - A[j]) return A[0] # (which is B_n)
def _LUrational(M): _utils.checkSquare(M) A = _np.copy(M) n = len(A) ipiv = _np.zeros(n, dtype=int) info = 0 for k in range(n): kp = k amax = _Fraction(0, 1) for i in range(k, n): absi = abs(A[i, k]) if absi > amax: kp = i amax = absi ipiv[k] = kp if A[kp, k] != 0: if k != kp: # Interchange for i in range(n): tmp = A[k, i] A[k, i] = A[kp, i] A[kp, i] = tmp # Scale first column Akkinv = _reciprocal(A[k, k]) for i in range(k + 1, n): A[i, k] *= Akkinv elif info == 0: info = k for j in range(k + 1, n): for i in range(k + 1, n): A[i, j] -= A[i, k] * A[k, j] return A, ipiv
def generate_pi_axis(start=0, end=2 * _pi, jumps=5): """ Generates an evenly spaced scale, in Pi multiplicities. :param start: A number to start the scale. :param end: A number to end the scale. :param jumps: Number of slices of the scale. :return: A tuple made of two lists, one for actual numbers and one for nicely formatted LaTeX scale. """ jump_size = (end - start) / (jumps - 1) y_ticks = [] y_ticks_labels = [] for y_tick in range(0, jumps): cur_tick = start + jump_size * y_tick y_ticks.append(cur_tick) cur_tick = _Fraction(cur_tick / _pi).limit_denominator(max_denominator=10) if cur_tick.numerator == 0: y_ticks_labels.append("0") elif cur_tick.denominator == 1: y_ticks_labels.append("$%s\\pi$" % (str(cur_tick.numerator))) elif cur_tick.numerator < 0: y_ticks_labels.append( "$-\\frac{%s}{%s}\\pi$" % (str(-cur_tick.numerator), str(cur_tick.denominator))) else: y_ticks_labels.append( "$\\frac{%s}{%s}\\pi$" % (str(cur_tick.numerator), str(cur_tick.denominator))) return y_ticks, y_ticks_labels
def __mul__(self, other): T = type(other) if T is float: out = self.value * _Fraction(other) else: out = self.value * other return RationalMatrix(out)
def _applyIpivRows(A, ipiv): n = len(A) B = _np.identity(n).astype(int) + _Fraction() for i, j in enumerate(ipiv): if i != j: for col in range(n): B[i, col], B[j, col] = B[j, col], B[i, col] return B
def __add__(self, other): T = type(other) if T is RationalMatrix: out = self.value + other.value elif T is float: out = self.value + _Fraction(other) else: out = self.value + other return RationalMatrix(out)
def __radd__(self, other): T = type(other) if T is int or T is _Fraction or T is RationalMatrix: outRa = self + other elif T is float: out = _Fraction(other) + self.value outRa = RationalMatrix(out) else: out = other + self.value outRa = RationalMatrix(out) return outRa
def _ldivLU(A, B, Mtype): _utils.checkSquare(A) nA = len(A) tmp = _np.zeros(nA).astype(int) + _Fraction() nB = len(B) for i in range(nB): _utils.unsafeCopyTo(tmp, 0, B, i * nB, nB) if Mtype is 'L': _utils.naivesubL(A, tmp) elif Mtype is 'U': _utils.naivesubU(A, tmp) _utils.unsafeCopyTo(B, i * nB, tmp, 0, nB) return B.transpose()
def _to_number(x, accept_fractions=True): if _could_be_number(x, accept_fractions=accept_fractions): if '.' in x or x in ('nan', 'inf', '-inf'): return float(x) else: try: return int(x) except: try: return _Fraction(x) except: return x else: return x
def nearest_node(self, note, max_harmonic=16): """ Find node closest to the given position note (str|num) : The position in the string as a note (str or midinumber) max_harmonic (int) : Consider only harmonics lower or equal to this harmonic """ fq = n2f(note) if isinstance(note, str) else m2f(note) if fq < self.freq: raise ValueError("The given note is lower than the fundamental") ratio = _Fraction(self.freq/fq).limit_denominator(max_harmonic) harmonic = ratio.denominator frets = self.find_node(harmonic).frets diff, fret_pos = min((abs(fret.freq - fq), fret) for fret in frets) resulting_freq = self.freq * harmonic return harmonic, Note(f2m(resulting_freq)), fret_pos
def userDefinedLoss(actionNumber, n, **kwargs): verbose = kwargs.get('verbose', False) if verbose: t = kwargs.get('t', None) T = kwargs.get('T', None) x = kwargs.get('x', None) if (t is not None) and (T is not None): print('Percent complete: {}%'.format(_np.round(100*(t+1)/T, 2))) if x is not None: print('Machine\'s pmf over actions is:') print(x) print('Machine selected action {} of {}.'.format(actionNumber, n)) print('How would you like to penalize this action?') userDefinedLoss = input('(Enter a value between 0 and 1): ') userDefinedLoss = float(_Fraction(userDefinedLoss)) userDefinedLoss = _np.maximum(0, _np.minimum(1, userDefinedLoss)) return userDefinedLoss
def _as_number_if_possible(s, accept_fractions=True): """try to convert 's' to a number if it is possible""" if accept_fractions: if "/" in s: try: n = _Fraction("/".join(n.strip() for n in s.split("/"))) return n except: return s try: n = int(s) return n except ValueError: try: n = float(s) return n except ValueError: s return s
def __add__(self, other): T = type(other) if T is int or T is _Fraction: out = self.value + other outRa = RationalVector(out) elif T is float: out = self.value + _Fraction(other) outRa = RationalVector(out) else: if T is RationalVector: out = self.value + other.value else: out = self.value + other if _utils.isVector(out): outRa = RationalVector(out) elif _utils.isSquare(out): outRa = RationalMatrix(out) else: raise ValueError('Dimension mismatch.') return outRa
# This Python file uses the following encoding: utf-8 import numpy as _np from fractions import Fraction as _Fraction from .rk_method import RK_method as _RK RKeuler = _RK(_np.array([[0]], dtype=object), _np.array([1], dtype=object)) RKimplicitEuler = _RK(_np.array([[1]], dtype=object), _np.array([1], dtype=object)) # Also known as backward Euler. RKmidpoint = _RK(_np.array([[0, 0], [_Fraction(1, 2), 0]], dtype=object), _np.array([0, 1], dtype=object)) RKimplicitTrapezoidal = _RK( _np.array([[0, 0], [_Fraction(1, 2), _Fraction(1, 2)]], dtype=object), _np.array([_Fraction(1, 2), _Fraction(1, 2)], dtype=object)) RKimplicitMidpoint = _RK(_np.array([[_Fraction(1, 2)]], dtype=object), _np.array([1], dtype=object)) # The two folloving are given at the top of page 30 in # Hairer, Lubich, Wanner. Due to Runge. RKrunge1 = _RK(_np.array([[0, 0], [1, 0]], dtype=object), _np.array([_Fraction(1, 2), _Fraction(1, 2)], dtype=object)) # Also known as Heun's method. RKrunge2 = _RK(_np.array([[0, 0], [_Fraction(1, 2), 0]], dtype=object), _np.array([0, 1], dtype=object))
def addsub_dimension(x, y): """Returns the unit obtained by adding or subtracting unit ``l`` with unit ``r``. Raises ``DimensionError`` if ``l`` and ``r`` are different. """ if x == y: return x else: raise DimensionError _prefixes_str = "pnum_kMG" _smallest_prefix = _Fraction(1, 10**12) def _format(amount, unit): if amount is NotImplemented: return NotImplemented if unit is None: return amount else: return Quantity(amount, unit) class Quantity: """Represents an amount in a given fundamental unit (identified by a string).
def asfrac(x): return _Fraction(x).limit_denominator(MAX_DENOMINATOR)
def _reciprocal(A): return _Fraction(A._denominator, A._numerator)
def __init__(self, intVector): _utils.checkVector(intVector) self.value = intVector + _Fraction() self.length = len(self.value)
def __init__(self, intMatrix): _utils.checkSquare(intMatrix) self.value = intMatrix + _Fraction() self.length = len(intMatrix)