unitsofmeasurement / indriya

JSR 385 - Reference Implementation
Other
119 stars 42 forks source link

1 °C + 1 °C = 275.15 °C ? #321

Closed gilles-gosuin closed 3 years ago

gilles-gosuin commented 3 years ago

I'm not sure I understand correctly what I just discovered, maybe you can help me...

The following test:

@Test
fun `celsius calculations are correct`() {
    val q1 = NumberQuantity.parse("1 ℃") as Quantity<Temperature>
    val q2 = NumberQuantity.parse("1 ℃") as Quantity<Temperature>
    val result = q1.add(q2)
    assertThat(result.unit).isEqualTo(Units.CELSIUS)
    assertThat(result.value).isEqualTo(2)
}

fails with:

org.opentest4j.AssertionFailedError: 
Expecting:
 <275.15>
to be equal to:
 <2>
but was not.
Expected :2
Actual   :275.15

My environment:

$ sw_vers
ProductName:    macOS
ProductVersion: 11.1
BuildVersion:   20C69

$ java -version
openjdk version "15.0.1" 2020-10-20
OpenJDK Runtime Environment (build 15.0.1+9-18)
OpenJDK 64-Bit Server VM (build 15.0.1+9-18, mixed mode, sharing)

Please find attached the fully functional Gradle project containing this test case, for your convenience: indryia-bug-report.zip

andi-huber commented 3 years ago

When adding 2 quantities of Celsius the library needs to know how to interpret these: Quantities can be of scale RELATIVE or ABSOLUTE, while if not explicitly specified the default is ABSOLUTE.

See these tests for the various combinations, and in particular the test addingRelativeTemperatures, which maps onto your usecase: https://github.com/unitsofmeasurement/indriya/blob/master/src/test/java/tech/units/indriya/quantity/TemperatureTest.java

(So in your case you likely want to declare both q1 and q2 with scale RELATIVE.)

andi-huber commented 3 years ago

Feel free to close this issue, if you think your question is sufficiently answered.

gilles-gosuin commented 3 years ago

Thanks for this quick reply!

As the API documentation mentions, this is hugely unintuitive. So much so that I actually didn't bother reading it (and definitely should have).

keilw commented 3 years ago

It may seem unintuitive, but it's thermodynamically correct, also see https://physics.stackexchange.com/questions/132720/how-do-you-add-temperatures or https://reference.wolfram.com/language/tutorial/TemperatureUnits.html or the JavaDoc of Quantity.