Java units of addition and subtraction of a measurement library that return incorrect values

I am using the reference implementation of JSR363. I have tried many variations of this, but I will give this code as an example.

ServiceProvider provider = ServiceProvider.current();
QuantityFactory<Length> lengthFactory = provider.getQuantityFactory(Length.class);
Quantity<Length> first = lengthFactory.create(5, Units.METRE.divide(100.0));
Quantity<Length> second = lengthFactory.create(3, Units.METRE);
System.out.println(second.add(first));

It will print 503.0 m. It is clear that something is very wrong, and it should be 3.05 m. It is very difficult for me to believe that this is actually a mistake with the library, and I hope someone will tell me what am I missing.

+4
source share
4 answers

Having studied this a little, I was able to reproduce these oddities. It seems that using methods multiply()or divide()when passing Unitto a QuantityFactory file has strange effects. In the example:

Quantity firstQuant = quantFactory.create(10.0,Units.METRE)
Quantity secondQuant = quantFactory.create(20.0,Units.METRE.divide(10.0))
System.out.println(secondQuant.add(firstQuant))

: 20.5 dm. MetricPrefix, , -, , , , Units. :

Quantity secondQuant = quantFactory.create(20.0,MetricPrefix.KILO(Units.METRE))

10020.0 km, . , :

Quantity firstQuant = quantFactory.create(10.0,Units.METRE)
Quantity secondQuant = quantFactory.create(20.0,Units.METRE)
System.out.println(secondQuant.divide(10.0).add(firstQuant))

12.0 m, , , .

, Quantity getConverter() MetricPrefix.

Quantities Quantities.getQuantities()

+3

, Beryllium, . .

, doubleValue(Unit<Q>) of NumberQuantity, , . OP, .

factory NumberQuantity, . , DoubleQuantity, . , Quantities.getQuantities(<value>, <unit>). , NumberQuantity, factory, DoubleQuantity:

package test.jsciunits;

import javax.measure.spi.ServiceProvider;
import javax.measure.Quantity;
import javax.measure.quantity.Length;
import javax.measure.spi.QuantityFactory;
import tec.units.ri.quantity.Quantities;
import static tec.units.ri.unit.Units.*;
import static tec.units.ri.unit.MetricPrefix.*;

public class JScienceUnits {
    public static void main(String[] args) {
        ServiceProvider provider = ServiceProvider.current();
        QuantityFactory<Length> lengthFactory = provider.getQuantityFactory(Length.class);

        Quantity<Length> q = lengthFactory.create(5.0, METRE);
        Quantity<Length> r = Quantities.getQuantity(5.0,  METRE);

        System.out.println("q = " + q + ", q.to(CENTI(METRE)) = " + q.to(CENTI(METRE)));
        System.out.println("r = " + r + ", r.to(CENTI(METRE)) = " + r.to(CENTI(METRE)));
    }
}

q = 5.0 m, q.to(CENTI(METRE)) = 0.05 cm
r = 5.0 m, r.to(CENTI(METRE)) = 500.0 cm

.

+2

, .

, NumberQuantity ( ). , , , RI.

,

+1

Fixed with release 1.0.1 of JSR 363 RI.

+1
source

Source: https://habr.com/ru/post/1655926/


All Articles