def test_sqrt(self): a = Complex(3,2) a = sqrt(a) b = complex(3,2) b = cmath.sqrt(b) self.assertEqual(a.re,b.real) self.assertEqual(a.im,b.imag) a = Complex(-3,-2) a = sqrt(a) b = complex(-3,-2) b = cmath.sqrt(b) self.assertEqual(a.re,b.real) self.assertEqual(a.im,b.imag) a = Complex(3,0) a = sqrt(a) b = complex(3,0) b = cmath.sqrt(b) self.assertEqual(a.re,b.real) self.assertEqual(a.im,b.imag) a = Complex(0,3) a = sqrt(a) a.re = round(a.re,2) a.im = round(a.im,2) b = complex(0,3) b = cmath.sqrt(b) breal = round(b.real,2) bimag = round(b.imag,2) self.assertEqual(a.re,breal) self.assertEqual(a.im,bimag)
def sqrt_check(): tests = 1000 r = 100 int_fail = 0 float_fail = 0 complex_fail = 0 print('### Square Root Checks ({} tests) ###'.format(tests)) for i in range(tests): num = random.randint(-r, r) a = sqrt(num) b = mathsqrt(num) # print(num, a, b) if isinstance(a, Complex): re_diff = abs(a.re - b.real) im_diff = abs(a.im - b.imag) if re_diff > 1e-8 or im_diff > 1e-8: int_fail += 1 else: diff = abs(a-b) if diff > 1e-8: int_fail += 1 for i in range(tests): num = random.randint(-r, r) + random.random() a = sqrt(num) b = mathsqrt(num) # print(num, a, b) if isinstance(a, Complex): re_diff = abs(a.re - b.real) im_diff = abs(a.im - b.imag) if re_diff > 1e-8 or im_diff > 1e-8: float_fail += 1 else: diff = abs(a - b) if diff > 1e-8: float_fail += 1 for i in range(tests): re = random.randint(-r, r) im = random.randint(-r, r) #print(re,im) a = sqrt(Complex(re, im)) b = mathsqrt(complex(re, im)) re_diff = abs(a.re - b.real) im_diff = abs(a.im - b.imag) if re_diff > 1e-8 or im_diff > 1e-8: complex_fail += 1 return 'Number of times square root of an integer resulted in a difference: {} \n\ Number of times square root of a float resulted in a difference: {} \n\ Number of times square root of a complex resulted in a difference: {}'.format(int_fail, float_fail, complex_fail)
def roots(self): D = self.b * self.b - 4 * self.a * self.c if D > 0: x1 = (-1 * self.b + sqrt(D)) / (2 * self.a) x2 = (-1 * self.b - sqrt(D)) / (2 * self.a) return [x1.__str__(), x2.__str__()] elif D == 0: return -1 * self.b / (2 * self.a) else: return None
def roots(coeff): if isinstance(coeff, list) == 0: raise TypeError('Input must be a list of length 3') else: pass a = coeff[0] b = coeff[1] c = coeff[2] x1 = -b/(2*a) + sqrt(b**2 - 4*a*c)/(2*a) x2 = -b/(2*a) - sqrt(b**2 - 4*a*c)/(2*a) roots = (x1, x2) return roots
def test_sqrt(): truth = 0 falseth = 0 for i in range(-10,10): for j in range(-10, 10): try: test_0 = sqrt(Complex(i, j)) c = cmath.sqrt(complex(i, j)) if test_0.re == c.real and test_0.im == c.imag: truth += 1 else: falseth += 1 except ZeroDivisionError: pass if falseth > 0: print('Failed square root test {} of 100...'.format(abs(i*j))) else: print('Passed {} random square root tests...'.format(abs(i*j)))