def testMul(self): self.assertEqual(1, Rational(2,3) * Rational(3,2)) self.assertEqual(Rational(26,18), Rational(13,18) * 2) self.assertEqual(500000000000000000000000000000000000000, 1000000000000000000000000000000000000000 * Rational(1,2)) self.assertEqual(Rational(1, 36), Rational(1,2) * Rational(1,3) * Rational(1,6)) ## self.assertEqual(Rational(1,4), Rational(1,2) * 0.5) ## self.assertEqual(Rational(1,4), 0.5 * Rational(1,2)) self.assertEqual(0.25, Rational(1,2) * 0.5) self.assertEqual(0.25, 0.5 * Rational(1,2)) self.assertEqual(Float(0.25), Rational(1,2) * Float(0.5)) self.assertEqual(Float(0.25), Float(0.5) * Rational(1,2))
def e3(x): """ 0 = x[0] + x[1]*t + x[2]*t**2 + x[3]*t**3 """ x3 = Float(x[3]) a = x[2] / x3 b = x[1] / x3 c = x[0] / x3 p = b - (a**2) / 3 q = 2 * (a**3) / 27 - a * b / 3 + c w = (-1 + cmath.sqrt(-3)) / 2 W = (1, w, w.conjugate()) k = -q / 2 + cmath.sqrt((q**2) / 4 + (p**3) / 27) l = -q / 2 - cmath.sqrt((q**2) / 4 + (p**3) / 27) m = k**(1 / 3) n = l**(1 / 3) # choose n*W[i] by which m*n*W[i] be the nearest to -p/3 checker = [abs(3 * m * n * z + p) for z in W] n = n * W[checker.index(min(checker))] sol = [] for i in range(3): sol.append(W[i] * m + W[-i] * n - a / 3) return sol
def __init__(self, value): """ value will be wrapped in Float. """ ring.FieldElement.__init__(self) if isinstance(value, rational.Rational): self.data = value.toFloat() else: self.data = Float(value)
def Newton(f, initial=1, repeat=250): """ Compute x s.t. 0 = f[0] + f[1] * x + ... + f[n] * x ** n """ length = len(f) df = [] for i in range(1, length): df.append(i * f[i]) l = initial for k in range(repeat): coeff = Float(0) dfcoeff = Float(0) for i in range(1, length): coeff = coeff * l + f[-i] dfcoeff += dfcoeff * l + df[-i] coeff = coeff * l + f[0] if coeff == 0: return l elif dfcoeff == 0: # Note coeff != 0 raise ValueError( "There is not solution or Choose different initial") else: l = l - coeff / dfcoeff return l
def createElement(self, seed): return Float(seed)
def toFloat(self): return Float(self.numerator) / Float(self.denominator)