Comparing floating point numbers

    private final static Complex ZERO = new Complex(0.0, 0.0);
    
    public void testMultiplicationByZero() {
        
        Complex result = z.multiply(ZERO);
        double tolerance = 0.0;
        assertEquals("Multiplication by zero failed in real part", 
          0.0, result.getRealPart(), tolerance);
        assertEquals("Multiplication by zero failed in imaginary part", 
          0.0, result.getImaginaryPart(), tolerance);
        
    }

As usual, fix the code after the test fails:

    public Complex multiply(Complex z) {
        return new Complex(
          this.real*z.real - this.imaginary * z.imaginary,
          this.real*z.imaginary + this.imaginary * z.real);
    }

Previous | Next | Top | Cafe au Lait

Copyright 2005 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified December 10, 2005