user722326
user722326

Reputation: 11

Assertion error

I have written(shown below) a method getCelsius to convert from Fahrenheit to Celsius but when I run the program it shows me an assertion error.

Code:

Method in class Temperature:

public double getCelsius() {

        double c = 0;
        c =  ((this.temp_value - 32) * (5 / 9));
        return c;
    }

and here is the method call in class TestTemperature, which gives me an assertion error:

Temperature t = new Temperature(212.0, "F");

assert t.getCelsius() == 100.0;  // < error in this line

Help!

Upvotes: 1

Views: 2821

Answers (3)

irreputable
irreputable

Reputation: 45463

well, if you want it that way

// will return "exact" value if input is 212.0 or 32.0
double f2c(double f)
{
    return  (f-32.0)/(212.0-32.0) * 100.0;
}

assert f2c(212.0)==100.0 ;  // true!
assert f2c( 32.0)==  0.0 ;  // true!

more generally, if we have two end points (x1,y1) and (x2,y2), this linear interpolation

y = (x-x2)/(x1-x2) * y1 + (x-x1)/(x2-x1) * y2 

will evaluate "exactly" to y1 at x=x1, and y2 at x=x2. Valid for double/float/int/short/byte

Upvotes: 0

sjr
sjr

Reputation: 9895

There are a couple problems: firstly, the 5 / 9 part is using integer division, so it will return 0 all the time. You need to change 5 / 9 to 5f / 9 or something similar.

Secondly (212f - 32) * (5f / 9) is not exactly 100.0: it's hard to do floating point comparison because not all values that you can write in Java are exactly representable in IEEE754 floating point numbers. So you should compare the two numbers like this: assert Math.abs(t.getCelsius() - expected) < 0.000001 or some other desired maximum difference.

Upvotes: 7

Mitch Wheat
Mitch Wheat

Reputation: 300837

You need to take into account precision/representation. i.e. perform your test like so:

assert Abs(t.getCelsius() - 100.0) < epsilon;

where epsilon is your tolerance (say, 0.000001)

You should very rarely use exact equality comparison when dealing with floating point quantities; use a tolerance instead.

Also, write your conversion factor to use floating point arithmetic:

    c =  ((this.temp_value - 32) * (5.0 / 9));

Upvotes: 0

Related Questions